├── .dockerignore
├── .fpm
├── .github
├── pull_request_template.md
├── release.yml
└── workflows
│ ├── build-docker.yml
│ ├── ci.yml
│ ├── current.yml
│ ├── docs.yml
│ └── release.yml
├── .gitignore
├── .gitmodules
├── .pre-commit-config.yaml
├── Cargo.lock
├── Cargo.toml
├── Cross.toml
├── Dockerfile
├── LICENSE.md
├── README.md
├── after-install.sh
├── build.rs
├── defguard-gateway.service
├── defguard-gateway.service.freebsd
├── defguard-rc.conf
├── deny.toml
├── docs
└── header.png
├── example-config.toml
├── examples
└── server.rs
├── flake.lock
├── flake.nix
├── opnsense
├── Makefile
└── src
│ ├── etc
│ └── inc
│ │ └── plugins.inc.d
│ │ └── defguardgateway.inc
│ └── opnsense
│ ├── mvc
│ └── app
│ │ ├── controllers
│ │ └── OPNsense
│ │ │ └── DefguardGateway
│ │ │ ├── Api
│ │ │ ├── ServiceController.php
│ │ │ └── SettingsController.php
│ │ │ ├── IndexController.php
│ │ │ └── forms
│ │ │ └── general.xml
│ │ ├── models
│ │ └── OPNsense
│ │ │ └── DefguardGateway
│ │ │ ├── DefguardGateway.php
│ │ │ ├── DefguardGateway.xml
│ │ │ └── Menu
│ │ │ └── Menu.xml
│ │ └── views
│ │ └── OPNsense
│ │ └── DefguardGateway
│ │ └── index.volt
│ └── service
│ ├── conf
│ └── actions.d
│ │ └── actions_defguardgateway.conf
│ └── templates
│ └── OPNsense
│ └── DefguardGateway
│ ├── +TARGETS
│ ├── config.toml
│ └── rc.conf.d
└── src
├── config.rs
├── enterprise
├── LICENSE.md
├── firewall
│ ├── api.rs
│ ├── dummy
│ │ └── mod.rs
│ ├── iprange.rs
│ ├── mod.rs
│ ├── nftables
│ │ ├── mod.rs
│ │ └── netfilter.rs
│ └── packetfilter
│ │ ├── api.rs
│ │ ├── calls.rs
│ │ ├── mod.rs
│ │ └── rule.rs
└── mod.rs
├── error.rs
├── gateway.rs
├── lib.rs
├── main.rs
└── server.rs
/.dockerignore:
--------------------------------------------------------------------------------
1 | target/
2 | .github/
3 | docs/
4 |
--------------------------------------------------------------------------------
/.fpm:
--------------------------------------------------------------------------------
1 | -s dir
2 | --name defguard-gateway
3 | --description "defguard VPN gateway service"
4 | --url "https://defguard.net/"
5 | --maintainer "teonite"
6 | --config-files /etc/defguard/gateway.toml.sample
7 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ## 📖 Description
2 |
3 | 1. include a **summary of the changes and the related issue**, eg. _Closes #XYZ_
4 | 2. Do not make a PR if you can't check **all the boxes below**
5 |
6 | ### 🛠️ Dev Branch Merge Checklist:
7 |
8 | #### Documentation ###
9 |
10 | - [ ] If testing requires changes in the environment or deployment, please **update the documentation** (https://defguard.gitbook.io) first and **attach the link to the documentation** section in this pool request
11 | - [ ] I have commented on my code, particularly in hard-to-understand areas
12 |
13 | #### Testing ###
14 |
15 | - [ ] I have prepared end-to-end tests for all new functionalities
16 | - [ ] I have performed end-to-end tests manually and they work
17 | - [ ] New and existing unit tests pass locally with my changes
18 |
19 | #### Deployment ###
20 |
21 | - [ ] If deployment is affected I have made corresponding/required changes to [deployment](https://github.com/defguard/deployment) (Docker, Kubernetes, one-line install)
22 |
23 | ### 🏚️ Main Branch Merge Checklist:
24 |
25 | #### Testing ###
26 |
27 | - [ ] I have merged my changes before to dev and the dev checklist is done
28 | - [ ] I have tested all functionalities on the dev instance and they work
29 |
30 | #### Documentation ###
31 |
32 | - [ ] I have made corresponding changes to the **user & admin documentation** and added new features documentation with screenshots for users/admins
33 |
--------------------------------------------------------------------------------
/.github/release.yml:
--------------------------------------------------------------------------------
1 | changelog:
2 | exclude:
3 | labels:
4 | - ignore-for-release
5 | categories:
6 | - title: Breaking Changes 🛠
7 | labels:
8 | - Semver-Major
9 | - breaking-change
10 | - title: Exciting New Features 🎉
11 | labels:
12 | - Semver-Minor
13 | - enhancement
14 | - title: Other Changes
15 | labels:
16 | - "*"
17 |
--------------------------------------------------------------------------------
/.github/workflows/build-docker.yml:
--------------------------------------------------------------------------------
1 | name: Build Docker image
2 |
3 | on:
4 | workflow_call:
5 | inputs:
6 | tags:
7 | description: "List of tags as key-value pair attributes"
8 | required: false
9 | type: string
10 | flavor:
11 | description: "List of flavors as key-value pair attributes"
12 | required: false
13 | type: string
14 |
15 | env:
16 | GHCR_REPO: ghcr.io/defguard/gateway
17 |
18 | jobs:
19 | build-docker:
20 | runs-on:
21 | - self-hosted
22 | - Linux
23 | - ${{ matrix.runner }}
24 | strategy:
25 | matrix:
26 | cpu: [arm64, amd64, arm/v7]
27 | include:
28 | - cpu: arm64
29 | runner: ARM64
30 | tag: arm64
31 | - cpu: amd64
32 | runner: X64
33 | tag: amd64
34 | - cpu: arm/v7
35 | runner: ARM
36 | tag: armv7
37 | steps:
38 | - name: Checkout
39 | uses: actions/checkout@v4
40 | with:
41 | submodules: recursive
42 | - name: Login to GitHub container registry
43 | uses: docker/login-action@v3
44 | with:
45 | registry: ghcr.io
46 | username: ${{ github.actor }}
47 | password: ${{ secrets.GITHUB_TOKEN }}
48 | - name: Set up Docker Buildx
49 | uses: docker/setup-buildx-action@v3
50 | with:
51 | buildkitd-config-inline: |
52 | [registry."docker.io"]
53 | mirrors = ["dockerhub-proxy.teonite.net"]
54 | - name: Build container
55 | uses: docker/build-push-action@v5
56 | with:
57 | context: .
58 | platforms: linux/${{ matrix.cpu }}
59 | provenance: false
60 | push: true
61 | tags: "${{ env.GHCR_REPO }}:${{ github.sha }}-${{ matrix.tag }}"
62 | cache-from: type=gha
63 | cache-to: type=gha,mode=max
64 |
65 | docker-manifest:
66 | runs-on: [self-hosted, Linux]
67 | needs: [build-docker]
68 | steps:
69 | - name: Docker meta
70 | id: meta
71 | uses: docker/metadata-action@v5
72 | with:
73 | images: |
74 | ${{ env.GHCR_REPO }}
75 | flavor: ${{ inputs.flavor }}
76 | tags: ${{ inputs.tags }}
77 | - name: Login to GitHub container registry
78 | uses: docker/login-action@v3
79 | with:
80 | registry: ghcr.io
81 | username: ${{ github.actor }}
82 | password: ${{ secrets.GITHUB_TOKEN }}
83 | - name: Create and push manifests
84 | run: |
85 | tags='${{ env.GHCR_REPO }}:${{ github.sha }} ${{ steps.meta.outputs.tags }}'
86 | for tag in ${tags}
87 | do
88 | docker manifest rm ${tag} || true
89 | docker manifest create ${tag} ${{ env.GHCR_REPO }}:${{ github.sha }}-amd64 ${{ env.GHCR_REPO }}:${{ github.sha }}-arm64 ${{ env.GHCR_REPO }}:${{ github.sha }}-armv7
90 | docker manifest push ${tag}
91 | done
92 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Continuous integration
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | - dev
8 | - 'release/**'
9 | paths-ignore:
10 | - "*.md"
11 | - "LICENSE"
12 | pull_request:
13 | branches:
14 | - main
15 | - dev
16 | - 'release/**'
17 | paths-ignore:
18 | - "*.md"
19 | - "LICENSE"
20 |
21 | env:
22 | CARGO_TERM_COLOR: always
23 |
24 | jobs:
25 | test:
26 | runs-on: [self-hosted, Linux, X64]
27 | container: rust:1
28 |
29 | steps:
30 | - name: Debug
31 | run: echo ${{ github.ref_name }}
32 | - name: Checkout
33 | uses: actions/checkout@v4
34 | with:
35 | submodules: recursive
36 | - name: Cache
37 | uses: Swatinem/rust-cache@v2
38 | with:
39 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
40 | - name: Install dependencies
41 | run: apt-get update && apt-get -y install protobuf-compiler libnftnl-dev libmnl-dev
42 | - name: Check format
43 | run: |
44 | rustup component add rustfmt
45 | cargo fmt -- --check
46 | - name: Run clippy linter
47 | run: |
48 | rustup component add clippy
49 | cargo clippy --all-targets --all-features -- -D warnings
50 | - name: Run cargo deny
51 | uses: EmbarkStudios/cargo-deny-action@v2
52 | - name: Run tests
53 | run: cargo test --locked --no-fail-fast
54 |
--------------------------------------------------------------------------------
/.github/workflows/current.yml:
--------------------------------------------------------------------------------
1 | name: Build current image
2 | on:
3 | push:
4 | branches:
5 | - main
6 | - dev
7 | - 'release/**'
8 | paths-ignore:
9 | - "*.md"
10 | - "LICENSE"
11 |
12 | concurrency:
13 | group: ${{ github.workflow }}-${{ github.ref }}
14 | cancel-in-progress: true
15 |
16 | jobs:
17 | build-current:
18 | uses: ./.github/workflows/build-docker.yml
19 | with:
20 | tags: |
21 | type=ref,event=branch
22 | type=sha
23 |
--------------------------------------------------------------------------------
/.github/workflows/docs.yml:
--------------------------------------------------------------------------------
1 | name: rustdoc Github Pages
2 | on:
3 | push:
4 | branches:
5 | - main
6 |
7 | env:
8 | CARGO_INCREMENTAL: 0
9 | CARGO_NET_RETRY: 10
10 | RUSTFLAGS: "-D warnings -W unreachable-pub"
11 | RUSTUP_MAX_RETRIES: 10
12 |
13 | jobs:
14 | rustdoc:
15 | runs-on: [self-hosted, Linux]
16 | container:
17 | image: rust:1
18 |
19 | steps:
20 | - name: Checkout
21 | uses: actions/checkout@v4
22 | with:
23 | submodules: recursive
24 |
25 | - name: Install Rust toolchain
26 | run: rustup update --no-self-update stable
27 |
28 | - name: Install dependencies
29 | run: apt-get update && apt-get -y install protobuf-compiler libnftnl-dev libmnl-dev
30 |
31 | - name: Build Docs
32 | run: cargo doc --all --no-deps
33 |
34 | - name: Deploy Docs
35 | uses: peaceiris/actions-gh-pages@v3
36 | with:
37 | github_token: ${{ secrets.GITHUB_TOKEN }}
38 | publish_branch: gh-pages
39 | publish_dir: ./target/doc
40 | force_orphan: true
41 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Publish
2 | on:
3 | push:
4 | tags:
5 | - v*.*.*
6 |
7 | concurrency:
8 | group: ${{ github.workflow }}-${{ github.ref }}
9 | cancel-in-progress: true
10 |
11 | jobs:
12 | build-docker-release:
13 | # Ignore tags with -, like v1.0.0-alpha
14 | # This job will build the docker container with the "latest" tag which
15 | # is a tag used in production, thus it should only be run for full releases.
16 | if: startsWith(github.ref, 'refs/tags/') && !contains(github.ref, '-')
17 | name: Build Release Docker image
18 | uses: ./.github/workflows/build-docker.yml
19 | with:
20 | tags: |
21 | type=raw,value=latest
22 | type=semver,pattern={{version}}
23 | type=semver,pattern={{major}}.{{minor}}
24 | type=sha
25 |
26 | build-docker-prerelease:
27 | # Only build tags with -, like v1.0.0-alpha
28 | if: startsWith(github.ref, 'refs/tags/') && contains(github.ref, '-')
29 | name: Build Pre-release Docker image
30 | uses: ./.github/workflows/build-docker.yml
31 | with:
32 | tags: |
33 | type=raw,value=pre-release
34 | type=semver,pattern={{version}}
35 | type=sha
36 | # Explicitly disable latest tag. It will be added otherwise.
37 | flavor: |
38 | latest=false
39 |
40 | create-release:
41 | name: create-release
42 | runs-on: self-hosted
43 | outputs:
44 | upload_url: ${{ steps.release.outputs.upload_url }}
45 | steps:
46 | - name: Create GitHub release
47 | id: release
48 | uses: softprops/action-gh-release@v1
49 | if: startsWith(github.ref, 'refs/tags/')
50 | with:
51 | draft: true
52 | generate_release_notes: true
53 |
54 | build-release:
55 | name: Release ${{ matrix.build }}
56 | needs: [create-release]
57 | runs-on:
58 | - self-hosted
59 | - ${{ matrix.os }}
60 | - X64
61 | strategy:
62 | fail-fast: false
63 | matrix:
64 | build: [linux, linux-arm64, freebsd]
65 | include:
66 | - build: linux
67 | arch: amd64
68 | os: Linux
69 | asset_name: defguard-gateway-linux-x86_64
70 | target: x86_64-unknown-linux-gnu
71 | - build: linux-arm64
72 | arch: arm64
73 | os: Linux
74 | asset_name: defguard-gateway-linux-arm64
75 | target: aarch64-unknown-linux-gnu
76 | - build: freebsd
77 | arch: amd64
78 | os: Linux
79 | asset_name: defguard-gateway-freebsd-x86_64
80 | target: x86_64-unknown-freebsd
81 | steps:
82 | # Store the version, stripping any v-prefix
83 | - name: Write release version
84 | run: |
85 | VERSION=${GITHUB_REF_NAME#v}
86 | echo Version: $VERSION
87 | echo "VERSION=$VERSION" >> $GITHUB_ENV
88 |
89 | - name: Checkout
90 | uses: actions/checkout@v3
91 | with:
92 | submodules: recursive
93 |
94 | - name: Install Rust stable
95 | uses: actions-rs/toolchain@v1
96 | with:
97 | toolchain: stable
98 | target: ${{ matrix.target }}
99 | override: true
100 |
101 | - name: Build release binary
102 | uses: actions-rs/cargo@v1
103 | with:
104 | use-cross: true
105 | command: build
106 | args: --locked --release --target ${{ matrix.target }}
107 |
108 | - name: Rename binary
109 | run: mv target/${{ matrix.target }}/release/defguard-gateway ${{ matrix.asset_name }}-${{ github.ref_name }}
110 |
111 | - name: Tar
112 | uses: a7ul/tar-action@v1.1.0
113 | with:
114 | command: c
115 | files: |
116 | ${{ matrix.asset_name }}-${{ github.ref_name }}
117 | outPath: ${{ matrix.asset_name }}-${{ github.ref_name }}-${{ matrix.target }}.tar.gz
118 |
119 | - name: Upload release archive
120 | uses: actions/upload-release-asset@v1
121 | env:
122 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
123 | with:
124 | upload_url: ${{ needs.create-release.outputs.upload_url }}
125 | asset_path: ${{ matrix.asset_name }}-${{ github.ref_name }}-${{ matrix.target }}.tar.gz
126 | asset_name: ${{ matrix.asset_name }}-${{ github.ref_name }}-${{ matrix.target }}.tar.gz
127 | asset_content_type: application/octet-stream
128 |
129 | - name: Build DEB package
130 | if: matrix.build != 'freebsd'
131 | uses: defGuard/fpm-action@main
132 | with:
133 | fpm_args: "${{ matrix.asset_name }}-${{ github.ref_name }}=/usr/sbin/defguard-gateway defguard-gateway.service=/usr/lib/systemd/system/defguard-gateway.service example-config.toml=/etc/defguard/gateway.toml.sample"
134 | fpm_opts: "--architecture ${{ matrix.arch }} --debug --output-type deb --version ${{ env.VERSION }} --package defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.deb --after-install after-install.sh"
135 |
136 | - name: Upload DEB
137 | if: matrix.build != 'freebsd'
138 | uses: actions/upload-release-asset@v1
139 | env:
140 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
141 | with:
142 | upload_url: ${{ needs.create-release.outputs.upload_url }}
143 | asset_path: defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.deb
144 | asset_name: defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.deb
145 | asset_content_type: application/octet-stream
146 |
147 | - name: Build RPM package
148 | if: matrix.build == 'linux'
149 | uses: defGuard/fpm-action@main
150 | with:
151 | fpm_args: "${{ matrix.asset_name }}-${{ github.ref_name }}=/usr/sbin/defguard-gateway defguard-gateway.service=/usr/lib/systemd/system/defguard-gateway.service example-config.toml=/etc/defguard/gateway.toml.sample"
152 | fpm_opts: "--architecture ${{ matrix.arch }} --debug --output-type rpm --version ${{ env.VERSION }} --package defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.rpm --after-install after-install.sh"
153 |
154 | - name: Upload RPM
155 | if: matrix.build == 'linux'
156 | uses: actions/upload-release-asset@v1
157 | env:
158 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
159 | with:
160 | upload_url: ${{ needs.create-release.outputs.upload_url }}
161 | asset_path: defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.rpm
162 | asset_name: defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.rpm
163 | asset_content_type: application/octet-stream
164 |
165 | - name: Build FreeBSD package
166 | if: matrix.build == 'freebsd'
167 | uses: defGuard/fpm-action@main
168 | with:
169 | fpm_args:
170 | "${{ matrix.asset_name }}-${{ github.ref_name }}=/usr/local/sbin/defguard-gateway
171 | defguard-gateway.service.freebsd=/usr/local/etc/rc.d/defguard_gateway
172 | example-config.toml=/etc/defguard/gateway.toml.sample
173 | defguard-rc.conf=/etc/rc.conf.d/defguard_gateway"
174 | fpm_opts: "--architecture ${{ matrix.arch }} --debug --output-type freebsd --version ${{ env.VERSION }} --package defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.pkg --freebsd-osversion '*'"
175 |
176 | - name: Upload FreeBSD
177 | if: matrix.build == 'freebsd'
178 | uses: actions/upload-release-asset@v1
179 | env:
180 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
181 | with:
182 | upload_url: ${{ needs.create-release.outputs.upload_url }}
183 | asset_path: defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.pkg
184 | asset_name: defguard-gateway_${{ env.VERSION }}_${{ matrix.target }}.pkg
185 | asset_content_type: application/octet-stream
186 |
187 | - name: Build OPNsense package
188 | if: matrix.build == 'freebsd'
189 | uses: defGuard/fpm-action@main
190 | with:
191 | fpm_args:
192 | "${{ matrix.asset_name }}-${{ github.ref_name }}=/usr/local/sbin/defguard-gateway
193 | defguard-gateway.service.freebsd=/usr/local/etc/rc.d/defguard_gateway
194 | example-config.toml=/etc/defguard/gateway.toml.sample
195 | defguard-rc.conf=/etc/rc.conf.d/defguard_gateway
196 | opnsense/src/etc/=/usr/local/etc/
197 | opnsense/src/opnsense/=/usr/local/opnsense/"
198 | fpm_opts: "--architecture ${{ matrix.arch }} --debug --output-type freebsd --version ${{ env.VERSION }} --package defguard-gateway_${{ env.VERSION }}_x86_64-unknown-opnsense.pkg --freebsd-osversion '*'"
199 |
200 | - name: Upload OPNsense package
201 | if: matrix.build == 'freebsd'
202 | uses: actions/upload-release-asset@v1
203 | env:
204 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
205 | with:
206 | upload_url: ${{ needs.create-release.outputs.upload_url }}
207 | asset_path: defguard-gateway_${{ env.VERSION }}_x86_64-unknown-opnsense.pkg
208 | asset_name: defguard-gateway_${{ env.VERSION }}_x86_64-unknown-opnsense.pkg
209 | asset_content_type: application/octet-stream
210 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /.idea
3 | .envrc
4 | .direnv/
5 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "proto"]
2 | path = proto
3 | url = ../proto.git
4 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: v4.4.0
4 | hooks:
5 | - id: trailing-whitespace
6 | - id: end-of-file-fixer
7 | - id: check-added-large-files
8 | - repo: https://github.com/doublify/pre-commit-rust
9 | rev: v1.0
10 | hooks:
11 | - id: fmt
12 | - id: clippy
13 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "defguard-gateway"
3 | version = "1.4.0"
4 | edition = "2021"
5 |
6 | [dependencies]
7 | axum = { version = "0.8", features = ["macros"] }
8 | base64 = "0.22"
9 | clap = { version = "4.5", features = ["derive", "env"] }
10 | defguard_wireguard_rs = { git = "https://github.com/DefGuard/wireguard-rs.git", rev = "v0.7.5" }
11 | env_logger = "0.11"
12 | gethostname = "1.0"
13 | ipnetwork = "0.21"
14 | libc = { version = "0.2", default-features = false }
15 | log = "0.4"
16 | prost = "0.13"
17 | serde = { version = "1.0", features = ["derive"] }
18 | syslog = "7.0"
19 | thiserror = "2.0"
20 | tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
21 | tokio-stream = { version = "0.1", features = [] }
22 | toml = { version = "0.8", default-features = false, features = ["parse"] }
23 | tonic = { version = "0.12", default-features = false, features = [
24 | "codegen",
25 | "gzip",
26 | "prost",
27 | "tls-native-roots",
28 | ] }
29 |
30 | [target.'cfg(target_os = "linux")'.dependencies]
31 | nftnl = { git = "https://github.com/DefGuard/nftnl-rs.git", rev = "1a1147271f43b9d7182a114bb056a5224c35d38f" }
32 | mnl = "0.2"
33 |
34 | [target.'cfg(any(target_os = "freebsd", target_os = "macos", target_os = "netbsd"))'.dependencies]
35 | nix = { version = "0.30", default-features = false, features = ["ioctl"] }
36 |
37 | [dev-dependencies]
38 | tokio = { version = "1", features = ["io-std", "io-util"] }
39 | tonic = { version = "0.12", default-features = false, features = [
40 | "codegen",
41 | "prost",
42 | "transport",
43 | ] }
44 | x25519-dalek = { version = "2.0", features = ["getrandom", "static_secrets"] }
45 |
46 | [build-dependencies]
47 | tonic-build = { version = "0.12" }
48 | vergen-git2 = { version = "1.0", features = ["build"] }
49 |
50 | [profile.release]
51 | codegen-units = 1
52 | panic = "abort"
53 | lto = "thin"
54 | strip = "symbols"
55 |
--------------------------------------------------------------------------------
/Cross.toml:
--------------------------------------------------------------------------------
1 | [target.x86_64-unknown-linux-gnu]
2 | image = "ghcr.io/defguard/cross:x86_64-unknown-linux-gnu"
3 | pre-build = [
4 | "dpkg --add-architecture $CROSS_DEB_ARCH",
5 | "apt-get update && apt-get install --assume-yes unzip libnftnl-dev:$CROSS_DEB_ARCH libmnl-dev:$CROSS_DEB_ARCH",
6 | "PB_REL='https://github.com/protocolbuffers/protobuf/releases'",
7 | "PB_VERSION='3.20.0' && curl -LO $PB_REL/download/v$PB_VERSION/protoc-$PB_VERSION-linux-x86_64.zip",
8 | "unzip protoc-$PB_VERSION-linux-x86_64.zip bin/protoc include/google/* -d /usr",
9 | ]
10 |
11 | [target.armv7-unknown-linux-gnueabihf]
12 | image = "ghcr.io/defguard/cross:armv7-unknown-linux-gnueabihf"
13 | pre-build = [
14 | "dpkg --add-architecture $CROSS_DEB_ARCH",
15 | "apt-get update && apt-get install --assume-yes unzip libnftnl-dev:$CROSS_DEB_ARCH libmnl-dev:$CROSS_DEB_ARCH",
16 | "PB_REL='https://github.com/protocolbuffers/protobuf/releases'",
17 | "PB_VERSION='3.20.0' && curl -LO $PB_REL/download/v$PB_VERSION/protoc-$PB_VERSION-linux-x86_64.zip",
18 | "unzip protoc-$PB_VERSION-linux-x86_64.zip bin/protoc include/google/* -d /usr",
19 | ]
20 |
21 |
22 | [target.aarch64-unknown-linux-gnu]
23 | image = "ghcr.io/defguard/cross:aarch64-unknown-linux-gnu"
24 | pre-build = [
25 | "dpkg --add-architecture $CROSS_DEB_ARCH",
26 | "apt-get update && apt-get install --assume-yes unzip libnftnl-dev libnftnl-dev:$CROSS_DEB_ARCH libmnl-dev libmnl-dev:$CROSS_DEB_ARCH",
27 | "PB_REL='https://github.com/protocolbuffers/protobuf/releases'",
28 | "PB_VERSION='3.20.0' && curl -LO $PB_REL/download/v$PB_VERSION/protoc-$PB_VERSION-linux-x86_64.zip",
29 | "unzip protoc-$PB_VERSION-linux-x86_64.zip bin/protoc include/google/* -d /usr",
30 | ]
31 |
32 | [target.x86_64-unknown-freebsd]
33 | image = "ghcr.io/defguard/cross:x86_64-unknown-freebsd"
34 | pre-build = [
35 | "apt-get update && apt-get install --assume-yes unzip",
36 | "PB_REL='https://github.com/protocolbuffers/protobuf/releases'",
37 | "PB_VERSION='3.20.0' && curl -LO $PB_REL/download/v$PB_VERSION/protoc-$PB_VERSION-linux-x86_64.zip",
38 | "unzip protoc-$PB_VERSION-linux-x86_64.zip bin/protoc include/google/* -d /usr",
39 | ]
40 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM rust:1-slim as builder
2 |
3 | RUN apt-get update && apt-get -y install protobuf-compiler libnftnl-dev libmnl-dev
4 | WORKDIR /app
5 | COPY . .
6 | RUN cargo build --release
7 |
8 | FROM debian:bookworm-slim
9 | RUN apt-get update && apt-get -y --no-install-recommends install \
10 | iproute2 wireguard-tools sudo ca-certificates iptables ebtables nftables && \
11 | apt-get clean && rm -rf /var/lib/apt/lists/*
12 | WORKDIR /app
13 | COPY --from=builder /app/target/release/defguard-gateway /usr/local/bin
14 | ENTRYPOINT ["/usr/local/bin/defguard-gateway"]
15 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | # Dual license info
2 | The code in this repository is available under a dual licensing model:
3 |
4 | 1. Open Source License: The code, except for the contents of the "src/enterprise" directory, is licensed under the AGPL license (this license). This applies to the open core components of the software.
5 | 2. Enterprise License: All code in this repository (including within the "src/enterprise" directory) is licensed under a separate Enterprise License (see file src/enterprise/LICENSE.md).
6 |
7 | # GNU AFFERO GENERAL PUBLIC LICENSE
8 |
9 | Version 3, 19 November 2007
10 |
11 | Copyright (C) 2007 Free Software Foundation, Inc.
12 |
13 |
14 | Everyone is permitted to copy and distribute verbatim copies of this
15 | license document, but changing it is not allowed.
16 |
17 | ## Preamble
18 |
19 | The GNU Affero General Public License is a free, copyleft license for
20 | software and other kinds of works, specifically designed to ensure
21 | cooperation with the community in the case of network server software.
22 |
23 | The licenses for most software and other practical works are designed
24 | to take away your freedom to share and change the works. By contrast,
25 | our General Public Licenses are intended to guarantee your freedom to
26 | share and change all versions of a program--to make sure it remains
27 | free software for all its users.
28 |
29 | When we speak of free software, we are referring to freedom, not
30 | price. Our General Public Licenses are designed to make sure that you
31 | have the freedom to distribute copies of free software (and charge for
32 | them if you wish), that you receive source code or can get it if you
33 | want it, that you can change the software or use pieces of it in new
34 | free programs, and that you know you can do these things.
35 |
36 | Developers that use our General Public Licenses protect your rights
37 | with two steps: (1) assert copyright on the software, and (2) offer
38 | you this License which gives you legal permission to copy, distribute
39 | and/or modify the software.
40 |
41 | A secondary benefit of defending all users' freedom is that
42 | improvements made in alternate versions of the program, if they
43 | receive widespread use, become available for other developers to
44 | incorporate. Many developers of free software are heartened and
45 | encouraged by the resulting cooperation. However, in the case of
46 | software used on network servers, this result may fail to come about.
47 | The GNU General Public License permits making a modified version and
48 | letting the public access it on a server without ever releasing its
49 | source code to the public.
50 |
51 | The GNU Affero General Public License is designed specifically to
52 | ensure that, in such cases, the modified source code becomes available
53 | to the community. It requires the operator of a network server to
54 | provide the source code of the modified version running there to the
55 | users of that server. Therefore, public use of a modified version, on
56 | a publicly accessible server, gives the public access to the source
57 | code of the modified version.
58 |
59 | An older license, called the Affero General Public License and
60 | published by Affero, was designed to accomplish similar goals. This is
61 | a different license, not a version of the Affero GPL, but Affero has
62 | released a new version of the Affero GPL which permits relicensing
63 | under this license.
64 |
65 | The precise terms and conditions for copying, distribution and
66 | modification follow.
67 |
68 | ## TERMS AND CONDITIONS
69 |
70 | ### 0. Definitions.
71 |
72 | "This License" refers to version 3 of the GNU Affero General Public
73 | License.
74 |
75 | "Copyright" also means copyright-like laws that apply to other kinds
76 | of works, such as semiconductor masks.
77 |
78 | "The Program" refers to any copyrightable work licensed under this
79 | License. Each licensee is addressed as "you". "Licensees" and
80 | "recipients" may be individuals or organizations.
81 |
82 | To "modify" a work means to copy from or adapt all or part of the work
83 | in a fashion requiring copyright permission, other than the making of
84 | an exact copy. The resulting work is called a "modified version" of
85 | the earlier work or a work "based on" the earlier work.
86 |
87 | A "covered work" means either the unmodified Program or a work based
88 | on the Program.
89 |
90 | To "propagate" a work means to do anything with it that, without
91 | permission, would make you directly or secondarily liable for
92 | infringement under applicable copyright law, except executing it on a
93 | computer or modifying a private copy. Propagation includes copying,
94 | distribution (with or without modification), making available to the
95 | public, and in some countries other activities as well.
96 |
97 | To "convey" a work means any kind of propagation that enables other
98 | parties to make or receive copies. Mere interaction with a user
99 | through a computer network, with no transfer of a copy, is not
100 | conveying.
101 |
102 | An interactive user interface displays "Appropriate Legal Notices" to
103 | the extent that it includes a convenient and prominently visible
104 | feature that (1) displays an appropriate copyright notice, and (2)
105 | tells the user that there is no warranty for the work (except to the
106 | extent that warranties are provided), that licensees may convey the
107 | work under this License, and how to view a copy of this License. If
108 | the interface presents a list of user commands or options, such as a
109 | menu, a prominent item in the list meets this criterion.
110 |
111 | ### 1. Source Code.
112 |
113 | The "source code" for a work means the preferred form of the work for
114 | making modifications to it. "Object code" means any non-source form of
115 | a work.
116 |
117 | A "Standard Interface" means an interface that either is an official
118 | standard defined by a recognized standards body, or, in the case of
119 | interfaces specified for a particular programming language, one that
120 | is widely used among developers working in that language.
121 |
122 | The "System Libraries" of an executable work include anything, other
123 | than the work as a whole, that (a) is included in the normal form of
124 | packaging a Major Component, but which is not part of that Major
125 | Component, and (b) serves only to enable use of the work with that
126 | Major Component, or to implement a Standard Interface for which an
127 | implementation is available to the public in source code form. A
128 | "Major Component", in this context, means a major essential component
129 | (kernel, window system, and so on) of the specific operating system
130 | (if any) on which the executable work runs, or a compiler used to
131 | produce the work, or an object code interpreter used to run it.
132 |
133 | The "Corresponding Source" for a work in object code form means all
134 | the source code needed to generate, install, and (for an executable
135 | work) run the object code and to modify the work, including scripts to
136 | control those activities. However, it does not include the work's
137 | System Libraries, or general-purpose tools or generally available free
138 | programs which are used unmodified in performing those activities but
139 | which are not part of the work. For example, Corresponding Source
140 | includes interface definition files associated with source files for
141 | the work, and the source code for shared libraries and dynamically
142 | linked subprograms that the work is specifically designed to require,
143 | such as by intimate data communication or control flow between those
144 | subprograms and other parts of the work.
145 |
146 | The Corresponding Source need not include anything that users can
147 | regenerate automatically from other parts of the Corresponding Source.
148 |
149 | The Corresponding Source for a work in source code form is that same
150 | work.
151 |
152 | ### 2. Basic Permissions.
153 |
154 | All rights granted under this License are granted for the term of
155 | copyright on the Program, and are irrevocable provided the stated
156 | conditions are met. This License explicitly affirms your unlimited
157 | permission to run the unmodified Program. The output from running a
158 | covered work is covered by this License only if the output, given its
159 | content, constitutes a covered work. This License acknowledges your
160 | rights of fair use or other equivalent, as provided by copyright law.
161 |
162 | You may make, run and propagate covered works that you do not convey,
163 | without conditions so long as your license otherwise remains in force.
164 | You may convey covered works to others for the sole purpose of having
165 | them make modifications exclusively for you, or provide you with
166 | facilities for running those works, provided that you comply with the
167 | terms of this License in conveying all material for which you do not
168 | control copyright. Those thus making or running the covered works for
169 | you must do so exclusively on your behalf, under your direction and
170 | control, on terms that prohibit them from making any copies of your
171 | copyrighted material outside their relationship with you.
172 |
173 | Conveying under any other circumstances is permitted solely under the
174 | conditions stated below. Sublicensing is not allowed; section 10 makes
175 | it unnecessary.
176 |
177 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
178 |
179 | No covered work shall be deemed part of an effective technological
180 | measure under any applicable law fulfilling obligations under article
181 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
182 | similar laws prohibiting or restricting circumvention of such
183 | measures.
184 |
185 | When you convey a covered work, you waive any legal power to forbid
186 | circumvention of technological measures to the extent such
187 | circumvention is effected by exercising rights under this License with
188 | respect to the covered work, and you disclaim any intention to limit
189 | operation or modification of the work as a means of enforcing, against
190 | the work's users, your or third parties' legal rights to forbid
191 | circumvention of technological measures.
192 |
193 | ### 4. Conveying Verbatim Copies.
194 |
195 | You may convey verbatim copies of the Program's source code as you
196 | receive it, in any medium, provided that you conspicuously and
197 | appropriately publish on each copy an appropriate copyright notice;
198 | keep intact all notices stating that this License and any
199 | non-permissive terms added in accord with section 7 apply to the code;
200 | keep intact all notices of the absence of any warranty; and give all
201 | recipients a copy of this License along with the Program.
202 |
203 | You may charge any price or no price for each copy that you convey,
204 | and you may offer support or warranty protection for a fee.
205 |
206 | ### 5. Conveying Modified Source Versions.
207 |
208 | You may convey a work based on the Program, or the modifications to
209 | produce it from the Program, in the form of source code under the
210 | terms of section 4, provided that you also meet all of these
211 | conditions:
212 |
213 | - a) The work must carry prominent notices stating that you modified
214 | it, and giving a relevant date.
215 | - b) The work must carry prominent notices stating that it is
216 | released under this License and any conditions added under
217 | section 7. This requirement modifies the requirement in section 4
218 | to "keep intact all notices".
219 | - c) You must license the entire work, as a whole, under this
220 | License to anyone who comes into possession of a copy. This
221 | License will therefore apply, along with any applicable section 7
222 | additional terms, to the whole of the work, and all its parts,
223 | regardless of how they are packaged. This License gives no
224 | permission to license the work in any other way, but it does not
225 | invalidate such permission if you have separately received it.
226 | - d) If the work has interactive user interfaces, each must display
227 | Appropriate Legal Notices; however, if the Program has interactive
228 | interfaces that do not display Appropriate Legal Notices, your
229 | work need not make them do so.
230 |
231 | A compilation of a covered work with other separate and independent
232 | works, which are not by their nature extensions of the covered work,
233 | and which are not combined with it such as to form a larger program,
234 | in or on a volume of a storage or distribution medium, is called an
235 | "aggregate" if the compilation and its resulting copyright are not
236 | used to limit the access or legal rights of the compilation's users
237 | beyond what the individual works permit. Inclusion of a covered work
238 | in an aggregate does not cause this License to apply to the other
239 | parts of the aggregate.
240 |
241 | ### 6. Conveying Non-Source Forms.
242 |
243 | You may convey a covered work in object code form under the terms of
244 | sections 4 and 5, provided that you also convey the machine-readable
245 | Corresponding Source under the terms of this License, in one of these
246 | ways:
247 |
248 | - a) Convey the object code in, or embodied in, a physical product
249 | (including a physical distribution medium), accompanied by the
250 | Corresponding Source fixed on a durable physical medium
251 | customarily used for software interchange.
252 | - b) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by a
254 | written offer, valid for at least three years and valid for as
255 | long as you offer spare parts or customer support for that product
256 | model, to give anyone who possesses the object code either (1) a
257 | copy of the Corresponding Source for all the software in the
258 | product that is covered by this License, on a durable physical
259 | medium customarily used for software interchange, for a price no
260 | more than your reasonable cost of physically performing this
261 | conveying of source, or (2) access to copy the Corresponding
262 | Source from a network server at no charge.
263 | - c) Convey individual copies of the object code with a copy of the
264 | written offer to provide the Corresponding Source. This
265 | alternative is allowed only occasionally and noncommercially, and
266 | only if you received the object code with such an offer, in accord
267 | with subsection 6b.
268 | - d) Convey the object code by offering access from a designated
269 | place (gratis or for a charge), and offer equivalent access to the
270 | Corresponding Source in the same way through the same place at no
271 | further charge. You need not require recipients to copy the
272 | Corresponding Source along with the object code. If the place to
273 | copy the object code is a network server, the Corresponding Source
274 | may be on a different server (operated by you or a third party)
275 | that supports equivalent copying facilities, provided you maintain
276 | clear directions next to the object code saying where to find the
277 | Corresponding Source. Regardless of what server hosts the
278 | Corresponding Source, you remain obligated to ensure that it is
279 | available for as long as needed to satisfy these requirements.
280 | - e) Convey the object code using peer-to-peer transmission,
281 | provided you inform other peers where the object code and
282 | Corresponding Source of the work are being offered to the general
283 | public at no charge under subsection 6d.
284 |
285 | A separable portion of the object code, whose source code is excluded
286 | from the Corresponding Source as a System Library, need not be
287 | included in conveying the object code work.
288 |
289 | A "User Product" is either (1) a "consumer product", which means any
290 | tangible personal property which is normally used for personal,
291 | family, or household purposes, or (2) anything designed or sold for
292 | incorporation into a dwelling. In determining whether a product is a
293 | consumer product, doubtful cases shall be resolved in favor of
294 | coverage. For a particular product received by a particular user,
295 | "normally used" refers to a typical or common use of that class of
296 | product, regardless of the status of the particular user or of the way
297 | in which the particular user actually uses, or expects or is expected
298 | to use, the product. A product is a consumer product regardless of
299 | whether the product has substantial commercial, industrial or
300 | non-consumer uses, unless such uses represent the only significant
301 | mode of use of the product.
302 |
303 | "Installation Information" for a User Product means any methods,
304 | procedures, authorization keys, or other information required to
305 | install and execute modified versions of a covered work in that User
306 | Product from a modified version of its Corresponding Source. The
307 | information must suffice to ensure that the continued functioning of
308 | the modified object code is in no case prevented or interfered with
309 | solely because modification has been made.
310 |
311 | If you convey an object code work under this section in, or with, or
312 | specifically for use in, a User Product, and the conveying occurs as
313 | part of a transaction in which the right of possession and use of the
314 | User Product is transferred to the recipient in perpetuity or for a
315 | fixed term (regardless of how the transaction is characterized), the
316 | Corresponding Source conveyed under this section must be accompanied
317 | by the Installation Information. But this requirement does not apply
318 | if neither you nor any third party retains the ability to install
319 | modified object code on the User Product (for example, the work has
320 | been installed in ROM).
321 |
322 | The requirement to provide Installation Information does not include a
323 | requirement to continue to provide support service, warranty, or
324 | updates for a work that has been modified or installed by the
325 | recipient, or for the User Product in which it has been modified or
326 | installed. Access to a network may be denied when the modification
327 | itself materially and adversely affects the operation of the network
328 | or violates the rules and protocols for communication across the
329 | network.
330 |
331 | Corresponding Source conveyed, and Installation Information provided,
332 | in accord with this section must be in a format that is publicly
333 | documented (and with an implementation available to the public in
334 | source code form), and must require no special password or key for
335 | unpacking, reading or copying.
336 |
337 | ### 7. Additional Terms.
338 |
339 | "Additional permissions" are terms that supplement the terms of this
340 | License by making exceptions from one or more of its conditions.
341 | Additional permissions that are applicable to the entire Program shall
342 | be treated as though they were included in this License, to the extent
343 | that they are valid under applicable law. If additional permissions
344 | apply only to part of the Program, that part may be used separately
345 | under those permissions, but the entire Program remains governed by
346 | this License without regard to the additional permissions.
347 |
348 | When you convey a copy of a covered work, you may at your option
349 | remove any additional permissions from that copy, or from any part of
350 | it. (Additional permissions may be written to require their own
351 | removal in certain cases when you modify the work.) You may place
352 | additional permissions on material, added by you to a covered work,
353 | for which you have or can give appropriate copyright permission.
354 |
355 | Notwithstanding any other provision of this License, for material you
356 | add to a covered work, you may (if authorized by the copyright holders
357 | of that material) supplement the terms of this License with terms:
358 |
359 | - a) Disclaiming warranty or limiting liability differently from the
360 | terms of sections 15 and 16 of this License; or
361 | - b) Requiring preservation of specified reasonable legal notices or
362 | author attributions in that material or in the Appropriate Legal
363 | Notices displayed by works containing it; or
364 | - c) Prohibiting misrepresentation of the origin of that material,
365 | or requiring that modified versions of such material be marked in
366 | reasonable ways as different from the original version; or
367 | - d) Limiting the use for publicity purposes of names of licensors
368 | or authors of the material; or
369 | - e) Declining to grant rights under trademark law for use of some
370 | trade names, trademarks, or service marks; or
371 | - f) Requiring indemnification of licensors and authors of that
372 | material by anyone who conveys the material (or modified versions
373 | of it) with contractual assumptions of liability to the recipient,
374 | for any liability that these contractual assumptions directly
375 | impose on those licensors and authors.
376 |
377 | All other non-permissive additional terms are considered "further
378 | restrictions" within the meaning of section 10. If the Program as you
379 | received it, or any part of it, contains a notice stating that it is
380 | governed by this License along with a term that is a further
381 | restriction, you may remove that term. If a license document contains
382 | a further restriction but permits relicensing or conveying under this
383 | License, you may add to a covered work material governed by the terms
384 | of that license document, provided that the further restriction does
385 | not survive such relicensing or conveying.
386 |
387 | If you add terms to a covered work in accord with this section, you
388 | must place, in the relevant source files, a statement of the
389 | additional terms that apply to those files, or a notice indicating
390 | where to find the applicable terms.
391 |
392 | Additional terms, permissive or non-permissive, may be stated in the
393 | form of a separately written license, or stated as exceptions; the
394 | above requirements apply either way.
395 |
396 | ### 8. Termination.
397 |
398 | You may not propagate or modify a covered work except as expressly
399 | provided under this License. Any attempt otherwise to propagate or
400 | modify it is void, and will automatically terminate your rights under
401 | this License (including any patent licenses granted under the third
402 | paragraph of section 11).
403 |
404 | However, if you cease all violation of this License, then your license
405 | from a particular copyright holder is reinstated (a) provisionally,
406 | unless and until the copyright holder explicitly and finally
407 | terminates your license, and (b) permanently, if the copyright holder
408 | fails to notify you of the violation by some reasonable means prior to
409 | 60 days after the cessation.
410 |
411 | Moreover, your license from a particular copyright holder is
412 | reinstated permanently if the copyright holder notifies you of the
413 | violation by some reasonable means, this is the first time you have
414 | received notice of violation of this License (for any work) from that
415 | copyright holder, and you cure the violation prior to 30 days after
416 | your receipt of the notice.
417 |
418 | Termination of your rights under this section does not terminate the
419 | licenses of parties who have received copies or rights from you under
420 | this License. If your rights have been terminated and not permanently
421 | reinstated, you do not qualify to receive new licenses for the same
422 | material under section 10.
423 |
424 | ### 9. Acceptance Not Required for Having Copies.
425 |
426 | You are not required to accept this License in order to receive or run
427 | a copy of the Program. Ancillary propagation of a covered work
428 | occurring solely as a consequence of using peer-to-peer transmission
429 | to receive a copy likewise does not require acceptance. However,
430 | nothing other than this License grants you permission to propagate or
431 | modify any covered work. These actions infringe copyright if you do
432 | not accept this License. Therefore, by modifying or propagating a
433 | covered work, you indicate your acceptance of this License to do so.
434 |
435 | ### 10. Automatic Licensing of Downstream Recipients.
436 |
437 | Each time you convey a covered work, the recipient automatically
438 | receives a license from the original licensors, to run, modify and
439 | propagate that work, subject to this License. You are not responsible
440 | for enforcing compliance by third parties with this License.
441 |
442 | An "entity transaction" is a transaction transferring control of an
443 | organization, or substantially all assets of one, or subdividing an
444 | organization, or merging organizations. If propagation of a covered
445 | work results from an entity transaction, each party to that
446 | transaction who receives a copy of the work also receives whatever
447 | licenses to the work the party's predecessor in interest had or could
448 | give under the previous paragraph, plus a right to possession of the
449 | Corresponding Source of the work from the predecessor in interest, if
450 | the predecessor has it or can get it with reasonable efforts.
451 |
452 | You may not impose any further restrictions on the exercise of the
453 | rights granted or affirmed under this License. For example, you may
454 | not impose a license fee, royalty, or other charge for exercise of
455 | rights granted under this License, and you may not initiate litigation
456 | (including a cross-claim or counterclaim in a lawsuit) alleging that
457 | any patent claim is infringed by making, using, selling, offering for
458 | sale, or importing the Program or any portion of it.
459 |
460 | ### 11. Patents.
461 |
462 | A "contributor" is a copyright holder who authorizes use under this
463 | License of the Program or a work on which the Program is based. The
464 | work thus licensed is called the contributor's "contributor version".
465 |
466 | A contributor's "essential patent claims" are all patent claims owned
467 | or controlled by the contributor, whether already acquired or
468 | hereafter acquired, that would be infringed by some manner, permitted
469 | by this License, of making, using, or selling its contributor version,
470 | but do not include claims that would be infringed only as a
471 | consequence of further modification of the contributor version. For
472 | purposes of this definition, "control" includes the right to grant
473 | patent sublicenses in a manner consistent with the requirements of
474 | this License.
475 |
476 | Each contributor grants you a non-exclusive, worldwide, royalty-free
477 | patent license under the contributor's essential patent claims, to
478 | make, use, sell, offer for sale, import and otherwise run, modify and
479 | propagate the contents of its contributor version.
480 |
481 | In the following three paragraphs, a "patent license" is any express
482 | agreement or commitment, however denominated, not to enforce a patent
483 | (such as an express permission to practice a patent or covenant not to
484 | sue for patent infringement). To "grant" such a patent license to a
485 | party means to make such an agreement or commitment not to enforce a
486 | patent against the party.
487 |
488 | If you convey a covered work, knowingly relying on a patent license,
489 | and the Corresponding Source of the work is not available for anyone
490 | to copy, free of charge and under the terms of this License, through a
491 | publicly available network server or other readily accessible means,
492 | then you must either (1) cause the Corresponding Source to be so
493 | available, or (2) arrange to deprive yourself of the benefit of the
494 | patent license for this particular work, or (3) arrange, in a manner
495 | consistent with the requirements of this License, to extend the patent
496 | license to downstream recipients. "Knowingly relying" means you have
497 | actual knowledge that, but for the patent license, your conveying the
498 | covered work in a country, or your recipient's use of the covered work
499 | in a country, would infringe one or more identifiable patents in that
500 | country that you have reason to believe are valid.
501 |
502 | If, pursuant to or in connection with a single transaction or
503 | arrangement, you convey, or propagate by procuring conveyance of, a
504 | covered work, and grant a patent license to some of the parties
505 | receiving the covered work authorizing them to use, propagate, modify
506 | or convey a specific copy of the covered work, then the patent license
507 | you grant is automatically extended to all recipients of the covered
508 | work and works based on it.
509 |
510 | A patent license is "discriminatory" if it does not include within the
511 | scope of its coverage, prohibits the exercise of, or is conditioned on
512 | the non-exercise of one or more of the rights that are specifically
513 | granted under this License. You may not convey a covered work if you
514 | are a party to an arrangement with a third party that is in the
515 | business of distributing software, under which you make payment to the
516 | third party based on the extent of your activity of conveying the
517 | work, and under which the third party grants, to any of the parties
518 | who would receive the covered work from you, a discriminatory patent
519 | license (a) in connection with copies of the covered work conveyed by
520 | you (or copies made from those copies), or (b) primarily for and in
521 | connection with specific products or compilations that contain the
522 | covered work, unless you entered into that arrangement, or that patent
523 | license was granted, prior to 28 March 2007.
524 |
525 | Nothing in this License shall be construed as excluding or limiting
526 | any implied license or other defenses to infringement that may
527 | otherwise be available to you under applicable patent law.
528 |
529 | ### 12. No Surrender of Others' Freedom.
530 |
531 | If conditions are imposed on you (whether by court order, agreement or
532 | otherwise) that contradict the conditions of this License, they do not
533 | excuse you from the conditions of this License. If you cannot convey a
534 | covered work so as to satisfy simultaneously your obligations under
535 | this License and any other pertinent obligations, then as a
536 | consequence you may not convey it at all. For example, if you agree to
537 | terms that obligate you to collect a royalty for further conveying
538 | from those to whom you convey the Program, the only way you could
539 | satisfy both those terms and this License would be to refrain entirely
540 | from conveying the Program.
541 |
542 | ### 13. Remote Network Interaction; Use with the GNU General Public License.
543 |
544 | Notwithstanding any other provision of this License, if you modify the
545 | Program, your modified version must prominently offer all users
546 | interacting with it remotely through a computer network (if your
547 | version supports such interaction) an opportunity to receive the
548 | Corresponding Source of your version by providing access to the
549 | Corresponding Source from a network server at no charge, through some
550 | standard or customary means of facilitating copying of software. This
551 | Corresponding Source shall include the Corresponding Source for any
552 | work covered by version 3 of the GNU General Public License that is
553 | incorporated pursuant to the following paragraph.
554 |
555 | Notwithstanding any other provision of this License, you have
556 | permission to link or combine any covered work with a work licensed
557 | under version 3 of the GNU General Public License into a single
558 | combined work, and to convey the resulting work. The terms of this
559 | License will continue to apply to the part which is the covered work,
560 | but the work with which it is combined will remain governed by version
561 | 3 of the GNU General Public License.
562 |
563 | ### 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions
566 | of the GNU Affero General Public License from time to time. Such new
567 | versions will be similar in spirit to the present version, but may
568 | differ in detail to address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the Program
571 | specifies that a certain numbered version of the GNU Affero General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU Affero General Public License, you may choose any version ever
577 | published by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future versions
580 | of the GNU Affero General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | ### 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
594 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
595 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
596 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
597 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
598 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
599 | CORRECTION.
600 |
601 | ### 16. Limitation of Liability.
602 |
603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
605 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
606 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
607 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
608 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
609 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
610 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
611 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
612 |
613 | ### 17. Interpretation of Sections 15 and 16.
614 |
615 | If the disclaimer of warranty and limitation of liability provided
616 | above cannot be given local legal effect according to their terms,
617 | reviewing courts shall apply local law that most closely approximates
618 | an absolute waiver of all civil liability in connection with the
619 | Program, unless a warranty or assumption of liability accompanies a
620 | copy of the Program in return for a fee.
621 |
622 | END OF TERMS AND CONDITIONS
623 |
624 | ## How to Apply These Terms to Your New Programs
625 |
626 | If you develop a new program, and you want it to be of the greatest
627 | possible use to the public, the best way to achieve this is to make it
628 | free software which everyone can redistribute and change under these
629 | terms.
630 |
631 | To do so, attach the following notices to the program. It is safest to
632 | attach them to the start of each source file to most effectively state
633 | the exclusion of warranty; and each file should have at least the
634 | "copyright" line and a pointer to where the full notice is found.
635 |
636 |
637 | Copyright (C)
638 |
639 | This program is free software: you can redistribute it and/or modify
640 | it under the terms of the GNU Affero General Public License as
641 | published by the Free Software Foundation, either version 3 of the
642 | License, or (at your option) any later version.
643 |
644 | This program is distributed in the hope that it will be useful,
645 | but WITHOUT ANY WARRANTY; without even the implied warranty of
646 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
647 | GNU Affero General Public License for more details.
648 |
649 | You should have received a copy of the GNU Affero General Public License
650 | along with this program. If not, see .
651 |
652 | Also add information on how to contact you by electronic and paper
653 | mail.
654 |
655 | If your software can interact with users remotely through a computer
656 | network, you should also make sure that it provides a way for users to
657 | get its source. For example, if your program is a web application, its
658 | interface could display a "Source" link that leads users to an archive
659 | of the code. There are many ways you could offer source, and different
660 | solutions will be better for different programs; see section 13 for
661 | the specific requirements.
662 |
663 | You should also get your employer (if you work as a programmer) or
664 | school, if any, to sign a "copyright disclaimer" for the program, if
665 | necessary. For more information on this, and how to apply and follow
666 | the GNU AGPL, see .
667 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | **defguard gateway** is a client service for [defguard](https://github.com/DefGuard/defguard) which can be used to create your own [WireGuard:tm:](https://www.wireguard.com/) VPN servers for secure and private networking.
6 |
7 | To learn more about the system see our [documentation](https://defguard.gitbook.io).
8 |
9 | ## Quick start
10 |
11 | If you already have your defguard instance running you can set up a gateway by following our [deployment guide](https://defguard.gitbook.io/defguard/features/setting-up-your-instance/gateway).
12 |
13 | ## Documentation
14 |
15 | See the [documentation](https://defguard.gitbook.io) for more information.
16 |
17 | ## Community and Support
18 |
19 | Find us on Matrix: [#defguard:teonite.com](https://matrix.to/#/#defguard:teonite.com)
20 |
21 | ## Contribution
22 |
23 | Please review the [Contributing guide](https://defguard.gitbook.io/defguard/for-developers/contributing) for information on how to get started contributing to the project. You might also find our [environment setup guide](https://defguard.gitbook.io/defguard/for-developers/dev-env-setup) handy.
24 |
25 | # Legal
26 | WireGuard is [registered trademarks](https://www.wireguard.com/trademark-policy/) of Jason A. Donenfeld.
27 |
--------------------------------------------------------------------------------
/after-install.sh:
--------------------------------------------------------------------------------
1 | if systemctl is-enabled defguard-gateway --quiet; then
2 | systemctl restart defguard-gateway
3 | fi
4 |
--------------------------------------------------------------------------------
/build.rs:
--------------------------------------------------------------------------------
1 | use vergen_git2::{Emitter, Git2Builder};
2 |
3 | fn main() -> Result<(), Box> {
4 | // set VERGEN_GIT_SHA env variable based on git commit hash
5 | let git2 = Git2Builder::default().branch(true).sha(true).build()?;
6 | Emitter::default().add_instructions(&git2)?.emit()?;
7 |
8 | // compiling protos using path on build time
9 | let mut config = tonic_build::Config::new();
10 | // enable optional fields
11 | config.protoc_arg("--experimental_allow_proto3_optional");
12 | tonic_build::configure().compile_protos_with_config(
13 | config,
14 | &[
15 | "proto/wireguard/gateway.proto",
16 | "proto/enterprise/firewall/firewall.proto",
17 | ],
18 | &["proto/wireguard", "proto/enterprise/firewall"],
19 | )?;
20 | println!("cargo:rerun-if-changed=proto");
21 | Ok(())
22 | }
23 |
--------------------------------------------------------------------------------
/defguard-gateway.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=defguard VPN gateway service
3 | Documentation=https://defguard.gitbook.io/defguard/
4 | Wants=network-online.target
5 | After=network-online.target
6 |
7 | [Service]
8 | ExecReload=/bin/kill -HUP $MAINPID
9 | ExecStart=/usr/sbin/defguard-gateway --config /etc/defguard/gateway.toml
10 | KillMode=process
11 | KillSignal=SIGINT
12 | LimitNOFILE=65536
13 | LimitNPROC=infinity
14 | Restart=on-failure
15 | RestartSec=2
16 | TasksMax=infinity
17 | OOMScoreAdjust=-1000
18 |
19 | [Install]
20 | WantedBy=multi-user.target
21 |
--------------------------------------------------------------------------------
/defguard-gateway.service.freebsd:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # PROVIDE: defguard-gateway
4 | # REQUIRE: NETWORKING wireguard
5 | # KEYWORD: shutdown
6 |
7 | . /etc/rc.subr
8 |
9 | name="defguard_gateway"
10 | rcvar=defguard_gateway_enable
11 | command="/usr/local/sbin/defguard-gateway"
12 | config="/etc/defguard/gateway.toml"
13 | start_cmd="${name}_start"
14 |
15 | defguard_gateway_start()
16 | {
17 | ${command} --config ${config} &
18 | }
19 |
20 | load_rc_config $name
21 | run_rc_command "$1"
22 |
--------------------------------------------------------------------------------
/defguard-rc.conf:
--------------------------------------------------------------------------------
1 | defguard_gateway_enable="YES"
2 |
--------------------------------------------------------------------------------
/deny.toml:
--------------------------------------------------------------------------------
1 | # This template contains all of the possible sections and their default values
2 |
3 | # Note that all fields that take a lint level have these possible values:
4 | # * deny - An error will be produced and the check will fail
5 | # * warn - A warning will be produced, but the check will not fail
6 | # * allow - No warning or error will be produced, though in some cases a note
7 | # will be
8 |
9 | # The values provided in this template are the default values that will be used
10 | # when any section or field is not specified in your own configuration
11 |
12 | # Root options
13 |
14 | # The graph table configures how the dependency graph is constructed and thus
15 | # which crates the checks are performed against
16 | [graph]
17 | # If 1 or more target triples (and optionally, target_features) are specified,
18 | # only the specified targets will be checked when running `cargo deny check`.
19 | # This means, if a particular package is only ever used as a target specific
20 | # dependency, such as, for example, the `nix` crate only being used via the
21 | # `target_family = "unix"` configuration, that only having windows targets in
22 | # this list would mean the nix crate, as well as any of its exclusive
23 | # dependencies not shared by any other crates, would be ignored, as the target
24 | # list here is effectively saying which targets you are building for.
25 | targets = [
26 | # The triple can be any string, but only the target triples built in to
27 | # rustc (as of 1.40) can be checked against actual config expressions
28 | #"x86_64-unknown-linux-musl",
29 | # You can also specify which target_features you promise are enabled for a
30 | # particular target. target_features are currently not validated against
31 | # the actual valid features supported by the target architecture.
32 | #{ triple = "wasm32-unknown-unknown", features = ["atomics"] },
33 | ]
34 | # When creating the dependency graph used as the source of truth when checks are
35 | # executed, this field can be used to prune crates from the graph, removing them
36 | # from the view of cargo-deny. This is an extremely heavy hammer, as if a crate
37 | # is pruned from the graph, all of its dependencies will also be pruned unless
38 | # they are connected to another crate in the graph that hasn't been pruned,
39 | # so it should be used with care. The identifiers are [Package ID Specifications]
40 | # (https://doc.rust-lang.org/cargo/reference/pkgid-spec.html)
41 | #exclude = []
42 | # If true, metadata will be collected with `--all-features`. Note that this can't
43 | # be toggled off if true, if you want to conditionally enable `--all-features` it
44 | # is recommended to pass `--all-features` on the cmd line instead
45 | all-features = false
46 | # If true, metadata will be collected with `--no-default-features`. The same
47 | # caveat with `all-features` applies
48 | no-default-features = false
49 | # If set, these feature will be enabled when collecting metadata. If `--features`
50 | # is specified on the cmd line they will take precedence over this option.
51 | #features = []
52 |
53 | # The output table provides options for how/if diagnostics are outputted
54 | [output]
55 | # When outputting inclusion graphs in diagnostics that include features, this
56 | # option can be used to specify the depth at which feature edges will be added.
57 | # This option is included since the graphs can be quite large and the addition
58 | # of features from the crate(s) to all of the graph roots can be far too verbose.
59 | # This option can be overridden via `--feature-depth` on the cmd line
60 | feature-depth = 1
61 |
62 | # This section is considered when running `cargo deny check advisories`
63 | # More documentation for the advisories section can be found here:
64 | # https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html
65 | [advisories]
66 | # The path where the advisory databases are cloned/fetched into
67 | #db-path = "$CARGO_HOME/advisory-dbs"
68 | # The url(s) of the advisory databases to use
69 | #db-urls = ["https://github.com/rustsec/advisory-db"]
70 | # A list of advisory IDs to ignore. Note that ignored advisories will still
71 | # output a note when they are encountered.
72 | ignore = [
73 | { id = "RUSTSEC-2024-0436", reason = "Unmaintained" },
74 | ]
75 | # If this is true, then cargo deny will use the git executable to fetch advisory database.
76 | # If this is false, then it uses a built-in git library.
77 | # Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support.
78 | # See Git Authentication for more information about setting up git authentication.
79 | #git-fetch-with-cli = true
80 |
81 | # This section is considered when running `cargo deny check licenses`
82 | # More documentation for the licenses section can be found here:
83 | # https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html
84 | [licenses]
85 | # List of explicitly allowed licenses
86 | # See https://spdx.org/licenses/ for list of possible licenses
87 | # [possible values: any SPDX 3.11 short identifier (+ optional exception)].
88 | allow = [
89 | "MIT",
90 | "Apache-2.0",
91 | "Apache-2.0 WITH LLVM-exception",
92 | "MPL-2.0",
93 | "BSD-3-Clause",
94 | "Unicode-3.0",
95 | "Unicode-DFS-2016", # unicode-ident
96 | "Zlib",
97 | "ISC",
98 | "BSL-1.0",
99 | "0BSD",
100 | "CC0-1.0",
101 | "OpenSSL",
102 | "CDLA-Permissive-2.0",
103 | ]
104 | # The confidence threshold for detecting a license from license text.
105 | # The higher the value, the more closely the license text must be to the
106 | # canonical license text of a valid SPDX license file.
107 | # [possible values: any between 0.0 and 1.0].
108 | confidence-threshold = 0.8
109 | # Allow 1 or more licenses on a per-crate basis, so that particular licenses
110 | # aren't accepted for every possible crate as with the normal allow list
111 | exceptions = [
112 | { allow = ["AGPL-3.0"], crate = "defguard-gateway" },
113 | ]
114 |
115 | # Some crates don't have (easily) machine readable licensing information,
116 | # adding a clarification entry for it allows you to manually specify the
117 | # licensing information
118 | #[[licenses.clarify]]
119 | # The package spec the clarification applies to
120 | #crate = "ring"
121 | # The SPDX expression for the license requirements of the crate
122 | #expression = "MIT AND ISC AND OpenSSL"
123 | # One or more files in the crate's source used as the "source of truth" for
124 | # the license expression. If the contents match, the clarification will be used
125 | # when running the license check, otherwise the clarification will be ignored
126 | # and the crate will be checked normally, which may produce warnings or errors
127 | # depending on the rest of your configuration
128 | #license-files = [
129 | # Each entry is a crate relative path, and the (opaque) hash of its contents
130 | #{ path = "LICENSE", hash = 0xbd0eed23 }
131 | #]
132 |
133 | [licenses.private]
134 | # If true, ignores workspace crates that aren't published, or are only
135 | # published to private registries.
136 | # To see how to mark a crate as unpublished (to the official registry),
137 | # visit https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field.
138 | ignore = false
139 | # One or more private registries that you might publish crates to, if a crate
140 | # is only published to private registries, and ignore is true, the crate will
141 | # not have its license(s) checked
142 | registries = [
143 | #"https://sekretz.com/registry
144 | ]
145 |
146 | # This section is considered when running `cargo deny check bans`.
147 | # More documentation about the 'bans' section can be found here:
148 | # https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html
149 | [bans]
150 | # Lint level for when multiple versions of the same crate are detected
151 | multiple-versions = "warn"
152 | # Lint level for when a crate version requirement is `*`
153 | wildcards = "allow"
154 | # The graph highlighting used when creating dotgraphs for crates
155 | # with multiple versions
156 | # * lowest-version - The path to the lowest versioned duplicate is highlighted
157 | # * simplest-path - The path to the version with the fewest edges is highlighted
158 | # * all - Both lowest-version and simplest-path are used
159 | highlight = "all"
160 | # The default lint level for `default` features for crates that are members of
161 | # the workspace that is being checked. This can be overridden by allowing/denying
162 | # `default` on a crate-by-crate basis if desired.
163 | workspace-default-features = "allow"
164 | # The default lint level for `default` features for external crates that are not
165 | # members of the workspace. This can be overridden by allowing/denying `default`
166 | # on a crate-by-crate basis if desired.
167 | external-default-features = "allow"
168 | # List of crates that are allowed. Use with care!
169 | allow = [
170 | #"ansi_term@0.11.0",
171 | #{ crate = "ansi_term@0.11.0", reason = "you can specify a reason it is allowed" },
172 | ]
173 | # List of crates to deny
174 | deny = [
175 | #"ansi_term@0.11.0",
176 | #{ crate = "ansi_term@0.11.0", reason = "you can specify a reason it is banned" },
177 | # Wrapper crates can optionally be specified to allow the crate when it
178 | # is a direct dependency of the otherwise banned crate
179 | #{ crate = "ansi_term@0.11.0", wrappers = ["this-crate-directly-depends-on-ansi_term"] },
180 | ]
181 |
182 | # List of features to allow/deny
183 | # Each entry the name of a crate and a version range. If version is
184 | # not specified, all versions will be matched.
185 | #[[bans.features]]
186 | #crate = "reqwest"
187 | # Features to not allow
188 | #deny = ["json"]
189 | # Features to allow
190 | #allow = [
191 | # "rustls",
192 | # "__rustls",
193 | # "__tls",
194 | # "hyper-rustls",
195 | # "rustls",
196 | # "rustls-pemfile",
197 | # "rustls-tls-webpki-roots",
198 | # "tokio-rustls",
199 | # "webpki-roots",
200 | #]
201 | # If true, the allowed features must exactly match the enabled feature set. If
202 | # this is set there is no point setting `deny`
203 | #exact = true
204 |
205 | # Certain crates/versions that will be skipped when doing duplicate detection.
206 | skip = [
207 | #"ansi_term@0.11.0",
208 | #{ crate = "ansi_term@0.11.0", reason = "you can specify a reason why it can't be updated/removed" },
209 | ]
210 | # Similarly to `skip` allows you to skip certain crates during duplicate
211 | # detection. Unlike skip, it also includes the entire tree of transitive
212 | # dependencies starting at the specified crate, up to a certain depth, which is
213 | # by default infinite.
214 | skip-tree = [
215 | #"ansi_term@0.11.0", # will be skipped along with _all_ of its direct and transitive dependencies
216 | #{ crate = "ansi_term@0.11.0", depth = 20 },
217 | ]
218 |
219 | # This section is considered when running `cargo deny check sources`.
220 | # More documentation about the 'sources' section can be found here:
221 | # https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html
222 | [sources]
223 | # Lint level for what to happen when a crate from a crate registry that is not
224 | # in the allow list is encountered
225 | unknown-registry = "warn"
226 | # Lint level for what to happen when a crate from a git repository that is not
227 | # in the allow list is encountered
228 | unknown-git = "warn"
229 | # List of URLs for allowed crate registries. Defaults to the crates.io index
230 | # if not specified. If it is specified but empty, no registries are allowed.
231 | allow-registry = ["https://github.com/rust-lang/crates.io-index"]
232 | # List of URLs for allowed Git repositories
233 | allow-git = []
234 |
235 | [sources.allow-org]
236 | # github.com organizations to allow git sources for
237 | github = []
238 | # gitlab.com organizations to allow git sources for
239 | gitlab = []
240 | # bitbucket.org organizations to allow git sources for
241 | bitbucket = []
242 |
--------------------------------------------------------------------------------
/docs/header.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DefGuard/gateway/c20856249cb73ec9d042327f2f193a016c0a6656/docs/header.png
--------------------------------------------------------------------------------
/example-config.toml:
--------------------------------------------------------------------------------
1 | # This is an example config file for defguard VPN gateway
2 | # To use it fill in actual values for your deployment below
3 |
4 | # Required: secret token generated by defguard
5 | # NOTE: must replace default with actual value
6 | token = ""
7 | # Required: defguard server gRPC endpoint URL
8 | # NOTE: must replace default with actual value
9 | grpc_url = ""
10 | # Optional: gateway name which will be displayed in defguard web UI
11 | name = "Gateway A"
12 | # Required: use userspace WireGuard implementation (e.g. wireguard-go)
13 | userspace = false
14 | # Optional: path to TLS cert file
15 | # grpc_ca = cert.pem
16 | # Required: how often should interface stat updates be sent to defguard server (in seconds)
17 | stats_period = 60
18 | # Required: name of WireGuard interface
19 | ifname = "wg0"
20 | # Optional: write PID to this file
21 | # pidfile = defguard-gateway.pid
22 | # Required: enable logging to syslog
23 | use_syslog = false
24 | # Required: which syslog facility to use
25 | syslog_facility = "LOG_USER"
26 | # Required: which socket to use for logging
27 | syslog_socket = "/var/run/log"
28 |
29 | # Optional: Command which will be run before bringing interface up
30 | # Example: Allow all traffic through WireGuard interface:
31 | #pre_up = "/path/to/iptables -A INPUT -i wg0 -j ACCEPT
32 | # example with multiple commands - add them to a shell script
33 | #pre_up = "/path/to/shell /path/to/script"
34 |
35 | # Optional: Command which will be run after bringing interface up
36 | # Example: Add a default route after WireGuard interface is up:
37 | #post_up = "/path/to/ip route add default via 192.168.1.1 dev wg0"
38 |
39 |
40 | # Optional: Command which will be run before bringing interface down
41 | # Example: Remove WireGuard-related firewall rules before interface is taken down:
42 | #pre_down = "/path/to/iptables -D INPUT -i wg0 -j ACCEPT"
43 |
44 | # Optional: Command which will be run after bringing interface down
45 | # Example: Remove the default route after WireGuard interface is down:
46 | #post_down = "/pat/to/ip route del default via 192.168.1.1 dev wg0"
47 |
48 | # A HTTP port that will expose the REST HTTP gateway health status
49 | # STATUS CODES:
50 | # 200 - Gateway is working and is connected to CORE
51 | # 503 - gateway works but is not connected to CORE
52 | #health_port = 55003
53 |
54 | # Optional: Enable automatic masquerading of traffic by the firewall
55 | #masquerade = true
56 |
57 | # Optional: Set the priority of the Defguard forward chain
58 | #fw_priority = 0
59 |
--------------------------------------------------------------------------------
/examples/server.rs:
--------------------------------------------------------------------------------
1 | use std::{
2 | collections::HashMap,
3 | io::{stdout, Write},
4 | net::{IpAddr, Ipv4Addr, SocketAddr},
5 | sync::{Arc, Mutex},
6 | };
7 |
8 | use defguard_gateway::proto;
9 | use defguard_wireguard_rs::{
10 | host::{Host, Peer},
11 | key::Key,
12 | net::IpAddrMask,
13 | };
14 | use tokio::{
15 | io::{AsyncBufReadExt, BufReader},
16 | sync::{
17 | mpsc::{self, UnboundedSender},
18 | watch::{self, Receiver, Sender},
19 | },
20 | };
21 | use tokio_stream::wrappers::UnboundedReceiverStream;
22 | use tonic::{transport::Server, Request, Response, Status, Streaming};
23 |
24 | pub struct HostConfig {
25 | name: String,
26 | addresses: Vec,
27 | host: Host,
28 | }
29 |
30 | type ClientMap = HashMap>>;
31 |
32 | struct GatewayServer {
33 | config_rx: Receiver,
34 | clients: Arc>,
35 | }
36 |
37 | impl GatewayServer {
38 | pub fn new(config_rx: Receiver, clients: Arc>) -> Self {
39 | // watch for changes in host configuration
40 | let task_clients = clients.clone();
41 | let mut task_config_rx = config_rx.clone();
42 | tokio::spawn(async move {
43 | while task_config_rx.changed().await.is_ok() {
44 | let config = (&*task_config_rx.borrow()).into();
45 | let update = proto::gateway::Update {
46 | update_type: proto::gateway::UpdateType::Modify as i32,
47 | update: Some(proto::gateway::update::Update::Network(config)),
48 | };
49 | task_clients.lock().unwrap().retain(
50 | move |_addr, tx: &mut UnboundedSender>| {
51 | tx.send(Ok(update.clone())).is_ok()
52 | },
53 | );
54 | }
55 | });
56 |
57 | Self { config_rx, clients }
58 | }
59 | }
60 |
61 | impl From<&HostConfig> for proto::gateway::Configuration {
62 | fn from(host_config: &HostConfig) -> Self {
63 | Self {
64 | name: host_config.name.clone(),
65 | prvkey: host_config
66 | .host
67 | .private_key
68 | .as_ref()
69 | .map(ToString::to_string)
70 | .unwrap_or_default(),
71 | addresses: host_config
72 | .addresses
73 | .iter()
74 | .map(ToString::to_string)
75 | .collect(),
76 | port: u32::from(host_config.host.listen_port),
77 | peers: host_config.host.peers.values().map(Into::into).collect(),
78 | firewall_config: None,
79 | }
80 | }
81 | }
82 |
83 | #[tonic::async_trait]
84 | impl proto::gateway::gateway_service_server::GatewayService for GatewayServer {
85 | type UpdatesStream = UnboundedReceiverStream>;
86 |
87 | async fn config(
88 | &self,
89 | request: Request,
90 | ) -> Result, Status> {
91 | let address = request.remote_addr().unwrap();
92 | eprintln!("CONFIG connected from: {address}");
93 | Ok(Response::new((&*self.config_rx.borrow()).into()))
94 | }
95 |
96 | async fn stats(
97 | &self,
98 | request: Request>,
99 | ) -> Result, Status> {
100 | let address = request.remote_addr().unwrap();
101 | eprintln!("STATS connected from: {address}");
102 |
103 | let mut stream = request.into_inner();
104 | while let Some(peer_stats) = stream.message().await? {
105 | eprintln!("STATS {peer_stats:?}");
106 | }
107 | Ok(Response::new(()))
108 | }
109 |
110 | async fn updates(&self, request: Request<()>) -> Result, Status> {
111 | let address = request.remote_addr().unwrap();
112 | eprintln!("UPDATES connected from: {address}");
113 |
114 | let (tx, rx) = mpsc::unbounded_channel();
115 | self.clients.lock().unwrap().insert(address, tx);
116 |
117 | Ok(Response::new(UnboundedReceiverStream::new(rx)))
118 | }
119 | }
120 |
121 | pub async fn cli(tx: Sender, clients: Arc>) {
122 | let mut stdin = BufReader::new(tokio::io::stdin());
123 | println!(
124 | "a|addr address - set host address\n\
125 | c|peer key - create peer with public key\n\
126 | d|del key - delete peer with public key\n\
127 | k|key key - set private key\n\
128 | p|port port - set listening port\n\
129 | q|quit - quit\n\
130 | "
131 | );
132 | loop {
133 | print!("> ");
134 | stdout().flush().unwrap();
135 | let mut line = String::new();
136 | let _count = stdin.read_line(&mut line).await.unwrap();
137 | let mut token_iter = line.split_whitespace();
138 | if let Some(keyword) = token_iter.next() {
139 | match keyword {
140 | "a" | "addr" => {
141 | let mut addresses = Vec::new();
142 | for address in token_iter.by_ref() {
143 | match address.parse() {
144 | Ok(ipaddr) => addresses.push(ipaddr),
145 | Err(err) => eprintln!("Skipping {address}: {err}"),
146 | }
147 | }
148 | if !addresses.is_empty() {
149 | tx.send_modify(|config| config.addresses = addresses);
150 | }
151 | }
152 | "c" | "peer" => {
153 | if let Some(key) = token_iter.next() {
154 | if let Ok(key) = Key::try_from(key) {
155 | let peer = Peer::new(key.clone());
156 |
157 | let update = proto::gateway::Update {
158 | update_type: proto::gateway::UpdateType::Create as i32,
159 | update: Some(proto::gateway::update::Update::Peer((&peer).into())),
160 | };
161 | clients.lock().unwrap().retain(
162 | move |addr,
163 | tx: &mut UnboundedSender<
164 | Result,
165 | >| {
166 | eprintln!("Sending peer update to {addr}");
167 | tx.send(Ok(update.clone())).is_ok()
168 | },
169 | );
170 |
171 | // modify HostConfig, but do not notify the receiver
172 | tx.send_if_modified(|config| {
173 | config.host.peers.insert(key, peer);
174 | false
175 | });
176 | } else {
177 | eprintln!("Parse error");
178 | }
179 | }
180 | }
181 | "d" | "del" => {
182 | if let Some(key) = token_iter.next() {
183 | if let Ok(key) = Key::try_from(key) {
184 | let peer = Peer::new(key);
185 |
186 | let update = proto::gateway::Update {
187 | update_type: proto::gateway::UpdateType::Delete as i32,
188 | update: Some(proto::gateway::update::Update::Peer((&peer).into())),
189 | };
190 | clients.lock().unwrap().retain(
191 | move |addr,
192 | tx: &mut UnboundedSender<
193 | Result,
194 | >| {
195 | eprintln!("Sending peer update to {addr}");
196 | tx.send(Ok(update.clone())).is_ok()
197 | },
198 | );
199 |
200 | // modify HostConfig, but do not notify the receiver
201 | // tx.send_if_modified(|config| {
202 | // config.host.peers.retain(|entry| entry.public_key != peer.public_key);
203 | // false
204 | // });
205 | } else {
206 | eprintln!("Parse error");
207 | }
208 | }
209 | }
210 | "k" | "key" => {
211 | if let Some(key) = token_iter.next() {
212 | if let Ok(key) = Key::try_from(key) {
213 | tx.send_modify(|config| config.host.private_key = Some(key));
214 | } else {
215 | eprintln!("Parse error");
216 | }
217 | }
218 | }
219 | "p" | "port" => {
220 | if let Some(port) = token_iter.next() {
221 | if let Ok(port) = port.parse() {
222 | tx.send_modify(|config| config.host.listen_port = port);
223 | } else {
224 | eprintln!("Parse error");
225 | }
226 | }
227 | }
228 | "q" | "quit" => break,
229 | _ => eprintln!("Unknown command"),
230 | }
231 | }
232 | }
233 | }
234 |
235 | pub async fn grpc(
236 | config_rx: Receiver,
237 | clients: Arc>,
238 | ) -> Result<(), tonic::transport::Error> {
239 | let gateway_service = proto::gateway::gateway_service_server::GatewayServiceServer::new(
240 | GatewayServer::new(config_rx, clients),
241 | );
242 | let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 50055); // TODO: port as an option
243 | Server::builder()
244 | .add_service(gateway_service)
245 | .serve(addr)
246 | .await
247 | }
248 |
249 | #[tokio::main]
250 | async fn main() -> Result<(), Box> {
251 | let configuration = HostConfig {
252 | name: "demo".into(),
253 | host: Host::new(
254 | 50505,
255 | Key::try_from("JPcD7xOfOAULx+cTdgzB3dIv6nvqqbmlACYzxrfJ4Dw=").unwrap(),
256 | ),
257 | addresses: vec!["192.168.68.68".parse().unwrap()],
258 | };
259 | let (config_tx, config_rx) = watch::channel(configuration);
260 | let clients = Arc::new(Mutex::new(HashMap::new()));
261 | tokio::select! {
262 | _ = grpc(config_rx, clients.clone()) => eprintln!("gRPC completed"),
263 | () = cli(config_tx, clients) => eprintln!("CLI completed")
264 | };
265 |
266 | Ok(())
267 | }
268 |
--------------------------------------------------------------------------------
/flake.lock:
--------------------------------------------------------------------------------
1 | {
2 | "nodes": {
3 | "flake-utils": {
4 | "inputs": {
5 | "systems": "systems"
6 | },
7 | "locked": {
8 | "lastModified": 1731533236,
9 | "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
10 | "owner": "numtide",
11 | "repo": "flake-utils",
12 | "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
13 | "type": "github"
14 | },
15 | "original": {
16 | "owner": "numtide",
17 | "repo": "flake-utils",
18 | "type": "github"
19 | }
20 | },
21 | "nixpkgs": {
22 | "locked": {
23 | "lastModified": 1746904237,
24 | "narHash": "sha256-3e+AVBczosP5dCLQmMoMEogM57gmZ2qrVSrmq9aResQ=",
25 | "owner": "NixOS",
26 | "repo": "nixpkgs",
27 | "rev": "d89fc19e405cb2d55ce7cc114356846a0ee5e956",
28 | "type": "github"
29 | },
30 | "original": {
31 | "owner": "NixOS",
32 | "ref": "nixos-unstable",
33 | "repo": "nixpkgs",
34 | "type": "github"
35 | }
36 | },
37 | "root": {
38 | "inputs": {
39 | "flake-utils": "flake-utils",
40 | "nixpkgs": "nixpkgs",
41 | "rust-overlay": "rust-overlay"
42 | }
43 | },
44 | "rust-overlay": {
45 | "inputs": {
46 | "nixpkgs": [
47 | "nixpkgs"
48 | ]
49 | },
50 | "locked": {
51 | "lastModified": 1747190175,
52 | "narHash": "sha256-s33mQ2s5L/2nyllhRTywgECNZyCqyF4MJeM3vG/GaRo=",
53 | "owner": "oxalica",
54 | "repo": "rust-overlay",
55 | "rev": "58160be7abad81f6f8cb53120d5b88c16e01c06d",
56 | "type": "github"
57 | },
58 | "original": {
59 | "owner": "oxalica",
60 | "repo": "rust-overlay",
61 | "type": "github"
62 | }
63 | },
64 | "systems": {
65 | "locked": {
66 | "lastModified": 1681028828,
67 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
68 | "owner": "nix-systems",
69 | "repo": "default",
70 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
71 | "type": "github"
72 | },
73 | "original": {
74 | "owner": "nix-systems",
75 | "repo": "default",
76 | "type": "github"
77 | }
78 | }
79 | },
80 | "root": "root",
81 | "version": 7
82 | }
83 |
--------------------------------------------------------------------------------
/flake.nix:
--------------------------------------------------------------------------------
1 | {
2 | description = "Rust development flake";
3 |
4 | inputs = {
5 | nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
6 | flake-utils.url = "github:numtide/flake-utils";
7 | rust-overlay = {
8 | url = "github:oxalica/rust-overlay";
9 | inputs = {
10 | nixpkgs.follows = "nixpkgs";
11 | };
12 | };
13 | };
14 |
15 | outputs = {
16 | nixpkgs,
17 | flake-utils,
18 | rust-overlay,
19 | ...
20 | }:
21 | flake-utils.lib.eachDefaultSystem (system: let
22 | overlays = [(import rust-overlay)];
23 | pkgs = import nixpkgs {
24 | inherit system overlays;
25 | };
26 | rustToolchain = pkgs.rust-bin.stable.latest.default.override {
27 | extensions = ["rust-analyzer" "rust-src" "rustfmt" "clippy"];
28 | };
29 | in {
30 | devShells.default = pkgs.mkShell {
31 | packages = with pkgs; [
32 | pkg-config
33 | openssl
34 | protobuf
35 | sqlx-cli
36 | rustToolchain
37 | libnftnl
38 | libmnl
39 | ];
40 | };
41 | });
42 | }
43 |
--------------------------------------------------------------------------------
/opnsense/Makefile:
--------------------------------------------------------------------------------
1 | PLUGIN_NAME= defguard-gateway
2 | PLUGIN_VERSION= 1.0.1
3 | PLUGIN_COMMENT= Gateway service for Defguard
4 | PLUGIN_MAINTAINER= defguard@community.net
5 |
6 | .include "../../Mk/plugins.mk"
7 |
--------------------------------------------------------------------------------
/opnsense/src/etc/inc/plugins.inc.d/defguardgateway.inc:
--------------------------------------------------------------------------------
1 | "Defguard Gateway",
8 | "configd" => [
9 | "start" => ["defguard_gateway start"],
10 | "restart" => ["defguard_gateway restart"],
11 | "stop" => ["defguard_gateway stop"],
12 | ],
13 | "name" => "defguard_gateway",
14 | "nocheck" => true,
15 | ];
16 |
17 | return $services;
18 | }
19 |
20 | function defguardgateway_interfaces()
21 | {
22 | $interfaces = [];
23 |
24 | $interfaces["defguard"] = [
25 | "descr" => gettext("Defguard (Group)"),
26 | "if" => "defguard",
27 | "virtual" => true,
28 | "enable" => true,
29 | "type" => "group",
30 | "networks" => [],
31 | ];
32 |
33 | return $interfaces;
34 | }
35 |
36 | function defguardgateway_devices()
37 | {
38 | $names = [];
39 |
40 | $interface = (new OPNsense\DefguardGateway\DefguardGateway())->general
41 | ->IfName;
42 |
43 | $devices[] = [
44 | "configurable" => false,
45 | "pattern" => "^wg",
46 | "type" => "wireguard",
47 | "volatile" => true,
48 | "names" => [
49 | (string) $interface => [
50 | "descr" => sprintf(
51 | "%s (Defguard Gateway)",
52 | (string) $interface
53 | ),
54 | "ifdescr" => "WireGuard interface used by Defguard Gateway",
55 | "name" => (string) $interface,
56 | ],
57 | ],
58 | ];
59 |
60 | return $devices;
61 | }
62 |
63 | function defguardgateway_enabled()
64 | {
65 | global $config;
66 |
67 | return isset($config['OPNsense']['defguardgateway']['general']['Enabled']) &&
68 | $config['OPNsense']['defguardgateway']['general']['Enabled'] == 1;
69 | }
70 |
71 | function defguardgateway_firewall($fw)
72 | {
73 | if (!defguardgateway_enabled()) {
74 | return;
75 | }
76 |
77 | // $fw->registerAnchor('defguard/*', 'nat', 1, 'head');
78 | // $fw->registerAnchor('defguard/*', 'rdr', 1, 'head');
79 | $fw->registerAnchor('defguard/*', 'fw', 1, 'head', true);
80 | }
81 |
--------------------------------------------------------------------------------
/opnsense/src/opnsense/mvc/app/controllers/OPNsense/DefguardGateway/Api/ServiceController.php:
--------------------------------------------------------------------------------
1 | view->pick("OPNsense/DefguardGateway/index");
8 | $this->view->generalForm = $this->getForm("general");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/opnsense/src/opnsense/mvc/app/controllers/OPNsense/DefguardGateway/forms/general.xml:
--------------------------------------------------------------------------------
1 |
105 |
--------------------------------------------------------------------------------
/opnsense/src/opnsense/mvc/app/models/OPNsense/DefguardGateway/DefguardGateway.php:
--------------------------------------------------------------------------------
1 |
2 | //OPNsense/defguardgateway
3 | Defguard Gateway plugin for OPNsense
4 |
5 |
6 |
7 | 0
8 | Y
9 |
10 |
11 | 0
12 | Y
13 |
14 |
15 | Y
16 | please add authorization token
17 |
18 |
19 | Y
20 | please specify Defguard Core gRPC URL
21 |
22 |
23 | N
24 |
25 |
26 | N
27 |
28 |
29 | 0
30 | Y
31 |
32 |
33 | N
34 |
35 |
36 | /var/run/log
37 | Y
38 |
39 |
40 | LOG_USER
41 | Y
42 |
43 |
44 | Y
45 | wg0
46 |
47 |
48 | Y
49 | 60
50 |
51 |
52 | N
53 |
54 |
55 | N
56 |
57 |
58 | N
59 |
60 |
61 | N
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/opnsense/src/opnsense/mvc/app/models/OPNsense/DefguardGateway/Menu/Menu.xml:
--------------------------------------------------------------------------------
1 |
6 |
--------------------------------------------------------------------------------
/opnsense/src/opnsense/mvc/app/views/OPNsense/DefguardGateway/index.volt:
--------------------------------------------------------------------------------
1 |