pax_global_header00006660000000000000000000000064142064724760014526gustar00rootroot0000000000000052 comment=45223a8dad15fa03e1c18b87d563ec394435f372 golang-github-networkplumbing-go-nft-0.2.0/000077500000000000000000000000001420647247600206715ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/.github/000077500000000000000000000000001420647247600222315ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/.github/workflows/000077500000000000000000000000001420647247600242665ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/.github/workflows/codeql-analysis.yml000066400000000000000000000046071420647247600301100ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ main ] pull_request: # The branches below must be a subset of the branches above branches: [ main ] schedule: - cron: '34 0 * * 3' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'go' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # Learn more: # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - name: Checkout repository uses: actions/checkout@v2 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v1 # â„šī¸ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 golang-github-networkplumbing-go-nft-0.2.0/.github/workflows/main.yml000066400000000000000000000014721420647247600257410ustar00rootroot00000000000000name: Go on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.16 - name: Install nftable headers run: sudo apt-get install libnftables-dev - name: Format Check run: ./automation/run-tests.sh --fmt - name: Build run: ./automation/run-tests.sh --build - name: Run Unit Tests run: ./automation/run-tests.sh --unit-test integration-tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Start Docker Service run: sudo service docker start - name: Run Integration Tests run: ./automation/run-tests.sh --integration-test golang-github-networkplumbing-go-nft-0.2.0/.gitignore000066400000000000000000000002211420647247600226540ustar00rootroot00000000000000# IDE metadata .idea # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out golang-github-networkplumbing-go-nft-0.2.0/CHANGELOG000066400000000000000000000014141420647247600221030ustar00rootroot00000000000000# Changelog ## [0.2.0] - 2021-09-13 ### New Features - Add support to link with libnftables using CGO. In order to use the lib backend, libnftables devel headers needs to be installed on the build machine. - Support NAT statements: dnat, snat, masquerade, redirect. - Support anonymous counter statement. ### Bug Fixes - When calling the `nft` binary, pass the nftables configuration through a temp file instead of a buffer. This is a workaround to the SELinux policy issue: https://github.com/containers/container-selinux/issues/147 ## [0.1.1] - 2021-06-29 ### Breaking Changes - Move the repo to the networkplumbing organization. Consume go-nft by importing `github.com/networkplumbing/go-nft/nft` ## [0.1.0] - 2021-06-29 ### New Features - Initial release. golang-github-networkplumbing-go-nft-0.2.0/CODE_OF_CONDUCT.md000066400000000000000000000060431420647247600234730ustar00rootroot00000000000000 # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Edward Haas at edwardh.dev-at-gmail-com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4. golang-github-networkplumbing-go-nft-0.2.0/CONTRIBUTING.md000066400000000000000000000053621420647247600231300ustar00rootroot00000000000000# How to Contribute CNI is [Apache 2.0 licensed](LICENSE) and accepts contributions via GitHub pull requests. This document outlines some of the conventions on development workflow, commit message formatting, contact points and other resources to make it easier to get your contribution accepted. We gratefully welcome improvements to documentation as well as to code. # Certificate of Origin By contributing to this project you agree to the Developer Certificate of Origin (DCO). This document was created by the Linux Kernel community and is a simple statement that you, as a contributor, have the legal right to make the contribution. See the [DCO](DCO) file for details. ## Contribution workflow This is a rough outline of how to prepare a contribution: - Create a topic branch from where you want to base your work (usually branched from main). - Make commits of logical units. - Make sure your commit messages are in the proper format (see below). - Push your changes to a topic branch in your fork of the repository. - If you changed code: - Add unit and integration tests to cover your changes (see existing tests for style). - Run all the test and ensure they pass. - Make sure any new code files have a license header. - Submit a pull request to the original repository. - Examine the check results on the PR. All required checks should pass. ## How to run the test suite We generally require test coverage of any new features or bug fixes. Unit test should not require any dependencies and may run on any platform. Integration tests depend on nftables and require a Linux platform with nftable support in the kernel and the `nft` executable. To run the unit-tests, use this command from the project root: ```bash ./autmation/run-tests.sh --unit-test ``` To run the integration-tests, use this command from the project root: ```bash ./autmation/run-tests.sh --integration-test ``` ## Help utilities In order to help resolve the formatting checks, developers can use the provided `./automation/go-format.sh` script to format inline the code. # Acceptance policy The following points will make a PR more likely to be accepted: - A well-described requirement. - Tests for new code. - Tests for old code! - A good commit message (see below). In general, we will merge a PR once at least one maintainer has endorsed it. For substantial changes, more people may become involved, and you might get asked to resubmit the PR or divide the changes into more than one PR/commit. ### Format of the Commit Message We follow a rough convention for commit messages that is designed to answer two questions: what changed and why. The subject line should feature the what and the body of the commit should describe the why. See https://chris.beams.io/posts/git-commit . golang-github-networkplumbing-go-nft-0.2.0/LICENSE000066400000000000000000000261351420647247600217050ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. golang-github-networkplumbing-go-nft-0.2.0/README.md000066400000000000000000000026171420647247600221560ustar00rootroot00000000000000# go-nft [![Licensed under Apache License version 2.0](https://img.shields.io/github/license/kubevirt/kubevirt.svg)](https://www.apache.org/licenses/LICENSE-2.0) [![Build Workflow](https://github.com/networkplumbing/go-nft/actions/workflows/main.yml/badge.svg)](https://github.com/networkplumbing/go-nft/actions/workflows/main.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/networkplumbing/go-nft)](https://goreportcard.com/report/github.com/networkplumbing/go-nft) Go bindings for nft utility. go-nft wraps invocation of the nft utility with functions to append and delete rules; create, clear and delete tables and chains. ## To start using go-nft go-nft is a library that provides a structured API to nftables. go-nft uses the [libnftables-json specification](https://www.mankier.com/5/libnftables-json) and exposes a subset of its structures. - Apply the configuration: ```golang config := nft.NewConfig() config.AddTable(nft.NewTable("mytable", nft.FamilyIP)) err := nft.ApplyConfig(config) ``` - Read the configuration: ```golang config, err := nft.ReadConfig() nftVersion := config.Nftables[0].Metainfo.Version ``` For full setup example, see the integration test [examples](tests/example_test.go). ## Contribution We welcome contribution of any kind! Read [CONTRIBUTING](CONTRIBUTING.md) to learn how to contribute to the project. ## Changelog Please refer to [CHANGELOG](CHANGELOG) golang-github-networkplumbing-go-nft-0.2.0/README.release.md000066400000000000000000000023171420647247600235720ustar00rootroot00000000000000# Creating a New Release ## Changelog - [ ] Update the CHANGELOG file in the project root directory. Use `git log --oneline v0.1.0..HEAD` to get the changes since the last tag. Pick the most important changes, especially user facing ones. The following format should be used when adding an entry: ``` ## [X.Y.Z] - YYYY-MM-DD ### Breaking Changes - ... ### New Features - ... ### Bug Fixes - ... ``` ## Tagging - [ ] Tag new release in git. ```bash # Make sure your local git repo is sync with upstream. # The whole version string should log like `v0.1.0`. # For the commit message use the following format: `go-nft 0.1.0 release`. git tag --sign v git push upstream --tags ``` - [ ] In case there is a need to remove a tag: ```bash # Remove local tag git tag -d # Remove upstream tag git push --delete upstream ``` ## GitHub Release - [ ] Visit [github draft release page][1]. - [ ] Make sure you are in `Release` tab. - [ ] Choose the git tag just pushed. - [ ] Set title with the following format: `Version 0.1.0 release`. - [ ] The content should be copied from the `CHANGELOG` file. - [ ] Click `Save draft` and seek for review. - [ ] Click `Publish release` once approved. golang-github-networkplumbing-go-nft-0.2.0/automation/000077500000000000000000000000001420647247600230515ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/automation/go-format.sh000077500000000000000000000002341420647247600253020ustar00rootroot00000000000000#!/usr/bin/env bash set -e gofmt -l -w ./nft ./tests go run golang.org/x/tools/cmd/goimports -l --local "github.com/networkplumbing/go-nft" ./nft ./tests golang-github-networkplumbing-go-nft-0.2.0/automation/run-tests.sh000077500000000000000000000043721420647247600253620ustar00rootroot00000000000000#!/usr/bin/env bash set -e EXEC_PATH=$(dirname "$(realpath "$0")") PROJECT_PATH="$(dirname $EXEC_PATH)" CONTAINER_WORKSPACE="/workspace/go-nft" : "${CONTAINER_CMD:="docker"}" : "${CONTAINER_IMG:="golang:1.16.4-alpine3.13"}" : "${DISABLE_IPV6_IN_CONTAINER:=0}" test -t 1 && USE_TTY="-t" options=$(getopt --options "" \ --long build,fmt,unit-test,integration-test,help\ -- "${@}") eval set -- "$options" while true; do case "$1" in --build) OPT_BUILD=1 ;; --fmt) OPT_FMT=1 ;; --unit-test) OPT_UTEST=1 ;; --integration-test) OPT_ITEST=1 ;; --help) set +x echo "$0 [--build] [--fmt] [--unit-test] [--integration-test]" exit ;; --) shift break ;; esac shift done function run_container { ${CONTAINER_CMD} run \ $USE_TTY \ -i \ --rm \ --cap-add=NET_ADMIN \ --cap-add=NET_RAW \ --sysctl net.ipv6.conf.all.disable_ipv6=$DISABLE_IPV6_IN_CONTAINER \ -v "$PROJECT_PATH":"$CONTAINER_WORKSPACE":Z \ -w "$CONTAINER_WORKSPACE" \ "$CONTAINER_IMG" \ sh -e -c "$1" } if [ -z "${OPT_BUILD}" ] && [ -z "${OPT_FMT}" ] && [ -z "${OPT_UTEST}" ] && [ -z "${OPT_ITEST}" ]; then OPT_BUILD=1 OPT_FMT=1 OPT_UTEST=1 OPT_ITEST=1 fi if [ -n "${OPT_BUILD}" ]; then go build -v ./... fi if [ -n "${OPT_FMT}" ]; then unformatted=$(gofmt -l ./nft ./tests) test -z "$unformatted" || (echo "Unformatted: $unformatted" && false) unformatted=$(go run golang.org/x/tools/cmd/goimports -l --local "github.com/networkplumbing/go-nft" ./nft ./tests) test -z "$unformatted" || (echo "Unformatted imports: $unformatted" && false) fi if [ -n "${OPT_UTEST}" ]; then go test -v ./nft/... fi if [ -n "${OPT_ITEST}" ]; then # Manually load `nft_masq` kmod on the host to support NAT definitions. # The container is unable to load a kmod (usually done by `nft` automatically). sudo modprobe nft_masq run_container ' apk add --no-cache nftables gcc musl-dev nft -j list ruleset go test -v --tags=exec ./tests/... apk add --no-cache nftables-dev go test -v ./tests/nftlib ' fi golang-github-networkplumbing-go-nft-0.2.0/go.mod000066400000000000000000000002121420647247600217720ustar00rootroot00000000000000module github.com/networkplumbing/go-nft go 1.16 require ( github.com/stretchr/testify v1.7.0 golang.org/x/tools v0.1.4 // indirect ) golang-github-networkplumbing-go-nft-0.2.0/go.sum000066400000000000000000000072241420647247600220310ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.4 h1:cVngSRcfgyZCzys3KYOpCFa+4dqX/Oub9tAq00ttGVs= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-github-networkplumbing-go-nft-0.2.0/nft/000077500000000000000000000000001420647247600214605ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/nft/chain.go000066400000000000000000000042231420647247600230720ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package nft import ( "github.com/networkplumbing/go-nft/nft/schema" ) type ChainType string type ChainHook string type ChainPolicy string // Chain Types const ( TypeFilter ChainType = schema.TypeFilter TypeNAT ChainType = schema.TypeNAT TypeRoute ChainType = schema.TypeRoute ) // Chain Hooks const ( HookPreRouting ChainHook = schema.HookPreRouting HookInput ChainHook = schema.HookInput HookOutput ChainHook = schema.HookOutput HookForward ChainHook = schema.HookForward HookPostRouting ChainHook = schema.HookPostRouting HookIngress ChainHook = schema.HookIngress ) // Chain Policies const ( PolicyAccept ChainPolicy = schema.PolicyAccept PolicyDrop ChainPolicy = schema.PolicyDrop ) // NewRegularChain returns a new schema chain structure for a regular chain. func NewRegularChain(table *schema.Table, name string) *schema.Chain { return NewChain(table, name, nil, nil, nil, nil) } // NewChain returns a new schema chain structure for a base chain. // For base chains, all arguments are required except the policy. // Missing arguments will cause an error once the config is applied. func NewChain(table *schema.Table, name string, ctype *ChainType, hook *ChainHook, prio *int, policy *ChainPolicy) *schema.Chain { c := &schema.Chain{ Family: table.Family, Table: table.Name, Name: name, } if ctype != nil { c.Type = string(*ctype) } if hook != nil { c.Hook = string(*hook) } if prio != nil { c.Prio = prio } if policy != nil { c.Policy = string(*policy) } return c } golang-github-networkplumbing-go-nft-0.2.0/nft/config.go000066400000000000000000000026511420647247600232600ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package nft import ( nftconfig "github.com/networkplumbing/go-nft/nft/config" nftexec "github.com/networkplumbing/go-nft/nft/exec" ) type Config = nftconfig.Config // NewConfig returns a new nftables config structure. func NewConfig() *nftconfig.Config { return nftconfig.New() } // ReadConfig loads the nftables configuration from the system and // returns it as a nftables config structure. // The system is expected to have the `nft` executable deployed and nftables enabled in the kernel. func ReadConfig() (*Config, error) { return nftexec.ReadConfig() } // ApplyConfig applies the given nftables config on the system. // The system is expected to have the `nft` executable deployed and nftables enabled in the kernel. func ApplyConfig(c *Config) error { return nftexec.ApplyConfig(c) } golang-github-networkplumbing-go-nft-0.2.0/nft/config/000077500000000000000000000000001420647247600227255ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/nft/config/chain.go000066400000000000000000000054121420647247600243400ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config import ( "github.com/networkplumbing/go-nft/nft/schema" ) // AddChain appends the given chain to the nftable config. // The chain is added without an explicit action (`add`). // Adding multiple times the same chain has no affect when the config is applied. func (c *Config) AddChain(chain *schema.Chain) { nftable := schema.Nftable{Chain: chain} c.Nftables = append(c.Nftables, nftable) } // DeleteChain appends a given chain to the nftable config // with the `delete` action. // Attempting to delete a non-existing chain, results with a failure when the config is applied. // The chain must not contain any rules or be used as a jump target. func (c *Config) DeleteChain(chain *schema.Chain) { nftable := schema.Nftable{Delete: &schema.Objects{Chain: chain}} c.Nftables = append(c.Nftables, nftable) } // FlushChain appends a given chain to the nftable config // with the `flush` action. // All rules under the chain are removed (when applied). // Attempting to flush a non-existing chain, results with a failure when the config is applied. func (c *Config) FlushChain(chain *schema.Chain) { nftable := schema.Nftable{Flush: &schema.Objects{Chain: chain}} c.Nftables = append(c.Nftables, nftable) } // LookupChain searches the configuration for a matching chain and returns it. // The chain is matched first by the table and chain name. // Other matching fields are optional (for matching base chains). // Mutating the returned chain will result in mutating the configuration. func (c *Config) LookupChain(toFind *schema.Chain) *schema.Chain { for _, nftable := range c.Nftables { if chain := nftable.Chain; chain != nil { match := chain.Table == toFind.Table && chain.Family == toFind.Family && chain.Name == toFind.Name if match { if t := toFind.Type; t != "" { match = match && chain.Type == t } if h := toFind.Hook; h != "" { match = match && chain.Hook == h } if p := toFind.Prio; p != nil { match = match && chain.Prio != nil && *chain.Prio == *p } if p := toFind.Policy; p != "" { match = match && chain.Policy == p } if match { return chain } } } } return nil } golang-github-networkplumbing-go-nft-0.2.0/nft/config/chain_test.go000066400000000000000000000121421420647247600253750ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config_test import ( "fmt" "strings" "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) type chainAction string type chainActionFunc func(*nft.Config, *schema.Chain) // Chain Actions const ( chainADD chainAction = "add" chainDELETE chainAction = "delete" chainFLUSH chainAction = "flush" ) const chainName = "test-chain" func TestChain(t *testing.T) { testAddBaseChains(t) // Removal of base-chains is identical to the removal of regular-chains. // Therefore, such scenarios are evaluated through the regular-chains actions testRegularChainsActions(t) testChainLookup(t) } func testAddBaseChains(t *testing.T) { types := []nft.ChainType{ nft.TypeFilter, nft.TypeNAT, nft.TypeRoute, } hooks := []nft.ChainHook{ nft.HookPreRouting, nft.HookInput, nft.HookOutput, nft.HookForward, nft.HookPostRouting, nft.HookIngress, } policies := []nft.ChainPolicy{ nft.PolicyAccept, nft.PolicyDrop, "", } table := nft.NewTable(tableName, nft.FamilyIP) for _, ctype := range types { for _, hook := range hooks { for _, policy := range policies { testName := createChainTestName(chainADD, ctype, hook, policy) t.Run(testName, func(t *testing.T) { priority := 100 chain := nft.NewChain(table, chainName, &ctype, &hook, &priority, &policy) config := nft.NewConfig() config.AddChain(chain) serializedConfig, err := config.ToJSON() assert.NoError(t, err) chainArgs := fmt.Sprintf( `"family":%q,"table":%q,"name":%q,"type":%q,"hook":%q,"prio":%d`, table.Family, table.Name, chainName, ctype, hook, priority, ) if policy != "" { chainArgs += fmt.Sprintf(`,"policy":%q`, policy) } expected := []byte(fmt.Sprintf(`{"nftables":[{"chain":{%s}}]}`, chainArgs)) assert.Equal(t, string(expected), string(serializedConfig)) }) } } } } func testRegularChainsActions(t *testing.T) { actions := map[chainAction]chainActionFunc{ chainADD: func(c *nft.Config, chain *schema.Chain) { c.AddChain(chain) }, chainDELETE: func(c *nft.Config, chain *schema.Chain) { c.DeleteChain(chain) }, chainFLUSH: func(c *nft.Config, chain *schema.Chain) { c.FlushChain(chain) }, } table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) for action, actionFunc := range actions { testName := createChainTestName(action, "", "", "") t.Run(testName, func(t *testing.T) { config := nft.NewConfig() actionFunc(config, chain) serializedConfig, err := config.ToJSON() assert.NoError(t, err) chainArgs := fmt.Sprintf(`"family":%q,"table":%q,"name":%q`, table.Family, table.Name, chainName) var expected []byte if action == chainADD { expected = []byte(fmt.Sprintf(`{"nftables":[{"chain":{%s}}]}`, chainArgs)) } else { expected = []byte(fmt.Sprintf(`{"nftables":[{%q:{"chain":{%s}}}]}`, action, chainArgs)) } assert.Equal(t, string(expected), string(serializedConfig)) }) } } func createChainTestName(action chainAction, ctype nft.ChainType, hook nft.ChainHook, policy nft.ChainPolicy) string { args := []string{string(action)} if ctype != "" { args = append(args, string(ctype)) } if hook != "" { args = append(args, string(hook)) } if policy != "" { args = append(args, string(policy)) } return strings.Join(args, " ") } func testChainLookup(t *testing.T) { config := nft.NewConfig() table_br := nft.NewTable("table-br", nft.FamilyBridge) config.AddTable(table_br) chainRegular := nft.NewRegularChain(table_br, "chain-regular") config.AddChain(chainRegular) ctype, hook, prio, policy := nft.TypeFilter, nft.HookPreRouting, 100, nft.PolicyAccept chainBase := nft.NewChain(table_br, "chain-base", &ctype, &hook, &prio, &policy) config.AddChain(chainBase) t.Run("Lookup an existing regular chain", func(t *testing.T) { chain := config.LookupChain(chainRegular) assert.Equal(t, chainRegular, chain) }) t.Run("Lookup an existing base chain", func(t *testing.T) { chain := config.LookupChain(chainBase) assert.Equal(t, chainBase, chain) }) t.Run("Lookup a missing regular chain", func(t *testing.T) { chain := nft.NewRegularChain(table_br, "chain-na") assert.Nil(t, config.LookupChain(chain)) }) t.Run("Lookup a missing base chain", func(t *testing.T) { inputHook := nft.HookInput chain := nft.NewChain(table_br, "chain-base", &ctype, &inputHook, &prio, &policy) assert.Nil(t, config.LookupChain(chain)) }) } golang-github-networkplumbing-go-nft-0.2.0/nft/config/config.go000066400000000000000000000033501420647247600245220ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config import ( "encoding/json" "github.com/networkplumbing/go-nft/nft/schema" ) type Config struct { schema.Root } // New returns a new nftables config structure. func New() *Config { c := &Config{} c.Nftables = []schema.Nftable{} return c } // ToJSON returns the JSON encoding of the nftables config. func (c *Config) ToJSON() ([]byte, error) { return json.Marshal(*c) } // FromJSON decodes the provided JSON-encoded data and populates the nftables config. func (c *Config) FromJSON(data []byte) error { if err := json.Unmarshal(data, c); err != nil { return err } return nil } // FlushRuleset adds a command to the nftables config that erases all the configuration when applied. // It is commonly used as the first config instruction, followed by a declarative configuration. // When used, any previous configuration is flushed away before adding the new one. // Calling FlushRuleset updates the configuration and will take effect only // when applied on the system. func (c *Config) FlushRuleset() { c.Nftables = append(c.Nftables, schema.Nftable{Flush: &schema.Objects{Ruleset: true}}) } golang-github-networkplumbing-go-nft-0.2.0/nft/config/config_test.go000066400000000000000000000040041420647247600255560ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config_test import ( "fmt" "testing" assert "github.com/stretchr/testify/require" nftconfig "github.com/networkplumbing/go-nft/nft/config" "github.com/networkplumbing/go-nft/nft/schema" ) func TestDefineEmptyConfig(t *testing.T) { config := nftconfig.New() expected := []byte(`{"nftables":[]}`) serializedConfig, err := config.ToJSON() assert.NoError(t, err) assert.Equal(t, string(expected), string(serializedConfig)) } func TestReadEmptyConfigWithMetaInfo(t *testing.T) { const version = "0.9.3" const releaseName = "Topsy" const schemaVersion = 1 serializedConfig := []byte(fmt.Sprintf( `{"nftables":[{"metainfo":{"version":%q,"release_name":%q,"json_schema_version":%d}}]}`, version, releaseName, schemaVersion, )) config := nftconfig.New() assert.NoError(t, config.FromJSON(serializedConfig)) expectedConfig := nftconfig.New() expectedConfig.Nftables = append(expectedConfig.Nftables, schema.Nftable{Metainfo: &schema.Metainfo{ Version: version, ReleaseName: releaseName, JsonSchemaVersion: schemaVersion, }}) assert.Equal(t, expectedConfig, config) } func TestFlushRuleset(t *testing.T) { config := nftconfig.New() config.FlushRuleset() expected := []byte(`{"nftables":[{"flush":{"ruleset":null}}]}`) serializedConfig, err := config.ToJSON() assert.NoError(t, err) assert.Equal(t, string(expected), string(serializedConfig)) } golang-github-networkplumbing-go-nft-0.2.0/nft/config/rule.go000066400000000000000000000061361420647247600242310ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config import ( "bytes" "encoding/json" "github.com/networkplumbing/go-nft/nft/schema" ) // AddRule appends the given rule to the nftable config. // The rule is added without an explicit action (`add`). // Adding multiple times the same rule will result in multiple identical rules when applied. func (c *Config) AddRule(rule *schema.Rule) { nftable := schema.Nftable{Rule: rule} c.Nftables = append(c.Nftables, nftable) } // DeleteRule appends a given rule to the nftable config // with the `delete` action. // A rule is identified by its handle ID and it must be present in the given rule. // Attempting to delete a non-existing rule, results with a failure when the config is applied. // A common usage is to use LookupRule() and then to pass the result to DeleteRule. func (c *Config) DeleteRule(rule *schema.Rule) { nftable := schema.Nftable{Delete: &schema.Objects{Rule: rule}} c.Nftables = append(c.Nftables, nftable) } // LookupRule searches the configuration for a matching rule and returns it. // The rule is matched first by the table and chain. // Other matching fields are optional (nil or an empty string arguments imply no-matching). // Mutating the returned chain will result in mutating the configuration. func (c *Config) LookupRule(toFind *schema.Rule) []*schema.Rule { var rules []*schema.Rule for _, nftable := range c.Nftables { if r := nftable.Rule; r != nil { match := r.Table == toFind.Table && r.Family == toFind.Family && r.Chain == toFind.Chain if match { if h := toFind.Handle; h != nil { match = match && r.Handle != nil && *r.Handle == *h } if i := toFind.Index; i != nil { match = match && r.Index != nil && *r.Index == *i } if co := toFind.Comment; co != "" { match = match && r.Comment == co } if toFindStatements := toFind.Expr; toFindStatements != nil { if match = match && len(toFindStatements) == len(r.Expr); match { for i, toFindStatement := range toFindStatements { equal, err := areStatementsEqual(toFindStatement, r.Expr[i]) match = match && err == nil && equal } } } if match { rules = append(rules, r) } } } } return rules } func areStatementsEqual(statementA, statementB schema.Statement) (bool, error) { statementARow, err := json.Marshal(statementA) if err != nil { return false, err } statementBRow, err := json.Marshal(statementB) if err != nil { return false, err } return bytes.Equal(statementARow, statementBRow), nil } golang-github-networkplumbing-go-nft-0.2.0/nft/config/rule_test.go000066400000000000000000000403661420647247600252730ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config_test import ( "encoding/json" "fmt" "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) type ruleAction string // Rule Actions const ( ruleADD ruleAction = "add" ruleDELETE ruleAction = "delete" ) func TestRule(t *testing.T) { testAddRuleWithMatchAndVerdict(t) testDeleteRule(t) testAddRuleWithRowExpression(t) testAddRuleWithCounter(t) testAddRuleWithNAT(t) testRuleLookup(t) testReadRuleWithNumericalExpression(t) } func testAddRuleWithRowExpression(t *testing.T) { const comment = "mycomment" table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) t.Run("Add rule with a row expression, check serialization", func(t *testing.T) { statements, serializedStatements := matchWithRowExpression() rule := nft.NewRule(table, chain, statements, nil, nil, comment) config := nft.NewConfig() config.AddRule(rule) serializedConfig, err := config.ToJSON() assert.NoError(t, err) expectedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) assert.Equal(t, string(expectedConfig), string(serializedConfig)) }) t.Run("Add rule with a row expression, check deserialization", func(t *testing.T) { statements, serializedStatements := matchWithRowExpression() serializedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) var deserializedConfig nft.Config assert.NoError(t, json.Unmarshal(serializedConfig, &deserializedConfig)) rule := nft.NewRule(table, chain, statements, nil, nil, comment) expectedConfig := nft.NewConfig() expectedConfig.AddRule(rule) assert.Equal(t, expectedConfig, &deserializedConfig) }) } func testAddRuleWithMatchAndVerdict(t *testing.T) { const comment = "mycomment" table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) t.Run("Add rule with match and verdict, check serialization", func(t *testing.T) { statements, serializedStatements := matchSrcIP4withReturnVerdict() rule := nft.NewRule(table, chain, statements, nil, nil, comment) config := nft.NewConfig() config.AddRule(rule) serializedConfig, err := config.ToJSON() assert.NoError(t, err) expectedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) assert.Equal(t, string(expectedConfig), string(serializedConfig)) }) t.Run("Add rule with match and verdict, check deserialization", func(t *testing.T) { statements, serializedStatements := matchSrcIP4withReturnVerdict() serializedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) var deserializedConfig nft.Config assert.NoError(t, json.Unmarshal(serializedConfig, &deserializedConfig)) rule := nft.NewRule(table, chain, statements, nil, nil, comment) expectedConfig := nft.NewConfig() expectedConfig.AddRule(rule) assert.Equal(t, expectedConfig, &deserializedConfig) }) } func testDeleteRule(t *testing.T) { table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) t.Run("Delete rule", func(t *testing.T) { handleID := 100 rule := nft.NewRule(table, chain, nil, &handleID, nil, "") config := nft.NewConfig() config.DeleteRule(rule) serializedConfig, err := config.ToJSON() assert.NoError(t, err) expectedConfig := buildSerializedConfig(ruleDELETE, "", &handleID, "") assert.Equal(t, string(expectedConfig), string(serializedConfig)) }) } func buildSerializedConfig(action ruleAction, serializedStatements string, handle *int, comment string) []byte { ruleArgs := fmt.Sprintf(`"family":%q,"table":%q,"chain":%q`, nft.FamilyIP, tableName, chainName) if serializedStatements != "" { ruleArgs += "," + serializedStatements } if handle != nil { ruleArgs += fmt.Sprintf(`,"handle":%d`, *handle) } if comment != "" { ruleArgs += fmt.Sprintf(`,"comment":%q`, comment) } var config string if action == ruleADD { config = fmt.Sprintf(`{"nftables":[{"rule":{%s}}]}`, ruleArgs) } else { config = fmt.Sprintf(`{"nftables":[{%q:{"rule":{%s}}}]}`, action, ruleArgs) } return []byte(config) } func matchSrcIP4withReturnVerdict() ([]schema.Statement, string) { ipAddress := "10.10.10.10" matchSrcIP4 := schema.Statement{ Match: &schema.Match{ Op: schema.OperEQ, Left: schema.Expression{ Payload: &schema.Payload{ Protocol: schema.PayloadProtocolIP4, Field: schema.PayloadFieldIPSAddr, }, }, Right: schema.Expression{String: &ipAddress}, }, } verdict := schema.Statement{} verdict.Return = true statements := []schema.Statement{matchSrcIP4, verdict} expectedMatch := fmt.Sprintf( `"match":{"op":"==","left":{"payload":{"protocol":"ip","field":"saddr"}},"right":%q}`, ipAddress, ) expectedVerdict := `"return":null` serializedStatements := fmt.Sprintf(`"expr":[{%s},{%s}]`, expectedMatch, expectedVerdict) return statements, serializedStatements } func matchWithRowExpression() ([]schema.Statement, string) { stringExpression := "string-expression" rowExpression := `{"foo":"boo"}` match := schema.Statement{ Match: &schema.Match{ Op: schema.OperEQ, Left: schema.Expression{RowData: json.RawMessage(rowExpression)}, Right: schema.Expression{String: &stringExpression}, }, } statements := []schema.Statement{match} expectedMatch := fmt.Sprintf(`"match":{"op":"==","left":%s,"right":%q}`, rowExpression, stringExpression) serializedStatements := fmt.Sprintf(`"expr":[{%s}]`, expectedMatch) return statements, serializedStatements } func testRuleLookup(t *testing.T) { config := nft.NewConfig() table_br := nft.NewTable("table-br", nft.FamilyBridge) config.AddTable(table_br) chainRegular := nft.NewRegularChain(table_br, "chain-regular") config.AddChain(chainRegular) ruleSimple := nft.NewRule(table_br, chainRegular, nil, nil, nil, "comment123") config.AddRule(ruleSimple) ruleWithStatement := nft.NewRule(table_br, chainRegular, []schema.Statement{{}}, nil, nil, "comment456") ruleWithStatement.Expr[0].Drop = true config.AddRule(ruleWithStatement) handle := 10 index := 1 ruleWithAllParams := nft.NewRule(table_br, chainRegular, []schema.Statement{{}, {}}, &handle, &index, "comment789") config.AddRule(ruleWithAllParams) t.Run("Lookup an existing rule by table, chain and comment", func(t *testing.T) { rules := config.LookupRule(ruleSimple) assert.Len(t, rules, 1) assert.Equal(t, ruleSimple, rules[0]) }) t.Run("Lookup an existing rule by table, chain, statement and comment", func(t *testing.T) { rules := config.LookupRule(ruleWithStatement) assert.Len(t, rules, 1) assert.Equal(t, ruleWithStatement, rules[0]) }) t.Run("Lookup an existing rule by all (root) parameters", func(t *testing.T) { rules := config.LookupRule(ruleWithAllParams) assert.Len(t, rules, 1) assert.Equal(t, ruleWithAllParams, rules[0]) }) t.Run("Lookup a missing rule (comment not matching)", func(t *testing.T) { rule := nft.NewRule(table_br, chainRegular, nil, nil, nil, "comment-missing") assert.Empty(t, config.LookupRule(rule)) }) t.Run("Lookup a missing rule (statement content not matching)", func(t *testing.T) { rule := nft.NewRule(table_br, chainRegular, []schema.Statement{{}}, nil, nil, "comment456") rule.Expr[0].Drop = false rule.Expr[0].Return = true assert.Empty(t, config.LookupRule(rule)) }) t.Run("Lookup a missing rule (statements count not matching)", func(t *testing.T) { rule := nft.NewRule(table_br, chainRegular, []schema.Statement{{}, {}}, nil, nil, "comment456") rule.Expr[0].Drop = true assert.Empty(t, config.LookupRule(rule)) }) t.Run("Lookup a missing rule (handle not matching)", func(t *testing.T) { changedHandle := 99 rule := nft.NewRule(table_br, chainRegular, []schema.Statement{{}, {}}, &changedHandle, &index, "comment789") assert.Empty(t, config.LookupRule(rule)) }) } func testReadRuleWithNumericalExpression(t *testing.T) { t.Run("Read rule with numerical expression", func(t *testing.T) { c := nft.NewConfig() assert.NoError(t, c.FromJSON([]byte(` {"nftables":[{"rule":{ "expr":[{"match":{"op":"==","left":"foo","right":12345}}] }}]} `))) }) } func testAddRuleWithCounter(t *testing.T) { const comment = "mycomment" table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) statements, serializedStatements := counterStatements() rule := nft.NewRule(table, chain, statements, nil, nil, comment) t.Run("Add rule with counter, check serialization", func(t *testing.T) { config := nft.NewConfig() config.AddRule(rule) serializedConfig, err := config.ToJSON() assert.NoError(t, err) expectedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) assert.JSONEq(t, string(expectedConfig), string(serializedConfig)) }) t.Run("Add rule with counter, check deserialization", func(t *testing.T) { serializedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) var deserializedConfig nft.Config assert.NoError(t, json.Unmarshal(serializedConfig, &deserializedConfig)) expectedConfig := nft.NewConfig() expectedConfig.AddRule(rule) assert.Equal(t, expectedConfig, &deserializedConfig) }) } func counterStatements() ([]schema.Statement, string) { statements := []schema.Statement{{ Counter: &schema.Counter{ Packets: 0, Bytes: 0, }, }} expectedCounter := `"counter":{"packets":0,"bytes":0}` serializedStatements := fmt.Sprintf(`"expr":[{%s}]`, expectedCounter) return statements, serializedStatements } func testAddRuleWithNAT(t *testing.T) { tableTests := []struct { typeName string createStatements func() ([]schema.Statement, string) }{ {"dnat", dNATStatements}, {"snat", sNATStatements}, {"masquerade", masqueradeStatements}, {"redirect", redirectStatements}, } for _, tt := range tableTests { t.Run(fmt.Sprintf("Add rule with %s, check serialization", tt.typeName), func(t *testing.T) { testSerializationWith(t, dNATStatements) }) t.Run(fmt.Sprintf("Add rule with %s, check deserialization", tt.typeName), func(t *testing.T) { testDeserializationWith(t, dNATStatements) }) } } func testSerializationWith(t *testing.T, createStatements func() ([]schema.Statement, string)) { const comment = "mycomment" table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) statements, serializedStatements := createStatements() rule := nft.NewRule(table, chain, statements, nil, nil, comment) config := nft.NewConfig() config.AddRule(rule) serializedConfig, err := config.ToJSON() assert.NoError(t, err) expectedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) assert.Equal(t, string(expectedConfig), string(serializedConfig)) } func testDeserializationWith(t *testing.T, createStatements func() ([]schema.Statement, string)) { const comment = "mycomment" table := nft.NewTable(tableName, nft.FamilyIP) chain := nft.NewRegularChain(table, chainName) statements, serializedStatements := createStatements() serializedConfig := buildSerializedConfig(ruleADD, serializedStatements, nil, comment) var deserializedConfig nft.Config assert.NoError(t, json.Unmarshal(serializedConfig, &deserializedConfig)) rule := nft.NewRule(table, chain, statements, nil, nil, comment) expectedConfig := nft.NewConfig() expectedConfig.AddRule(rule) assert.Equal(t, expectedConfig, &deserializedConfig) } func dNATStatements() ([]schema.Statement, string) { address0 := "1.2.3.4" addressWithFamily := schema.Statement{} familyIP4 := schema.FamilyIP addressWithFamily.Dnat = &schema.Dnat{ Addr: &schema.Expression{String: &address0}, Family: &familyIP4, } portList := schema.Statement{} portList.Dnat = &schema.Dnat{ Port: &schema.Expression{RowData: json.RawMessage(`[80,8080]`)}, } var port float64 = 12345 address1 := "feed::c0fe" fullHouse := schema.Statement{} familyIP6 := schema.FamilyIP6 fullHouse.Dnat = &schema.Dnat{ Addr: &schema.Expression{String: &address1}, Family: &familyIP6, Port: &schema.Expression{Float64: &port}, Flags: &schema.Flags{Flags: []string{schema.NATFlagRandom, schema.NATFlagPersistent}}, } statements := []schema.Statement{addressWithFamily, portList, fullHouse} expectedDNATIP4 := `"dnat":{"addr":"1.2.3.4","family":"ip"}` expectedDNATMultiPorts := `"dnat":{"port":[80,8080]}` expectedDNATIP6PortAndFlags := `"dnat":{"addr":"feed::c0fe","family":"ip6","port":12345,"flags":["random","persistent"]}` serializedStatements := fmt.Sprintf( `"expr":[{%s},{%s},{%s}]`, expectedDNATIP4, expectedDNATMultiPorts, expectedDNATIP6PortAndFlags, ) return statements, serializedStatements } func sNATStatements() ([]schema.Statement, string) { address0 := "1.2.3.4" addressWithFamily := schema.Statement{} familyIP4 := schema.FamilyIP addressWithFamily.Snat = &schema.Snat{ Addr: &schema.Expression{String: &address0}, Family: &familyIP4, } portList := schema.Statement{} portList.Snat = &schema.Snat{ Port: &schema.Expression{RowData: json.RawMessage(`[80,8080]`)}, } var port float64 = 12345 address1 := "feed::c0fe" fullHouse := schema.Statement{} familyIP6 := schema.FamilyIP6 fullHouse.Snat = &schema.Snat{ Addr: &schema.Expression{String: &address1}, Family: &familyIP6, Port: &schema.Expression{Float64: &port}, Flags: &schema.Flags{Flags: []string{schema.NATFlagFullyRandom}}, } statements := []schema.Statement{addressWithFamily, portList, fullHouse} expectedDNATIP4 := `"snat":{"addr":"1.2.3.4","family":"ip"}` expectedDNATMultiPorts := `"snat":{"port":[80,8080]}` expectedDNATIP6PortAndFlag := `"snat":{"addr":"feed::c0fe","family":"ip6","port":12345,"flags":"fully-random"}` serializedStatements := fmt.Sprintf( `"expr":[{%s},{%s},{%s}]`, expectedDNATIP4, expectedDNATMultiPorts, expectedDNATIP6PortAndFlag, ) return statements, serializedStatements } func masqueradeStatements() ([]schema.Statement, string) { basic := schema.Statement{} basic.Masquerade = &schema.Masquerade{Enabled: true} portList := schema.Statement{} portList.Masquerade = &schema.Masquerade{ Port: &schema.Expression{RowData: json.RawMessage(`[80,8080]`)}, } var port float64 = 12345 portAndFlags := schema.Statement{} portAndFlags.Masquerade = &schema.Masquerade{ Port: &schema.Expression{Float64: &port}, Flags: &schema.Flags{Flags: []string{schema.NATFlagFullyRandom}}, } statements := []schema.Statement{basic, portList, portAndFlags} expectedMasqueradeNoValues := `"masquerade":null` expectedMasqueradeMultiPorts := `"masquerade":{"port":[80,8080]}` expectedMasqueradePortAndFlag := `"masquerade":{"port":12345,"flags":"fully-random"}` serializedStatements := fmt.Sprintf( `"expr":[{%s},{%s},{%s}]`, expectedMasqueradeNoValues, expectedMasqueradeMultiPorts, expectedMasqueradePortAndFlag, ) return statements, serializedStatements } func redirectStatements() ([]schema.Statement, string) { basic := schema.Statement{} basic.Redirect = &schema.Redirect{Enabled: true} portList := schema.Statement{} portList.Redirect = &schema.Redirect{ Port: &schema.Expression{RowData: json.RawMessage(`[80,8080]`)}, } var port float64 = 12345 portAndFlags := schema.Statement{} portAndFlags.Redirect = &schema.Redirect{ Port: &schema.Expression{Float64: &port}, Flags: &schema.Flags{Flags: []string{schema.NATFlagFullyRandom}}, } statements := []schema.Statement{basic, portList, portAndFlags} expectedRedirectNoValues := `"redirect":null` expectedRedirectMultiPorts := `"redirect":{"port":[80,8080]}` expectedRedirectPortAndFlag := `"redirect":{"port":12345,"flags":"fully-random"}` serializedStatements := fmt.Sprintf( `"expr":[{%s},{%s},{%s}]`, expectedRedirectNoValues, expectedRedirectMultiPorts, expectedRedirectPortAndFlag, ) return statements, serializedStatements } golang-github-networkplumbing-go-nft-0.2.0/nft/config/table.go000066400000000000000000000043541420647247600243510ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config import ( "github.com/networkplumbing/go-nft/nft/schema" ) // AddTable appends the given table to the nftable config. // The table is added without an explicit action (`add`). // Adding multiple times the same table has no effect when the config is applied. func (c *Config) AddTable(table *schema.Table) { nftable := schema.Nftable{Table: table} c.Nftables = append(c.Nftables, nftable) } // DeleteTable appends a given table to the nftable config // with the `delete` action. // Attempting to delete a non-existing table, results with a failure when the config is applied. // All chains and rules under the table are removed as well (when applied). func (c *Config) DeleteTable(table *schema.Table) { nftable := schema.Nftable{Delete: &schema.Objects{Table: table}} c.Nftables = append(c.Nftables, nftable) } // FlushTable appends a given table to the nftable config // with the `flush` action. // All chains and rules under the table are removed (when applied). // Attempting to flush a non-existing table, results with a failure when the config is applied. func (c *Config) FlushTable(table *schema.Table) { nftable := schema.Nftable{Flush: &schema.Objects{Table: table}} c.Nftables = append(c.Nftables, nftable) } // LookupTable searches the configuration for a matching table and returns it. // Mutating the returned table will result in mutating the configuration. func (c *Config) LookupTable(toFind *schema.Table) *schema.Table { for _, nftable := range c.Nftables { if t := nftable.Table; t != nil { if t.Name == toFind.Name && t.Family == toFind.Family { return t } } } return nil } golang-github-networkplumbing-go-nft-0.2.0/nft/config/table_test.go000066400000000000000000000056451420647247600254140ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package config_test import ( "fmt" "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) type tableActionFunc func(*nft.Config, *schema.Table) const tableName = "test-table" func TestTable(t *testing.T) { testTableActions(t) testTableLookup(t) } func testTableActions(t *testing.T) { actions := map[nft.TableAction]tableActionFunc{ nft.TableADD: func(c *nft.Config, t *schema.Table) { c.AddTable(t) }, nft.TableDELETE: func(c *nft.Config, t *schema.Table) { c.DeleteTable(t) }, nft.TableFLUSH: func(c *nft.Config, t *schema.Table) { c.FlushTable(t) }, } families := []nft.AddressFamily{ nft.FamilyIP, nft.FamilyIP6, nft.FamilyINET, nft.FamilyBridge, nft.FamilyARP, nft.FamilyNETDEV, } for actionName, actionFunc := range actions { for _, family := range families { testTableAction(t, actionName, actionFunc, family) } } } func testTableAction(t *testing.T, actionName nft.TableAction, actionFunc tableActionFunc, family nft.AddressFamily) { testName := fmt.Sprintf("%s %s table", actionName, family) t.Run(testName, func(t *testing.T) { table := nft.NewTable(tableName, family) config := nft.NewConfig() actionFunc(config, table) serializedConfig, err := config.ToJSON() assert.NoError(t, err) var expected []byte if actionName == nft.TableADD { expected = []byte(fmt.Sprintf(`{"nftables":[{"table":{"family":%q,"name":%q}}]}`, family, tableName)) } else { expected = []byte(fmt.Sprintf(`{"nftables":[{%q:{"table":{"family":%q,"name":%q}}}]}`, actionName, family, tableName)) } assert.Equal(t, string(expected), string(serializedConfig)) }) } func testTableLookup(t *testing.T) { config := nft.NewConfig() config.AddTable(nft.NewTable("table-ip", nft.FamilyIP)) config.AddTable(nft.NewTable("table-ip", nft.FamilyIP6)) table_br := nft.NewTable("table-br", nft.FamilyBridge) config.AddTable(table_br) config.AddChain(nft.NewRegularChain(table_br, "chain-br")) t.Run("Lookup an existing table", func(t *testing.T) { table := config.LookupTable(table_br) assert.Equal(t, *table_br, *table) }) t.Run("Lookup a missing table", func(t *testing.T) { table := config.LookupTable(nft.NewTable("table-na", nft.FamilyBridge)) assert.Nil(t, table) }) } golang-github-networkplumbing-go-nft-0.2.0/nft/doc.go000066400000000000000000000034461420647247600225630ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ // Package nft provides a GO API to nftables. // Together with the schema package, it allows to build, read and apply // nftables configuration on a supporting system. // // The schema structures are based on libnftables-json (https://www.mankier.com/5/libnftables-json) // and implement a subset of them. // // To create a new configuration, use `NewConfig` followed by methods // which populates the configuration with tables, chains and rules, accompanied // to specific actions (add, delete, flush). // // config := nft.NewConfig() // table := nft.NewTable("mytable", nft.FamilyIP) // config.AddTable(table) // chain := nft.NewRegularChain(table, "mychain") // config.AddChain(chain) // rule := nft.NewRule(table, chain, statements, nil, nil, "mycomment") // // To apply a configuration on the system, use the `ApplyConfig` function. // err := nft.ApplyConfig(config) // // To read the configuration from the system, use the `ReadConfig` function. // config, err := nft.ReadConfig() // // For full setup example, see the integration test: tests/config_test.go // // The nft package is dependent on the `nft` binary and the kernel nftables // support. package nft golang-github-networkplumbing-go-nft-0.2.0/nft/exec/000077500000000000000000000000001420647247600224045ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/nft/exec/exec.go000066400000000000000000000050711420647247600236620ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package exec import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "strings" nftconfig "github.com/networkplumbing/go-nft/nft/config" ) const ( cmdBin = "nft" cmdFile = "-f" cmdJSON = "-j" cmdList = "list" cmdRuleset = "ruleset" ) // ReadConfig loads the nftables configuration from the system and // returns it as a nftables config structure. // The system is expected to have the `nft` executable deployed and nftables enabled in the kernel. func ReadConfig() (*nftconfig.Config, error) { stdout, err := execCommand(cmdJSON, cmdList, cmdRuleset) if err != nil { return nil, err } config := nftconfig.New() if err := config.FromJSON(stdout.Bytes()); err != nil { return nil, fmt.Errorf("failed to list ruleset: %v", err) } return config, nil } // ApplyConfig applies the given nftables config on the system. // The system is expected to have the `nft` executable deployed and nftables enabled in the kernel. func ApplyConfig(c *nftconfig.Config) error { data, err := c.ToJSON() if err != nil { return err } tmpFile, err := ioutil.TempFile(os.TempDir(), "spoofcheck-") if err != nil { return fmt.Errorf("failed to create temporary file: %v", err) } defer os.Remove(tmpFile.Name()) if _, err = tmpFile.Write(data); err != nil { return fmt.Errorf("failed to write to temporary file: %v", err) } if err := tmpFile.Close(); err != nil { return fmt.Errorf("failed to close temporary file: %v", err) } if _, err := execCommand(cmdJSON, cmdFile, tmpFile.Name()); err != nil { return err } return nil } func execCommand(args ...string) (*bytes.Buffer, error) { cmd := exec.Command(cmdBin, args...) var stdout, stderr bytes.Buffer cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { return nil, fmt.Errorf( "failed to execute %s %s: %v stdout:'%s' stderr:'%s'", cmd.Path, strings.Join(cmd.Args, " "), err, stdout.String(), stderr.String(), ) } return &stdout, nil } golang-github-networkplumbing-go-nft-0.2.0/nft/lib/000077500000000000000000000000001420647247600222265ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/nft/lib/lib.go000066400000000000000000000052041420647247600233240ustar00rootroot00000000000000// +build cgo /* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package lib // #cgo CFLAGS: -g -Wall // #cgo LDFLAGS: -lnftables // #include // #include // #include import "C" import ( "fmt" "unsafe" "github.com/networkplumbing/go-nft/nft" ) const ( cmdList = "list" cmdRuleset = "ruleset" ) // ReadConfig loads the nftables configuration from the system and // returns it as a nftables config structure. // The system is expected to have the `nft` executable deployed and nftables enabled in the kernel. func ReadConfig() (*nft.Config, error) { stdout, err := libNftablesRunCmd(fmt.Sprintf("%s %s", cmdList, cmdRuleset)) if err != nil { return nil, err } config := nft.NewConfig() if err := config.FromJSON(stdout); err != nil { return nil, fmt.Errorf("failed to list ruleset: %v", err) } return config, nil } // ApplyConfig applies the given nftables config on the system. // The system is expected to have the `nft` executable deployed and nftables enabled in the kernel. func ApplyConfig(c *nft.Config) error { data, err := c.ToJSON() if err != nil { return err } if _, err = libNftablesRunCmd(string(data)); err != nil { return err } return nil } func libNftablesRunCmd(cmd string) ([]byte, error) { nft := C.nft_ctx_new(C.NFT_CTX_DEFAULT) defer C.nft_ctx_free(nft) C.nft_ctx_output_set_flags(nft, C.NFT_CTX_OUTPUT_JSON) buf := C.CString(cmd) defer C.free(unsafe.Pointer(buf)) rc := C.nft_ctx_buffer_output(nft) if rc != C.EXIT_SUCCESS { return nil, fmt.Errorf("failed enabling output buffering (rc=%d)", rc) } rc = C.nft_ctx_buffer_error(nft) if rc != C.EXIT_SUCCESS { return nil, fmt.Errorf("failed enabling error buffering (rc=%d)", rc) } rc = C.nft_run_cmd_from_buffer(nft, buf) if rc != C.EXIT_SUCCESS { errMsg := C.nft_ctx_get_error_buffer(nft) return nil, fmt.Errorf("failed running cmd (rc=%d): %s", rc, C.GoString(errMsg)) } config := C.nft_ctx_get_output_buffer(nft) configLen := C.int(C.strlen(config)) return C.GoBytes(unsafe.Pointer(config), configLen), nil } golang-github-networkplumbing-go-nft-0.2.0/nft/rule.go000066400000000000000000000033241420647247600227600ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package nft import ( "github.com/networkplumbing/go-nft/nft/schema" ) // NewRule returns a new schema rule structure. func NewRule(table *schema.Table, chain *schema.Chain, expr []schema.Statement, handle *int, index *int, comment string) *schema.Rule { c := &schema.Rule{ Family: table.Family, Table: table.Name, Chain: chain.Name, Expr: expr, Handle: handle, Index: index, Comment: comment, } return c } type RuleIndex int // NewRuleIndex returns a rule index object which acts as an iterator. // When multiple rules are added to a chain, index allows to define an order between them. // The first rule which is added to a chain should have no index (it is assigned index 0), // following rules should have the index set, referencing after/before which rule the new one is to be added/inserted. func NewRuleIndex() *RuleIndex { var index RuleIndex = -1 return &index } // Next returns the next iteration value as an integer pointer. // When first time called, it returns the value 0. func (i *RuleIndex) Next() *int { *i++ var index = int(*i) return &index } golang-github-networkplumbing-go-nft-0.2.0/nft/schema/000077500000000000000000000000001420647247600227205ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/nft/schema/chain.go000066400000000000000000000024311420647247600243310ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package schema // Chain Types const ( TypeFilter = "filter" TypeNAT = "nat" TypeRoute = "route" ) // Chain Hooks const ( HookPreRouting = "prerouting" HookInput = "input" HookOutput = "output" HookForward = "forward" HookPostRouting = "postrouting" HookIngress = "ingress" ) // Chain Policies const ( PolicyAccept = "accept" PolicyDrop = "drop" ) type Chain struct { Family string `json:"family"` Table string `json:"table"` Name string `json:"name"` Type string `json:"type,omitempty"` Hook string `json:"hook,omitempty"` Prio *int `json:"prio,omitempty"` Policy string `json:"policy,omitempty"` } golang-github-networkplumbing-go-nft-0.2.0/nft/schema/rule.go000066400000000000000000000215421420647247600242220ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package schema import ( "encoding/json" "fmt" ) type Rule struct { Family string `json:"family"` Table string `json:"table"` Chain string `json:"chain"` Expr []Statement `json:"expr,omitempty"` Handle *int `json:"handle,omitempty"` Index *int `json:"index,omitempty"` Comment string `json:"comment,omitempty"` } type Statement struct { Counter *Counter `json:"counter,omitempty"` Match *Match `json:"match,omitempty"` Verdict Nat } type Counter struct { Packets int `json:"packets"` Bytes int `json:"bytes"` } type Nat struct { Snat *Snat `json:"snat,omitempty"` Dnat *Dnat `json:"dnat,omitempty"` Masquerade *Masquerade `json:"masquerade,omitempty"` Redirect *Redirect `json:"redirect,omitempty"` } type Snat struct { Addr *Expression `json:"addr,omitempty"` Family *string `json:"family,omitempty"` Port *Expression `json:"port,omitempty"` Flags *Flags `json:"flags,omitempty"` } type Dnat struct { Addr *Expression `json:"addr,omitempty"` Family *string `json:"family,omitempty"` Port *Expression `json:"port,omitempty"` Flags *Flags `json:"flags,omitempty"` } const masquerade = "masquerade" type Masquerade struct { Enabled bool `json:"-"` Port *Expression `json:"port,omitempty"` Flags *Flags `json:"flags,omitempty"` } const redirect = "redirect" type Redirect struct { Enabled bool `json:"-"` Port *Expression `json:"port,omitempty"` Flags *Flags `json:"flags,omitempty"` } type Flags struct { Flags []string `json:"-"` } // NAT Flags const ( NATFlagRandom = "random" NATFlagFullyRandom = "fully-random" NATFlagPersistent = "persistent" ) type Verdict struct { SimpleVerdict Jump *ToTarget `json:"jump,omitempty"` Goto *ToTarget `json:"goto,omitempty"` } type SimpleVerdict struct { Accept bool `json:"-"` Continue bool `json:"-"` Drop bool `json:"-"` Return bool `json:"-"` } type ToTarget struct { Target string `json:"target"` } type Match struct { Op string `json:"op"` Left Expression `json:"left"` Right Expression `json:"right"` } type Expression struct { String *string `json:"-"` Bool *bool `json:"-"` Float64 *float64 `json:"-"` Payload *Payload `json:"payload,omitempty"` // RowData accepts arbitrary data which cannot be composed from the existing schema. // Use `json.RawMessage()` or `[]byte()` for the value. // Example: // `schema.Expression{RowData: json.RawMessage(`{"meta":{"key":"iifname"}}`)}` RowData json.RawMessage `json:"-"` } type Payload struct { Protocol string `json:"protocol"` Field string `json:"field"` } // Verdict Operations const ( VerdictAccept = "accept" VerdictContinue = "continue" VerdictDrop = "drop" VerdictReturn = "return" ) // Match Operators const ( OperAND = "&" // Binary AND OperOR = "|" // Binary OR OperXOR = "^" // Binary XOR OperLSH = "<<" // Left shift OperRSH = ">>" // Right shift OperEQ = "==" // Equal OperNEQ = "!=" // Not equal OperLS = "<" // Less than OperGR = ">" // Greater than OperLSE = "<=" // Less than or equal to OperGRE = ">=" // Greater than or equal to OperIN = "in" // Perform a lookup, i.e. test if bits on RHS are contained in LHS value ) // Payload Expressions const ( PayloadKey = "payload" // Ethernet PayloadProtocolEther = "ether" PayloadFieldEtherDAddr = "daddr" PayloadFieldEtherSAddr = "saddr" PayloadFieldEtherType = "type" // IP (common) PayloadFieldIPVer = "version" PayloadFieldIPDscp = "dscp" PayloadFieldIPEcn = "ecn" PayloadFieldIPLen = "length" PayloadFieldIPSAddr = "saddr" PayloadFieldIPDAddr = "daddr" // IPv4 PayloadProtocolIP4 = "ip" PayloadFieldIP4HdrLen = "hdrlength" PayloadFieldIP4Id = "id" PayloadFieldIP4FragOff = "frag-off" PayloadFieldIP4Ttl = "ttl" PayloadFieldIP4Protocol = "protocol" PayloadFieldIP4Chksum = "checksum" // IPv6 PayloadProtocolIP6 = "ip6" PayloadFieldIP6FlowLabel = "flowlabel" PayloadFieldIP6NextHdr = "nexthdr" PayloadFieldIP6HopLimit = "hoplimit" ) func (s Statement) MarshalJSON() ([]byte, error) { type _Statement Statement statement := _Statement(s) // Convert to a dynamic structure data, err := json.Marshal(statement) if err != nil { return nil, err } dynamicStructure := make(map[string]json.RawMessage) if err := json.Unmarshal(data, &dynamicStructure); err != nil { return nil, err } switch { case s.Accept: dynamicStructure[VerdictAccept] = nil case s.Continue: dynamicStructure[VerdictContinue] = nil case s.Drop: dynamicStructure[VerdictDrop] = nil case s.Return: dynamicStructure[VerdictReturn] = nil case s.Masquerade != nil && s.Masquerade.Enabled && s.Masquerade.Port == nil && s.Masquerade.Flags == nil: dynamicStructure[masquerade] = nil case s.Redirect != nil && s.Redirect.Enabled && s.Redirect.Port == nil && s.Redirect.Flags == nil: dynamicStructure[redirect] = nil } data, err = json.Marshal(dynamicStructure) if err != nil { return nil, err } return data, nil } func (s *Statement) UnmarshalJSON(data []byte) error { type _Statement Statement statement := _Statement{} if err := json.Unmarshal(data, &statement); err != nil { return err } *s = Statement(statement) dynamicStructure := make(map[string]json.RawMessage) if err := json.Unmarshal(data, &dynamicStructure); err != nil { return err } _, s.Accept = dynamicStructure[VerdictAccept] _, s.Continue = dynamicStructure[VerdictContinue] _, s.Drop = dynamicStructure[VerdictDrop] _, s.Return = dynamicStructure[VerdictReturn] if _, masqueradeDefined := dynamicStructure[masquerade]; s.Masquerade == nil && masqueradeDefined { s.Masquerade = &Masquerade{Enabled: true} } if _, redirectDefined := dynamicStructure[redirect]; s.Redirect == nil && redirectDefined { s.Redirect = &Redirect{Enabled: true} } return nil } func (e Expression) MarshalJSON() ([]byte, error) { var dynamicStruct interface{} switch { case e.RowData != nil: return e.RowData, nil case e.String != nil: dynamicStruct = *e.String case e.Float64 != nil: dynamicStruct = *e.Float64 case e.Bool != nil: dynamicStruct = *e.Bool default: type _Expression Expression dynamicStruct = _Expression(e) } return json.Marshal(dynamicStruct) } func (e *Expression) UnmarshalJSON(data []byte) error { var dynamicStruct interface{} if err := json.Unmarshal(data, &dynamicStruct); err != nil { return err } switch dynamicStruct.(type) { case string: d := dynamicStruct.(string) e.String = &d case float64: d := dynamicStruct.(float64) e.Float64 = &d case bool: d := dynamicStruct.(bool) e.Bool = &d case []interface{}: e.RowData = data case map[string]interface{}: type _Expression Expression expression := _Expression(*e) if err := json.Unmarshal(data, &expression); err != nil { return err } *e = Expression(expression) default: return fmt.Errorf("unsupported field type in expression: %T(%v)", dynamicStruct, dynamicStruct) } if e.String == nil && e.Float64 == nil && e.Bool == nil && e.Payload == nil { e.RowData = data } return nil } func (f Flags) MarshalJSON() ([]byte, error) { var dynamicStruct interface{} switch flagCount := len(f.Flags); { case flagCount == 1: dynamicStruct = f.Flags[0] case flagCount > 1: dynamicStruct = f.Flags } return json.Marshal(dynamicStruct) } func (f *Flags) UnmarshalJSON(data []byte) error { var dynamicStruct interface{} if err := json.Unmarshal(data, &dynamicStruct); err != nil { return err } switch v := dynamicStruct.(type) { case string: f.Flags = []string{v} case []interface{}: for _, val := range v { stringVal, ok := val.(string) if !ok { return fmt.Errorf("flags values require string type: %T(%v)", dynamicStruct, dynamicStruct) } f.Flags = append(f.Flags, stringVal) } default: return fmt.Errorf("flags values require string type: %T(%v)", dynamicStruct, dynamicStruct) } return nil } func Accept() Verdict { return Verdict{SimpleVerdict: SimpleVerdict{Accept: true}} } func Continue() Verdict { return Verdict{SimpleVerdict: SimpleVerdict{Continue: true}} } func Drop() Verdict { return Verdict{SimpleVerdict: SimpleVerdict{Drop: true}} } func Return() Verdict { return Verdict{SimpleVerdict: SimpleVerdict{Return: true}} } golang-github-networkplumbing-go-nft-0.2.0/nft/schema/schema.go000066400000000000000000000036421420647247600245140ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package schema import ( "encoding/json" ) type Root struct { Nftables []Nftable `json:"nftables"` } const ruleSetKey = "ruleset" type Objects struct { Table *Table `json:"table,omitempty"` Chain *Chain `json:"chain,omitempty"` Rule *Rule `json:"rule,omitempty"` Ruleset bool `json:"-"` } func (o Objects) MarshalJSON() ([]byte, error) { type _Objects Objects objects := _Objects(o) data, err := json.Marshal(objects) if err != nil { return nil, err } if o.Ruleset { // Convert to a dynamic structure var dynamicStructure map[string]json.RawMessage if err := json.Unmarshal(data, &dynamicStructure); err != nil { return nil, err } dynamicStructure[ruleSetKey] = nil data, err = json.Marshal(dynamicStructure) if err != nil { return nil, err } } return data, nil } type Nftable struct { Table *Table `json:"table,omitempty"` Chain *Chain `json:"chain,omitempty"` Rule *Rule `json:"rule,omitempty"` Add *Objects `json:"add,omitempty"` Delete *Objects `json:"delete,omitempty"` Flush *Objects `json:"flush,omitempty"` Metainfo *Metainfo `json:"metainfo,omitempty"` } type Metainfo struct { Version string `json:"version"` ReleaseName string `json:"release_name"` JsonSchemaVersion int `json:"json_schema_version"` } golang-github-networkplumbing-go-nft-0.2.0/nft/schema/table.go000066400000000000000000000023341420647247600243400ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package schema // Table Address Families const ( FamilyIP = "ip" // IPv4 address AddressFamily. FamilyIP6 = "ip6" // IPv6 address AddressFamily. FamilyINET = "inet" // Internet (IPv4/IPv6) address AddressFamily. FamilyARP = "arp" // ARP address AddressFamily, handling IPv4 ARP packets. FamilyBridge = "bridge" // Bridge address AddressFamily, handling packets which traverse a bridge device. FamilyNETDEV = "netdev" // Netdev address AddressFamily, handling packets from ingress. ) type Table struct { Family string `json:"family"` Name string `json:"name"` } golang-github-networkplumbing-go-nft-0.2.0/nft/table.go000066400000000000000000000025731420647247600231050ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package nft import "github.com/networkplumbing/go-nft/nft/schema" type AddressFamily string // Address Families const ( FamilyIP AddressFamily = schema.FamilyIP FamilyIP6 AddressFamily = schema.FamilyIP6 FamilyINET AddressFamily = schema.FamilyINET FamilyARP AddressFamily = schema.FamilyARP FamilyBridge AddressFamily = schema.FamilyBridge FamilyNETDEV AddressFamily = schema.FamilyNETDEV ) type TableAction string // Table Actions const ( TableADD TableAction = "add" TableDELETE TableAction = "delete" TableFLUSH TableAction = "flush" ) // NewTable returns a new schema table structure. func NewTable(name string, family AddressFamily) *schema.Table { return &schema.Table{ Name: name, Family: string(family), } } golang-github-networkplumbing-go-nft-0.2.0/tests/000077500000000000000000000000001420647247600220335ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/tests/config_test.go000066400000000000000000000056601420647247600246750ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package tests import ( "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/tests/testlib" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) func TestConfig(t *testing.T) { testlib.RunTestWithFlushTable(t, testReadEmptyConfig) testlib.RunTestWithFlushTable(t, testApplyConfigWithAnEmptyTable) testlib.RunTestWithFlushTable(t, testApplyConfigWithSampleStatements) } func testReadEmptyConfig(t *testing.T) { config, err := nft.ReadConfig() assert.NoError(t, err) assert.Len(t, config.Nftables, 1, "Expecting just the metainfo entry") expectedConfig := nft.NewConfig() expectedConfig.Nftables = append(expectedConfig.Nftables, schema.Nftable{Metainfo: &schema.Metainfo{JsonSchemaVersion: 1}}) // The underling nftable userspace version depends on where it is ran, therefore remove it from the diff. expectedConfig.Nftables[0].Metainfo.Version = config.Nftables[0].Metainfo.Version expectedConfig.Nftables[0].Metainfo.ReleaseName = config.Nftables[0].Metainfo.ReleaseName assert.Equal(t, expectedConfig, config) } func testApplyConfigWithAnEmptyTable(t *testing.T) { config := nft.NewConfig() config.AddTable(nft.NewTable("mytable", nft.FamilyIP)) assert.NoError(t, nft.ApplyConfig(config)) newConfig, err := nft.ReadConfig() assert.NoError(t, err) assert.Len(t, newConfig.Nftables, 2, "Expecting the metainfo and an empty table entry") assert.Equal(t, config.Nftables[0], newConfig.Nftables[1]) } func testApplyConfigWithSampleStatements(t *testing.T) { testApplyConfigWithStatements(t, schema.Statement{Counter: &schema.Counter{}}, ) } func testApplyConfigWithStatements(t *testing.T, statements ...schema.Statement) { const tableName = "mytable" config := nft.NewConfig() table := nft.NewTable(tableName, nft.FamilyIP) config.AddTable(table) const chainName = "mychain" chain := nft.NewChain(table, chainName, nil, nil, nil, nil) config.AddChain(chain) rule := nft.NewRule(table, chain, statements, nil, nil, "test") config.AddRule(rule) assert.NoError(t, nft.ApplyConfig(config)) newConfig, err := nft.ReadConfig() assert.NoError(t, err) config = testlib.NormalizeConfigForComparison(config) newConfig = testlib.NormalizeConfigForComparison(newConfig) assert.Equal(t, config.Nftables, newConfig.Nftables) } golang-github-networkplumbing-go-nft-0.2.0/tests/example/000077500000000000000000000000001420647247600234665ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/tests/example/nat_test.go000066400000000000000000000054771420647247600256530ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package example import ( "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/tests/testlib" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) // TestNATExamples are based on the examples given at [1]. // 1. https://wiki.nftables.org/wiki-nftables/index.php/Performing_Network_Address_Translation_(NAT) // // The inet family is mentioned in [1]: // "Since Linux kernel 5.2, there is support for performing stateful NAT in inet family chains.". // Therefore, inet family is not used in this example. func TestNATExamples(t *testing.T) { testlib.RunTestWithFlushTable(t, testMasqueradeExample) } func testMasqueradeExample(t *testing.T) { desiredJson, actualJson, err := setupExample(buildMasqueradeConfig) assert.NoError(t, err) assert.JSONEq(t, desiredJson, actualJson) } func buildMasqueradeConfig() *nft.Config { const ( ip4TableName = "ip4-masquerade-example" ip6TableName = "ip6-masquerade-example" baseChainName = "postrouting" ) chainPriority := 100 return &nft.Config{schema.Root{Nftables: []schema.Nftable{ {Table: &schema.Table{Family: schema.FamilyIP, Name: ip4TableName}}, {Table: &schema.Table{Family: schema.FamilyIP6, Name: ip6TableName}}, {Chain: &schema.Chain{ Family: schema.FamilyIP, Table: ip4TableName, Name: baseChainName, Type: schema.TypeNAT, Hook: schema.HookPostRouting, Prio: &chainPriority, Policy: schema.PolicyAccept, }}, {Chain: &schema.Chain{ Family: schema.FamilyIP6, Table: ip6TableName, Name: baseChainName, Type: schema.TypeNAT, Hook: schema.HookPostRouting, Prio: &chainPriority, Policy: schema.PolicyAccept, }}, {Rule: &schema.Rule{ Family: schema.FamilyIP, Table: ip4TableName, Chain: baseChainName, Expr: []schema.Statement{ {Nat: schema.Nat{Masquerade: &schema.Masquerade{Enabled: true}}}, }, Comment: "generic masquerade", }}, {Rule: &schema.Rule{ Family: schema.FamilyIP6, Table: ip6TableName, Chain: baseChainName, Expr: []schema.Statement{ {Nat: schema.Nat{Masquerade: &schema.Masquerade{Enabled: true}}}, }, Comment: "generic masquerade", }}, }}} } golang-github-networkplumbing-go-nft-0.2.0/tests/example/nomacspoofing_test.go000066400000000000000000000152351420647247600277240ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package example import ( "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/tests/testlib" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) func TestNoMacSpoofingExample(t *testing.T) { testlib.RunTestWithFlushTable(t, testNoMacSpoofingExample) } func testNoMacSpoofingExample(t *testing.T) { // The definition of no-mac-spoofing, is to prevent users from modifying an interface mac-address and keep // connectivity. // A simple implementation is to allow only a pre-defined number of mac-addresses on egress (filtering the source // mac) and ingress (filtering the destination mac). // User input var ( ifaceName = "nic0" macAddress = "00:00:00:00:00:01" ) desiredConfig := buildNoMacSpoofingConfigImperatively(ifaceName, macAddress) assert.Equal(t, desiredConfig, buildNoMacSpoofingConfigDecleratively(ifaceName, macAddress)) assert.NoError(t, nft.ApplyConfig(desiredConfig)) actualConfig, err := nft.ReadConfig() assert.NoError(t, err) expectedNftablesEntries := len(desiredConfig.Nftables) + 1 // +1 for the metainfo entry. assert.Len(t, actualConfig.Nftables, expectedNftablesEntries) desiredConfig = testlib.NormalizeConfigForComparison(desiredConfig) actualConfig = testlib.NormalizeConfigForComparison(actualConfig) desiredJson, err := desiredConfig.ToJSON() assert.NoError(t, err) actualJson, err := actualConfig.ToJSON() assert.NoError(t, err) assert.Equal(t, string(desiredJson), string(actualJson)) } func buildNoMacSpoofingConfigImperatively(ifaceName string, macAddress string) *nft.Config { // Configuration Details var ( baseChainName = "preroute-bridge" ifaceChainName = "example-iface-" + ifaceName macChainName = ifaceChainName + "-mac" ) config := nft.NewConfig() table := nft.NewTable("example", nft.FamilyBridge) config.AddTable(table) chainType, chainHook, chainPrio, chainPolicy := nft.TypeFilter, nft.HookPreRouting, -300, nft.PolicyAccept baseChain := nft.NewChain(table, baseChainName, &chainType, &chainHook, &chainPrio, &chainPolicy) config.AddChain(baseChain) ifaceChain := nft.NewRegularChain(table, ifaceChainName) config.AddChain(ifaceChain) macChain := nft.NewRegularChain(table, macChainName) config.AddChain(macChain) matchIfaceAndJump := []schema.Statement{ {Match: &schema.Match{ Op: schema.OperEQ, Left: schema.Expression{RowData: []byte(`{"meta":{"key":"iifname"}}`)}, Right: schema.Expression{String: &ifaceName}, }}, {Verdict: schema.Verdict{Jump: &schema.ToTarget{Target: ifaceChainName}}}, } matchIfaceRule := nft.NewRule(table, baseChain, matchIfaceAndJump, nil, nil, "match input interface name") config.AddRule(matchIfaceRule) jumpToMACChain := []schema.Statement{ {Verdict: schema.Verdict{Jump: &schema.ToTarget{Target: macChainName}}}, } ifaceRule := nft.NewRule(table, ifaceChain, jumpToMACChain, nil, nil, "redirect to mac-chain") config.AddRule(ifaceRule) matchSrcMacAndReturn := []schema.Statement{ {Match: &schema.Match{ Op: schema.OperEQ, Left: schema.Expression{Payload: &schema.Payload{ Protocol: schema.PayloadProtocolEther, Field: schema.PayloadFieldEtherSAddr, }}, Right: schema.Expression{String: &macAddress}, }}, {Verdict: schema.Return()}, } matchSrcMacRule := nft.NewRule(table, macChain, matchSrcMacAndReturn, nil, nil, "match source mac address") config.AddRule(matchSrcMacRule) drop := []schema.Statement{{Verdict: schema.Drop()}} // When multiple rules are added to a chain, index allows to define an order between them. macRulesIndex := nft.NewRuleIndex() dropRule := nft.NewRule(table, macChain, drop, nil, macRulesIndex.Next(), "drop all the rest") config.AddRule(dropRule) return config } func buildNoMacSpoofingConfigDecleratively(ifaceName string, macAddress string) *nft.Config { // Configuration Details const tableName = "example" var ( baseChainName = "preroute-bridge" ifaceChainName = "example-iface-" + ifaceName macChainName = ifaceChainName + "-mac" chainPriority = -300 macRulesIndex = nft.NewRuleIndex() ) return &nft.Config{schema.Root{Nftables: []schema.Nftable{ {Table: &schema.Table{Family: schema.FamilyBridge, Name: tableName}}, {Chain: &schema.Chain{ Family: schema.FamilyBridge, Table: tableName, Name: baseChainName, Type: schema.TypeFilter, Hook: schema.HookPreRouting, Prio: &chainPriority, Policy: schema.PolicyAccept, }}, {Chain: &schema.Chain{ Family: schema.FamilyBridge, Table: tableName, Name: ifaceChainName, }}, {Chain: &schema.Chain{ Family: schema.FamilyBridge, Table: tableName, Name: macChainName, }}, {Rule: &schema.Rule{ Family: schema.FamilyBridge, Table: tableName, Chain: baseChainName, Expr: []schema.Statement{ {Match: &schema.Match{ Op: schema.OperEQ, Left: schema.Expression{RowData: []byte(`{"meta":{"key":"iifname"}}`)}, Right: schema.Expression{String: &ifaceName}, }}, {Verdict: schema.Verdict{Jump: &schema.ToTarget{Target: ifaceChainName}}}, }, Comment: "match input interface name", }}, {Rule: &schema.Rule{ Family: schema.FamilyBridge, Table: tableName, Chain: ifaceChainName, Expr: []schema.Statement{ {Verdict: schema.Verdict{Jump: &schema.ToTarget{Target: macChainName}}}, }, Comment: "redirect to mac-chain", }}, {Rule: &schema.Rule{ Family: schema.FamilyBridge, Table: tableName, Chain: macChainName, Expr: []schema.Statement{ {Match: &schema.Match{ Op: schema.OperEQ, Left: schema.Expression{Payload: &schema.Payload{ Protocol: schema.PayloadProtocolEther, Field: schema.PayloadFieldEtherSAddr, }}, Right: schema.Expression{String: &macAddress}, }}, {Verdict: schema.Return()}, }, Comment: "match source mac address", }}, {Rule: &schema.Rule{ Family: schema.FamilyBridge, Table: tableName, Chain: macChainName, Index: macRulesIndex.Next(), Expr: []schema.Statement{{Verdict: schema.Drop()}}, Comment: "drop all the rest", }}, }}} } golang-github-networkplumbing-go-nft-0.2.0/tests/example/skeleton.go000066400000000000000000000041461420647247600256460ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package example import ( "fmt" "github.com/networkplumbing/go-nft/tests/testlib" "github.com/networkplumbing/go-nft/nft" ) type buildConfigT func() *nft.Config func setupExample(buildConfig buildConfigT) (string, string, error) { desiredConfig := buildConfig() if err := nft.ApplyConfig(desiredConfig); err != nil { return "", "", fmt.Errorf("failed to setup example: %v", err) } actualConfig, err := nft.ReadConfig() if err != nil { return "", "", fmt.Errorf("failed to setup example: %v", err) } desiredNftablesEntries := len(desiredConfig.Nftables) + 1 // +1 for the metainfo entry. actualNftablesEntries := len(actualConfig.Nftables) if actualNftablesEntries != desiredNftablesEntries { desiredJson, _ := desiredConfig.ToJSON() actualJson, _ := actualConfig.ToJSON() return "", "", fmt.Errorf( "failed to setup example, unexpected entries in post-setup resuts, desired(%d): %s, actual(%d): %s", desiredNftablesEntries, desiredJson, actualNftablesEntries, actualJson, ) } desiredConfig = testlib.NormalizeConfigForComparison(desiredConfig) actualConfig = testlib.NormalizeConfigForComparison(actualConfig) desiredJson, err := desiredConfig.ToJSON() if err != nil { return "", "", fmt.Errorf("failed to setup example, error json encoding: %v", err) } actualJson, err := actualConfig.ToJSON() if err != nil { return "", "", fmt.Errorf("failed to setup example, error json encoding: %v", err) } return string(desiredJson), string(actualJson), nil } golang-github-networkplumbing-go-nft-0.2.0/tests/nftlib/000077500000000000000000000000001420647247600233115ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/tests/nftlib/nftlib_test.go000066400000000000000000000025571420647247600261660ustar00rootroot00000000000000// +build !exec /* This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package main import ( "testing" assert "github.com/stretchr/testify/require" "github.com/networkplumbing/go-nft/nft" nftlib "github.com/networkplumbing/go-nft/nft/lib" "github.com/networkplumbing/go-nft/tests/testlib" ) func TestNftlib(t *testing.T) { testlib.RunTestWithFlushTable(t, func(t *testing.T) { config := nft.NewConfig() config.AddTable(nft.NewTable("mytable", nft.FamilyIP)) assert.NoError(t, nftlib.ApplyConfig(config)) newConfig, err := nftlib.ReadConfig() assert.NoError(t, err) assert.Len(t, newConfig.Nftables, 2, "Expecting the metainfo and an empty table entry") assert.Equal(t, config.Nftables[0], newConfig.Nftables[1]) _, err = nftlib.ReadConfig() assert.NoError(t, err) }) } golang-github-networkplumbing-go-nft-0.2.0/tests/testlib/000077500000000000000000000000001420647247600235015ustar00rootroot00000000000000golang-github-networkplumbing-go-nft-0.2.0/tests/testlib/config.go000066400000000000000000000033631420647247600253020ustar00rootroot00000000000000/* * This file is part of the go-nft project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2021 Red Hat, Inc. * */ package testlib import ( "sort" "testing" "github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft/schema" ) func RunTestWithFlushTable(t *testing.T, test func(t *testing.T)) { test(t) nft.ApplyConfig(&nft.Config{schema.Root{Nftables: []schema.Nftable{ {Flush: &schema.Objects{Ruleset: true}}, }}}) } // NormalizeConfigForComparison returns the configuration ready for comparison with another by // - removing the metainfo entry. // - removing the handle + index parameters. // - Sorting the list. func NormalizeConfigForComparison(config *nft.Config) *nft.Config { if len(config.Nftables) > 0 && config.Nftables[0].Metainfo != nil { config.Nftables = config.Nftables[1:] } for _, nftable := range config.Nftables { if nftable.Rule != nil { nftable.Rule.Index = nil nftable.Rule.Handle = nil } } sort.Slice(config.Nftables, func(i int, j int) bool { s := config.Nftables isTableFirst := s[i].Table != nil && (s[j].Chain != nil || s[j].Rule != nil) isChainBeforeRule := s[i].Chain != nil && s[j].Rule != nil return isTableFirst || isChainBeforeRule }) return config }