├── .github └── workflows │ ├── ci.yml │ └── release.yml ├── BUILD.md ├── CHANGELOG.md ├── LICENSE ├── README.md ├── files ├── bin │ └── .gitkeep ├── json │ └── ebpf_config.json.sample ├── scripts │ ├── revert_ebpf_router.py │ ├── set_xdp_redirect.py │ ├── start_ebpf_router.py │ ├── start_ebpf_tunnel.py │ └── user_rules.sh.sample └── services │ ├── fw-init.service │ ├── ziti-fw-init.service │ └── ziti-wrapper.service └── src ├── Makefile ├── install.sh ├── zfw.c ├── zfw_tc_ingress.c ├── zfw_tc_outbound_track.c ├── zfw_tunnel_wrapper.c └── zfw_xdp_tun_ingress.c /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: release 3 | 4 | on: [push] 5 | 6 | 7 | env: 8 | APP_NAME: 'zfw' 9 | MAINTAINER: 'Robert Caamano' 10 | DESC: 'An ebpf based statefull fw for openziti edge-routers and tunnelers' 11 | 12 | jobs: 13 | build_amd64_release: 14 | runs-on: ubuntu-22.04 15 | outputs: 16 | version: ${{ steps.version.outputs.version }} 17 | strategy: 18 | matrix: 19 | goos: [linux] 20 | ziti_type: [tunnel, router] 21 | goarch: [amd64] 22 | steps: 23 | - name: Check out code 24 | uses: actions/checkout@v3 25 | 26 | - name: Install EBPF Packages 27 | run: | 28 | sudo apt-get update -qq 29 | sudo apt-get upgrade -yqq 30 | sudo apt-get install -y jq gcc clang libc6-dev-i386 libbpfcc-dev libbpf-dev libjson-c-dev 31 | 32 | - name: Compile Object file from Source 33 | run: | 34 | clang -D BPF_MAX_ENTRIES=100000 -g -O2 -Wall -Wextra -target bpf -c -o files/bin/zfw_tc_ingress.o src/zfw_tc_ingress.c 35 | clang -g -O2 -Wall -Wextra -target bpf -c -o files/bin/zfw_xdp_tun_ingress.o src/zfw_xdp_tun_ingress.c 36 | clang -g -O2 -Wall -Wextra -target bpf -c -o files/bin/zfw_tc_outbound_track.o src/zfw_tc_outbound_track.c 37 | clang -D BPF_MAX_ENTRIES=100000 -O2 -lbpf -Wall -Wextra -o files/bin/zfw src/zfw.c 38 | gcc -o files/bin/zfw_tunnwrapper src/zfw_tunnel_wrapper.c -l json-c 39 | 40 | - name: Get version 41 | run: echo "version=`files/bin/zfw -V`" >> $GITHUB_OUTPUT 42 | id: version 43 | 44 | - name: Deb directory 45 | run: echo "deb_dir=${{ env.APP_NAME }}-${{ matrix.ziti_type }}_${{ steps.version.outputs.version }}_${{ matrix.goarch }}" >> $GITHUB_OUTPUT 46 | id: deb_dir 47 | 48 | - name: Deb Object File 49 | run: | 50 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN 51 | touch ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 52 | echo Package: ${{ env.APP_NAME }}-${{ matrix.ziti_type }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 53 | echo Version: ${{ steps.version.outputs.version }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 54 | echo Architecture: ${{ matrix.goarch }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 55 | echo Maintainer: ${{ env.MAINTAINER }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 56 | echo Description: ${{ env.DESC }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 57 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user 58 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc 59 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system 60 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin 61 | cp -p files/bin/zfw_xdp_tun_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 62 | cp -p files/bin/zfw_tc_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 63 | cp -p files/bin/zfw_tc_outbound_track.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 64 | cp -p files/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 65 | cp -p files/scripts/start_ebpf_${{ matrix.ziti_type }}.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 66 | cp -p files/scripts/set_xdp_redirect.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 67 | cp -p files/scripts/user_rules.sh.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/ 68 | cp -p files/json/ebpf_config.json.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc/ 69 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw 70 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/set_xdp_redirect.py 71 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/start_ebpf_${{ matrix.ziti_type }}.py 72 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/user_rules.sh.sample 73 | ln -s /opt/openziti/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin/zfw 74 | 75 | - name: Set Deb Predepends 76 | if: ${{ matrix.ziti_type == 'tunnel' }} 77 | run: | 78 | echo 'Pre-Depends: ziti-edge-tunnel (>= 0.22.5)' >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 79 | cp -p files/services/ziti-fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 80 | cp -p files/services/ziti-wrapper.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 81 | cp -p files/bin/zfw_tunnwrapper ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 82 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw_tunnwrapper 83 | 84 | - name: Standalone FW service and router revert 85 | if: ${{ matrix.ziti_type == 'router' }} 86 | run: | 87 | cp -p files/services/fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 88 | cp -p files/scripts/revert_ebpf_router.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 89 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/revert_ebpf_router.py 90 | 91 | - name: Build Deb package 92 | run: | 93 | dpkg-deb --build -Z gzip --root-owner-group ${{ steps.deb_dir.outputs.deb_dir }} 94 | 95 | - uses: actions/upload-artifact@v3 96 | with: 97 | name: artifact-${{ matrix.ziti_type }}-amd64-deb 98 | path: | 99 | ./*.deb 100 | 101 | build_arm64_release: 102 | runs-on: [self-hosted, linux, ARM64] 103 | outputs: 104 | version: ${{ steps.version.outputs.version }} 105 | strategy: 106 | matrix: 107 | goos: [linux] 108 | ziti_type: [tunnel, router] 109 | goarch: [arm64] 110 | steps: 111 | - name: Check out code 112 | uses: actions/checkout@v3 113 | 114 | - name: Install EBPF Packages 115 | run: | 116 | sudo apt-get update -qq 117 | sudo apt-get upgrade -yqq 118 | sudo apt-get install -y jq gcc clang libbpfcc-dev libbpf-dev libjson-c-dev 119 | sudo apt-get install -y linux-headers-$(uname -r) 120 | 121 | - name: Compile Object file from Source 122 | run: | 123 | clang -D BPF_MAX_ENTRIES=100000 -g -O2 -Wall -I /usr/include/aarch64-linux-gnu/ -Wextra -target bpf -c -o files/bin/zfw_tc_ingress.o src/zfw_tc_ingress.c 124 | clang -g -O2 -Wall -I /usr/include/aarch64-linux-gnu/ -Wextra -target bpf -c -o files/bin/zfw_xdp_tun_ingress.o src/zfw_xdp_tun_ingress.c 125 | clang -g -O2 -Wall -I /usr/include/aarch64-linux-gnu/-Wextra -target bpf -c -o files/bin/zfw_tc_outbound_track.o src/zfw_tc_outbound_track.c 126 | clang -D BPF_MAX_ENTRIES=100000 -O2 -lbpf -Wall -I /usr/include/aarch64-linux-gnu/ -Wextra -o files/bin/zfw src/zfw.c 127 | gcc -o files/bin/zfw_tunnwrapper src/zfw_tunnel_wrapper.c -l json-c 128 | 129 | - name: Get version 130 | run: echo "version=`files/bin/zfw -V`" >> $GITHUB_OUTPUT 131 | id: version 132 | 133 | - name: Deb directory 134 | run: echo "deb_dir=${{ env.APP_NAME }}-${{ matrix.ziti_type }}_${{ steps.version.outputs.version }}_${{ matrix.goarch }}" >> $GITHUB_OUTPUT 135 | id: deb_dir 136 | 137 | - name: Deb artifact directory setup 138 | run: | 139 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN 140 | touch ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 141 | echo Package: ${{ env.APP_NAME }}-${{ matrix.ziti_type }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 142 | echo Version: ${{ steps.version.outputs.version }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 143 | echo Architecture: ${{ matrix.goarch }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 144 | echo Maintainer: ${{ env.MAINTAINER }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 145 | echo Description: ${{ env.DESC }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 146 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user 147 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc 148 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system 149 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin 150 | cp -p files/bin/zfw_xdp_tun_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 151 | cp -p files/bin/zfw_tc_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 152 | cp -p files/bin/zfw_tc_outbound_track.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 153 | cp -p files/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 154 | cp -p files/scripts/start_ebpf_${{ matrix.ziti_type }}.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 155 | cp -p files/scripts/set_xdp_redirect.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 156 | cp -p files/scripts/user_rules.sh.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/ 157 | cp -p files/json/ebpf_config.json.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc/ 158 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw 159 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/set_xdp_redirect.py 160 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/start_ebpf_${{ matrix.ziti_type }}.py 161 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/user_rules.sh.sample 162 | ln -s /opt/openziti/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin/zfw 163 | 164 | - name: Set Deb Predepends 165 | if: ${{ matrix.ziti_type == 'tunnel' }} 166 | run: | 167 | echo 'Pre-Depends: ziti-edge-tunnel (>= 0.22.5)' >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 168 | cp -p files/services/ziti-fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 169 | cp -p files/services/ziti-wrapper.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 170 | cp -p files/bin/zfw_tunnwrapper ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 171 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw_tunnwrapper 172 | 173 | - name: Standalone FW service and router revert 174 | if: ${{ matrix.ziti_type == 'router' }} 175 | run: | 176 | cp -p files/services/fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 177 | cp -p files/scripts/revert_ebpf_router.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 178 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/revert_ebpf_router.py 179 | 180 | - name: Build Deb package 181 | run: | 182 | dpkg-deb --build -Z gzip --root-owner-group ${{ steps.deb_dir.outputs.deb_dir }} 183 | 184 | - uses: actions/upload-artifact@v3 185 | with: 186 | name: artifact-${{ matrix.ziti_type }}-arm64-deb 187 | path: | 188 | ./*.deb -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: release 3 | 4 | on: 5 | pull_request: 6 | types: [closed] 7 | 8 | env: 9 | APP_NAME: 'zfw' 10 | MAINTAINER: 'Robert Caamano' 11 | DESC: 'An ebpf based statefull fw for openziti edge-routers and tunnelers' 12 | 13 | jobs: 14 | build_amd64_release: 15 | runs-on: ubuntu-22.04 16 | outputs: 17 | version: ${{ steps.version.outputs.version }} 18 | strategy: 19 | matrix: 20 | goos: [linux] 21 | ziti_type: [tunnel, router] 22 | goarch: [amd64] 23 | steps: 24 | - name: Check out code 25 | uses: actions/checkout@v3 26 | 27 | - name: Install EBPF Packages 28 | run: | 29 | sudo apt-get update -qq 30 | sudo apt-get upgrade -yqq 31 | sudo apt-get install -y jq gcc clang libc6-dev-i386 libbpfcc-dev libbpf-dev libjson-c-dev 32 | 33 | - name: Compile Object file from Source 34 | run: | 35 | clang -D BPF_MAX_ENTRIES=100000 -g -O2 -Wall -Wextra -target bpf -c -o files/bin/zfw_tc_ingress.o src/zfw_tc_ingress.c 36 | clang -g -O2 -Wall -Wextra -target bpf -c -o files/bin/zfw_xdp_tun_ingress.o src/zfw_xdp_tun_ingress.c 37 | clang -g -O2 -Wall -Wextra -target bpf -c -o files/bin/zfw_tc_outbound_track.o src/zfw_tc_outbound_track.c 38 | clang -D BPF_MAX_ENTRIES=100000 -O2 -lbpf -Wall -Wextra -o files/bin/zfw src/zfw.c 39 | gcc -o files/bin/zfw_tunnwrapper src/zfw_tunnel_wrapper.c -l json-c 40 | 41 | - name: Get version 42 | run: echo "version=`files/bin/zfw -V`" >> $GITHUB_OUTPUT 43 | id: version 44 | 45 | - name: Deb directory 46 | run: echo "deb_dir=${{ env.APP_NAME }}-${{ matrix.ziti_type }}_${{ steps.version.outputs.version }}_${{ matrix.goarch }}" >> $GITHUB_OUTPUT 47 | id: deb_dir 48 | 49 | - name: Deb Object File 50 | run: | 51 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN 52 | touch ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 53 | echo Package: ${{ env.APP_NAME }}-${{ matrix.ziti_type }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 54 | echo Version: ${{ steps.version.outputs.version }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 55 | echo Architecture: ${{ matrix.goarch }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 56 | echo Maintainer: ${{ env.MAINTAINER }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 57 | echo Description: ${{ env.DESC }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 58 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user 59 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc 60 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system 61 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin 62 | cp -p files/bin/zfw_xdp_tun_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 63 | cp -p files/bin/zfw_tc_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 64 | cp -p files/bin/zfw_tc_outbound_track.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 65 | cp -p files/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 66 | cp -p files/scripts/start_ebpf_${{ matrix.ziti_type }}.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 67 | cp -p files/scripts/set_xdp_redirect.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 68 | cp -p files/scripts/user_rules.sh.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/ 69 | cp -p files/json/ebpf_config.json.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc/ 70 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw 71 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/set_xdp_redirect.py 72 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/start_ebpf_${{ matrix.ziti_type }}.py 73 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/user_rules.sh.sample 74 | ln -s /opt/openziti/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin/zfw 75 | 76 | - name: Set Deb Predepends 77 | if: ${{ matrix.ziti_type == 'tunnel' }} 78 | run: | 79 | echo 'Pre-Depends: ziti-edge-tunnel (>= 0.22.5)' >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 80 | cp -p files/services/ziti-fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 81 | cp -p files/services/ziti-wrapper.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 82 | cp -p files/bin/zfw_tunnwrapper ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 83 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw_tunnwrapper 84 | 85 | - name: Standalone FW service and router revert 86 | if: ${{ matrix.ziti_type == 'router' }} 87 | run: | 88 | cp -p files/services/fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 89 | cp -p files/scripts/revert_ebpf_router.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 90 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/revert_ebpf_router.py 91 | 92 | - name: Build Deb package 93 | run: | 94 | dpkg-deb --build -Z gzip --root-owner-group ${{ steps.deb_dir.outputs.deb_dir }} 95 | 96 | - uses: actions/upload-artifact@v3 97 | with: 98 | name: artifact-${{ matrix.ziti_type }}-amd64-deb 99 | path: | 100 | ./*.deb 101 | 102 | build_arm64_release: 103 | runs-on: [self-hosted, linux, ARM64] 104 | outputs: 105 | version: ${{ steps.version.outputs.version }} 106 | strategy: 107 | matrix: 108 | goos: [linux] 109 | ziti_type: [tunnel, router] 110 | goarch: [arm64] 111 | steps: 112 | - name: Check out code 113 | uses: actions/checkout@v3 114 | 115 | - name: Install EBPF Packages 116 | run: | 117 | sudo apt-get update -qq 118 | sudo apt-get upgrade -yqq 119 | sudo apt-get install -y jq gcc clang libbpfcc-dev libbpf-dev libjson-c-dev 120 | sudo apt-get install -y linux-headers-$(uname -r) 121 | 122 | - name: Compile Object file from Source 123 | run: | 124 | clang -D BPF_MAX_ENTRIES=100000 -g -O2 -Wall -I /usr/include/aarch64-linux-gnu/ -Wextra -target bpf -c -o files/bin/zfw_tc_ingress.o src/zfw_tc_ingress.c 125 | clang -g -O2 -Wall -I /usr/include/aarch64-linux-gnu/ -Wextra -target bpf -c -o files/bin/zfw_xdp_tun_ingress.o src/zfw_xdp_tun_ingress.c 126 | clang -g -O2 -Wall -I /usr/include/aarch64-linux-gnu/-Wextra -target bpf -c -o files/bin/zfw_tc_outbound_track.o src/zfw_tc_outbound_track.c 127 | clang -D BPF_MAX_ENTRIES=100000 -O2 -lbpf -Wall -I /usr/include/aarch64-linux-gnu/ -Wextra -o files/bin/zfw src/zfw.c 128 | gcc -o files/bin/zfw_tunnwrapper src/zfw_tunnel_wrapper.c -l json-c 129 | 130 | - name: Get version 131 | run: echo "version=`files/bin/zfw -V`" >> $GITHUB_OUTPUT 132 | id: version 133 | 134 | - name: Deb directory 135 | run: echo "deb_dir=${{ env.APP_NAME }}-${{ matrix.ziti_type }}_${{ steps.version.outputs.version }}_${{ matrix.goarch }}" >> $GITHUB_OUTPUT 136 | id: deb_dir 137 | 138 | - name: Deb artifact directory setup 139 | run: | 140 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN 141 | touch ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 142 | echo Package: ${{ env.APP_NAME }}-${{ matrix.ziti_type }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 143 | echo Version: ${{ steps.version.outputs.version }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 144 | echo Architecture: ${{ matrix.goarch }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 145 | echo Maintainer: ${{ env.MAINTAINER }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 146 | echo Description: ${{ env.DESC }} >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 147 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user 148 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc 149 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system 150 | mkdir -p ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin 151 | cp -p files/bin/zfw_xdp_tun_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 152 | cp -p files/bin/zfw_tc_ingress.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 153 | cp -p files/bin/zfw_tc_outbound_track.o ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 154 | cp -p files/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 155 | cp -p files/scripts/start_ebpf_${{ matrix.ziti_type }}.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 156 | cp -p files/scripts/set_xdp_redirect.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 157 | cp -p files/scripts/user_rules.sh.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/ 158 | cp -p files/json/ebpf_config.json.sample ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/etc/ 159 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw 160 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/set_xdp_redirect.py 161 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/start_ebpf_${{ matrix.ziti_type }}.py 162 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/user/user_rules.sh.sample 163 | ln -s /opt/openziti/bin/zfw ${{ steps.deb_dir.outputs.deb_dir }}/usr/sbin/zfw 164 | 165 | - name: Set Deb Predepends 166 | if: ${{ matrix.ziti_type == 'tunnel' }} 167 | run: | 168 | echo 'Pre-Depends: ziti-edge-tunnel (>= 0.22.5)' >> ${{ steps.deb_dir.outputs.deb_dir }}/DEBIAN/control 169 | cp -p files/services/ziti-fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 170 | cp -p files/services/ziti-wrapper.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 171 | cp -p files/bin/zfw_tunnwrapper ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 172 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/zfw_tunnwrapper 173 | 174 | - name: Standalone FW service and router revert 175 | if: ${{ matrix.ziti_type == 'router' }} 176 | run: | 177 | cp -p files/services/fw-init.service ${{ steps.deb_dir.outputs.deb_dir }}/etc/systemd/system/ 178 | cp -p files/scripts/revert_ebpf_router.py ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/ 179 | chmod 744 ${{ steps.deb_dir.outputs.deb_dir }}/opt/openziti/bin/revert_ebpf_router.py 180 | 181 | - name: Build Deb package 182 | run: | 183 | dpkg-deb --build -Z gzip --root-owner-group ${{ steps.deb_dir.outputs.deb_dir }} 184 | 185 | - uses: actions/upload-artifact@v3 186 | with: 187 | name: artifact-${{ matrix.ziti_type }}-arm64-deb 188 | path: | 189 | ./*.deb 190 | 191 | deploy_release: 192 | runs-on: ubuntu-22.04 193 | needs: 194 | - build_amd64_release 195 | - build_arm64_release 196 | strategy: 197 | matrix: 198 | goos: [linux] 199 | steps: 200 | - name: Create release 201 | uses: ncipollo/release-action@v1.12.0 202 | id: release 203 | with: 204 | draft: false 205 | prerelease: false 206 | tag: v${{ needs.build_amd64_release.outputs.version }} 207 | env: 208 | GITHUB_TOKEN: ${{ github.token }} 209 | 210 | deploy_packages: 211 | runs-on: ubuntu-22.04 212 | needs: 213 | - build_amd64_release 214 | - build_arm64_release 215 | - deploy_release 216 | strategy: 217 | matrix: 218 | goos: [linux] 219 | ziti_type: [tunnel, router] 220 | goarch: [amd64, arm64] 221 | steps: 222 | - uses: actions/download-artifact@v3 223 | with: 224 | name: artifact-${{ matrix.ziti_type }}-${{ matrix.goarch }}-deb 225 | - name: Upload built deb artifacts 226 | uses: svenstaro/upload-release-action@2.5.0 227 | env: 228 | GITHUB_TOKEN: ${{ github.token }} 229 | with: 230 | file: ./${{ env.APP_NAME }}-${{ matrix.ziti_type }}_${{ needs.build_amd64_release.outputs.version }}_${{ matrix.goarch }}.deb 231 | release_name: ${{ needs.build_amd64_release.outputs.version }} 232 | tag: v${{ needs.build_amd64_release.outputs.version }} 233 | -------------------------------------------------------------------------------- /BUILD.md: -------------------------------------------------------------------------------- 1 | ## Build from source 2 | --- 3 | - OS/Platform: Ubuntu 22.04 / amd64 4 | 1. install libraries 5 | 6 | **Ubuntu 22.04 server / amd64** (kernel 5.15 or higher) 7 | 8 | ```bash 9 | sudo apt update 10 | sudo apt upgrade 11 | sudo reboot 12 | sudo apt install -y gcc clang libc6-dev-i386 libbpfcc-dev libbpf-dev libjson-c-dev make 13 | ``` 14 | 15 | 1. Compile: 16 | 17 | ```bash 18 | mkdir ~/repos 19 | cd repos 20 | git clone https://github.com/r-caamano/zfw.git 21 | cd zfw/src 22 | make all 23 | sudo make install ARGS= 24 | ``` 25 | 26 | - OS/Platform: Ubuntu 22.04 / arm64 27 | 1. install libraries 28 | 29 | **Ubuntu 22.04 server / arm** (kernel 5.15 or higher) 30 | 31 | ```bash 32 | sudo apt update 33 | sudo apt upgrade 34 | sudo reboot 35 | sudo apt-get install -y gcc clang libbpfcc-dev libbpf-dev libjson-c-dev make 36 | ``` 37 | 38 | 1. Compile: 39 | 40 | ```bash 41 | mkdir ~/repos 42 | cd repos 43 | git clone https://github.com/r-caamano/zfw.git 44 | cd zfw/src 45 | make all 46 | sudo make install ARGS= 47 | ``` 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 4 | 5 | --- 6 | # [0.5.11] - 2024-02-09 7 | 8 | ### 9 | 10 | - Added ip protocol to matched map key and fixed typo in comment 11 | 12 | # [0.5.10] - 2024-02-09 13 | 14 | ### 15 | 16 | - Fixed a possible issue where in high performance compute environments there could be more than one packet being processed by the TC filters there could be a 17 | mismatched rule where if a new packet matches a rule it could cause other packets in flight to be processed by the same rule. 18 | 19 | # [0.5.9] - 2024-02-09 20 | 21 | ### 22 | 23 | - Fixed an issue where if tc filter is applied to the loopback interface traffic is dropped if it does not match 24 | a filter. The correct action is to pass all traffic to the loopback unless there is a rule explicitly redirecting 25 | the traffic to either a tproxy port or ziti(tun) interface. 26 | 27 | 28 | # [0.5.7] - 2024-01-21 29 | 30 | ### 31 | 32 | -- Modified the "zfw -F" system call in start_ebpf_py.py to "zfw -F -r" to ensure that any ziti created loopback routes are also 33 | cleared when restarting ziti-router. 34 | -- Removed deprecated sed entries in start_ebpf_router.py that are no longer required 35 | -- Fixed inaccurate string parse check in start_ebpf_router.py set_local_rules() 36 | 37 | # [0.5.6] - 2024-01-19 38 | 39 | ### 40 | 41 | -- Fixed issue in outbound tracking for passthrough tcp connections where packets with rst set from 42 | server were only accepted if connection was already in established state. Changed to allow rst during 43 | tcp handshake which occurs when server refuses a connection. 44 | 45 | # [0.5.5] - 2024-01-05 46 | 47 | ### 48 | 49 | -- Changed ICMP Unreachable logging to default level 50 | -- Added -L, --write-log option to -M, --monitor output to a specified log file 51 | -- Removed redundant check on ifname in process_events 52 | -- Refactored ring_buffer to report only errors and ICMP Unreachables by default and 53 | require verbose for all valid traffic monitoring. 54 | -- Added new error code ICMP_INNER_IP_HEADER_TOO_BIG 55 | -- Code consolidation in zfw_tc_ingress.c 56 | 57 | # [0.5.4] - 2023-12-24 58 | 59 | ### 60 | 61 | -- Added support for stateful stateful icmp unreachable inbound support in order to support 62 | pmtud and unreachable metric collection. 63 | -- Fixed added ring_buffer__free() to INThandler in zfw.c to properly de-allocate memory 64 | allocated by ring_buffer__new in main() if -M argument was supplied and SIGINT or SIGTERM 65 | is received. 66 | 67 | # [0.5.3] - 2023-12-19 68 | 69 | ### 70 | 71 | - Fixed issue causing valgrind memory error due to non-initialized struct in add_if_index() in zfw.c. 72 | 73 | # [0.5.2] - 2023-11-27 74 | 75 | ### 76 | 77 | - Changed ifindex_ip_map to a hashmap and added code to prune stale keys due to 78 | index changes for dynamic interfaces. 79 | - cleanup removed redefinitions of global count_map_path in multiple functions 80 | 81 | # [0.5.1] - 2023-08-22 82 | 83 | ### 84 | 85 | - Fixed outbound tracking broken due to missed addition of eapol to diag_map values. 86 | 87 | # [0.5.0] - 2023-08-18 88 | 89 | ### 90 | 91 | - Added make to pre-compile binary package installs listed in BUILD.md 92 | - Changed bind service lookup from dumpfile to event channel. 0.5.0 will only work with 93 | ZET 0.22.4 or above 94 | - Added passthrough support for eapol (802.1X) frames 95 | 96 | # [0.4.6] - 2023-08-13 97 | 98 | ### 99 | 100 | - Fixed potential race condition if upstream DHCP server is not functioning when FW inits ebpf. 101 | Changed address family match to ethernet when applying TC Filters/Diag settings. 102 | 103 | # [0.4.5] - 2023-08-03 104 | 105 | ### 106 | 107 | - Fixed ring buffer events for tunnel interface not sending correct source/destination ports. Also changed default 108 | xdp RB events to only send if verbose mode is enabled for the tun/ziti interface. 109 | 110 | # [0.4.4] - 2023-08-01 111 | 112 | ### 113 | 114 | - Added Makefile and install.sh in src folder to allow 115 | build via make. 116 | 117 | - Fixed issue where start_ebpf_router.py was not 118 | properly updating the ziti-router.service file. 119 | 120 | # [0.4.3] - 2023-07-25 121 | 122 | ### 123 | 124 | -- Refactored monitoring to use ring buffer and removed all bpf_printk() helper calls 125 | -- Added ring buffer monitoring to zfw via -M, --monitor flags 126 | -- General Code cleanup in zfw.c 127 | 128 | # [0.4.2] - 2023-07-15 129 | 130 | ### 131 | 132 | - Added support for secondary ip addresses with the auto ssh inbound support function on the incoming interface. 133 | Number of total addresses if defined in by MACRO MAX_ADDRESSES. In package deployments this will be set to 10. 134 | 135 | # [0.4.1] - 2023-06-30 136 | 137 | ### 138 | 139 | - Added support for inbound vrrp on a per port basis. 140 | 141 | # [0.4.0] - 2023-06-29 142 | 143 | ### 144 | 145 | - Added support for upcoming ziti-edge-tunnel interface name change from tunX to zitiX. 146 | 147 | # [0.3.10] - 2023-06-28 148 | 149 | ### 150 | 151 | - Added checks to catch exceptions in config.yml 152 | 153 | # [0.3.9] - 2023-06-27 154 | 155 | ### 156 | 157 | - Refactored start_ebpf_router.py and revert_ebpf_router.py to read / update config.yml 158 | using pyyaml python module. 159 | 160 | # [0.3.8] - 2023-06-26 161 | 162 | ### 163 | 164 | - Fixed missing terminating bold in README.md. 165 | - Refactored start_ebpf_router.py to suppress some output messages. 166 | 167 | # [0.3.7] - 2023-06-16 168 | 169 | ### 170 | 171 | - Fixed CHANGELOG Duplicate 0.3.5 entry and set to 0.3.6 172 | - Added check to make sure each ebpf program loads into tc filter before proceeding and if failure occurs 173 | exit(1) and print the filter# where the failure ocurred. 174 | - Removed unknown import shutil from start_ebpf_router.py 175 | 176 | 177 | # [0.3.6] - 2023-06-15 178 | 179 | ### 180 | 181 | - Refactored auto-load of ziti-router config.yml port rules to dynamically enter rules when ziti-router.service is restarted or 182 | the start_ebpf_router.py is executed. Also refactored deb packages to install all scripts, zfw and zfw_tunnwrapper as only 183 | root executable. 184 | 185 | # [0.3.5] - 2023-06-15 186 | 187 | ### 188 | 189 | - Changed zfw-router auto ziti-router config.yml port/rule insertion to limit destination IP to config.yml lanIf 190 | 191 | # [0.3.4] - 2023-06-14 192 | 193 | ### 194 | 195 | - Fixed bug in start_ebpf_router.py where lan IP mask was set to /24 instead of /32 196 | 197 | # [0.3.3] - 2023-06-14 198 | 199 | ### 200 | 201 | - Refactored to start_ebpf_router.py to add ziti-router listen ports as passthrough zfw rules on in /user/openziti/bin/user/user_rules.sh for both CloudZiti and 202 | OpenZiti deployed ziti-routers. 203 | - Refactored start_ebpf_router.py and revert_ebpf_router.py scripts ziti-router.service auto-edits to key on only the router service for entry 204 | for both start and revert respectfully. 205 | 206 | # [0.3.2] - 2023-06-13 207 | 208 | ### 209 | 210 | - initial integration of ziti-router. Changed package name for ziti-tunnel to zfw-tunnel. Added new package zfw-router. Previous installs with 211 | zfw package should remove package first then install new package i.e. sudo dpkg -P zfw && sudo dpkg -i zfw-tunnel__.deb 212 | 213 | # [0.2.5] - 2023-06-05 214 | 215 | ### 216 | 217 | - Refactored zfw.c to include vs for consistency. 218 | - Refactored zfw_tc_ingress.c and zfw_tc_ingress.c added final seq/ack tracking to more accurately determine 219 | tcp session termination. 220 | - Updated README with link to build openziti network and install ziti-edge-tunnel 221 | 222 | # [0.2.4] - 2023-06-02 223 | 224 | ### 225 | 226 | - Fixed fd leak in zfw.c get_index() 227 | - Interface function refactor / clean 228 | 229 | # [0.2.2] - 2023-05-31 230 | 231 | ### 232 | 233 | - Fixed missing verbose check for bpf_printk statement in action/5. 234 | - Fixed logic in action/5 for tproxy based forwarding decision (Needed for ziti-router integration). 235 | - Minor README formatting change. 236 | 237 | # [0.2.1] - 2023-05-29 238 | 239 | ### 240 | 241 | - Changed in operation of transparency route unbinding. In order to allow internal tunneler connections 242 | over ziti the default operation has been set to not delete any tunX link routes. This will disable the ability to support transparency on some architectures. There is now an environmental variable TRANSPARENT_MODE='true' that can be set in the /opt/openziti/etc/ziti-edge-tunnel.env file to enable deletion of tun routes if bi-directional transparency is required at the expense of disabling internal tunneler interception. 243 | 244 | # [0.2.0] - 2023-05-29 245 | 246 | ### 247 | 248 | - Changed ebpf program chaining method from tail calls to tc filter chaining. This 249 | change should allow for installation on newer linux releases that do not support 250 | legacy ELF maps. 251 | - Fixed issue where if the loopback was set to disable ssh via zfw -x, --disable-ssh 252 | the diag setting incorrectly set it to disabled and would not allow the disable to 253 | be removed without clearing the ebpf diag map manually. 254 | 255 | # [0.1.19] - 2023-05-25 256 | 257 | ### 258 | 259 | - Removed unused/unsupported 'id' field from all BTF Maps 260 | 261 | # [0.1.18] - 2023-05-25 262 | 263 | ### 264 | 265 | - Switched deb compression algorithm to gzip 266 | 267 | # [0.1.17] - 2023-05-25 268 | 269 | ### 270 | 271 | - Fixed BUILD.md pointing to deprecated repo. 272 | 273 | # [0.1.16] - 2023-05-23 274 | 275 | ### 276 | 277 | - Increased event buffer size / max line size to support single services with large #s 278 | of prefixes. 279 | 280 | # [0.1.15] - 2023-05-23 281 | 282 | ### 283 | 284 | - Added local route cleanup on SIGTERM/SIGINT. 285 | 286 | # [0.1.14] - 2023-05-23 287 | 288 | ### 289 | 290 | - Major operational change. Fixed issue where ziti-edge-tunnel would not bind to egress allows source 291 | ip unless there was an exact /32 match. Now binding is possible with a subnet level match. This is 292 | a significant improvement as now allowed sources do not have to be host level entries. In order to 293 | achieve this the link scoped route to tuX created by ZET for interception is deleted by the wrapper and a 294 | local ip route is added to lo in its place. This is made possible by the tc-ebpf-redirect which negates 295 | the need for the link scoped route. **After update a system reboot should be performed** 296 | 297 | - General code cleanup 298 | 299 | # [0.1.13] - 2023-05-21 300 | 301 | ### 302 | 303 | - Fixed incorrect spelling of privileges in ebpf not enabled output messages. 304 | 305 | # [0.1.12] - 2023-05-21 306 | 307 | ### 308 | 309 | - Changed interface ebpf settings assignment which may require alteration of existing config if setup for exteral 310 | outbound tracking. 311 | 312 | Added keys to /opt/openziti/etc/ebpf_config.json 313 | - PerInterfaceRules - sets state of per interface rules awareness. 314 | - InternalInterfaces default: false 315 | - ExternalInterfaces default: true 316 | - OutboundPassThroughTrack 317 | - InternalInterfaces default: false 318 | - ExternalInterfaces default: true 319 | 320 | - Added empty ExternalInterfaces key to ebpf_config.json.sample and new keys described above with default values in 321 | the InternalInterfaces object. These can be excluded since they are default and provided only for example purposes. 322 | - /opt/openziti/start_ebpf.py updated to parse new keys and implement new interface deployment logic. 323 | 324 | - Edited debug output in ingress/egress tc to better reflect data captured 325 | 326 | # [0.1.11] - 2023-05-17 327 | 328 | ### 329 | 330 | - Fixed Usage: output inconsistencies 331 | - Added hyperlink to https://docs.openziti.io/ 332 | - Added debug output in both ingress and egress for traffic that matches 333 | host initiated connections 334 | - standardized on debug output messaging and corrected spelling errors. 335 | 336 | # [0.1.10] - 2023-05-17 337 | 338 | ### 339 | 340 | - Reverted ci/release.yml to include 'Pre-Depends: linux-image-generic (>= 5.15.0)' 341 | - Fixed README Missing comma in json sample 342 | 343 | 344 | # [0.1.9] - 2023-05-17 345 | 346 | - Changed ci/release.yml to include 'Pre-Depends: linux-image-generic (>= 5.15.0)' 347 | - Fixed ci/release.yml ${{ env.MAINTAINER }} missing prepended $ 348 | - Added additional src/dest debug info in outbound tracking for udp 349 | - Fixed inconsistency in usage: 350 | 351 | ### 352 | 353 | - Fixed --help output changed "ssh echo" to ssh 354 | 355 | # [0.1.8] - 2023-05-17 356 | 357 | ### 358 | 359 | - Added input validation to all interface related commands. If non existent name is given "Interface not 360 | found: will be output. 361 | - Fixed output of zfw -L -i 362 | - Added README.md section for containers, fixed some inconsistencies 363 | 364 | # [0.1.7] - 2023-05-17 365 | 366 | ### 367 | 368 | - Fixed input validation to reject any tc filter commands with out -z, --direction specified 369 | - Added enhanced output for outbound tracking 370 | - Modified tcp state map to have separate fin state for client and server to more accurately 371 | identify tcp session close. 372 | - Edits to readme removed ./ and repeated sudo 373 | 374 | # [0.1.6] - 2023-05-17 375 | 376 | ### 377 | 378 | -Fixed start_ebpf.py syntax error printf() and should have been print() and removed sys.exit(1) on zfw -Q fail. 379 | -Fixed README.md inconsistencies/errors. 380 | -Fixed zfw -Q not displaying sudo permissions requirement when operated as a non privileged user. 381 | -Modified Maximums entries for multiple maps, this included a changed for MAX_BPF_ENTRIES which 382 | is settable at compile time and reflected in release.yml/ci.yml workload. 383 | 384 | # [0.1.5] - 2023-05-16 385 | 386 | ### 387 | 388 | - Fixed some README.md inconsistencies and reduced some instructions to list only the most optimal methods. 389 | - Changed Depends: ziti-edge-tunnel to Pre-Depends: ziti-edge-tunnel '(>= 0.21.0)' in release.yml key to .deb 390 | control to prevent installation if ziti-edge-tunnel is not already installed. 391 | 392 | # [0.1.4] - 2023-05-16 393 | 394 | ### 395 | 396 | - Refactored release.yml to replace deprecated actions. 397 | 398 | # [0.1.3] - 2023-05-15 399 | 400 | ### 401 | 402 | - Added ability to override automated settings in start_ebpf.sh by moving user_rules.sh read to last item in script 403 | 404 | ## [0.1.2] - 2023-05-15 405 | 406 | ### 407 | 408 | - Refactored release.yml deploy_packages_(arch) jobs to a single deploy_packages job with iteration through ${{ matrix.goarch }} 409 | 410 | ## [0.1.1] - 2023-05-15 411 | 412 | ### 413 | 414 | - Added initial code. 415 | - Added README.md 416 | - Added BUILD.md 417 | - Modified json object in files/json/ebpf_config.json and modified files/scripts/start_ebpf.py to parse it for new key "ExternalInterfaces" which 418 | gives the ability to assign an outbound tracking object and set per interface rules on a wan interface as described in README.md 419 | - Fixed memory leak caused b y not calling json_object_put() on the root json objects created by calls to json _token_parse(). 420 | 421 | ## [0.1.0] - 2023-05-12 422 | 423 | ### 424 | 425 | - Added initial code. 426 | 427 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ARCHIVED 2 | ## All further development moved to https://github.com/netfoundry/zfw 3 | 4 | 5 | # Introduction 6 | 7 | --- 8 | This firewall application utilizes both tc-ebpf and xdp to provide stateful firewalling 9 | for an [OpenZiti](https://docs.openziti.io/) ziti-edge-tunnel installation and is meant as a replacement for packet 10 | filtering. It can be used in conjunction with ufw's masquerade feature on a Wan facing interface if 11 | the zfw_outbound_track.o is activated in the egress direction. It can also be used in conjunction with OpenZiti 12 | edge-routers. 13 | 14 | 15 | ## Build 16 | 17 | [To build / install zfw from source. Click here!](./BUILD.md) 18 | 19 | ## Ziti-Edge-Tunnel Deployment 20 | 21 | The program is designed to be deployed as systemd services if deployed via .deb package with 22 | an existing ziti-edge-tunnel(v22.5 +) installation on Ubuntu 22.04(amd64/arm64)service installation. If you don't currently 23 | have ziti-edge-tunnel installed and an operational OpenZiti network built, follow these 24 | [instructions](https://docs.openziti.io/docs/guides/Local_Gateway/EdgeTunnel). 25 | 26 | 27 | - Install 28 | ubuntu 22.04 only (binary deb package) 29 | ``` 30 | sudo dpkg -i zfw-tunnel__.deb 31 | ``` 32 | Install from source ubuntu 22.04+ / Debian 12 33 | [build / install zfw from source](./BUILD.md) 34 | 35 | ## Ziti-Router Deployment 36 | 37 | The program is designed to integrated into an existing Openziti ziti-router installation if ziti router has been deployed via ziti_auto_enroll 38 | [instructions](https://docs.openziti.io/docs/guides/Local_Gateway/EdgeRouter). 39 | 40 | - Install 41 | ubuntu 22.04 only (binary deb package) 42 | ``` 43 | sudo dpkg -i zfw-router__.deb 44 | ``` 45 | Install from source ubuntu 22.04+ / Debian 12 46 | [build / install zfw from source](./BUILD.md) 47 | 48 | **The following instructions pertain to both zfw-tunnel and zfw-router. Platform specific functions will be noted explicitly** 49 | 50 | Packages files will be installed in the following directories. 51 | ``` 52 | /etc/systemd/system 53 | /usr/sbin 54 | /opt/openziti/etc : 55 | /opt/openziti/bin : 56 | /opt/openziti/bin/user/: 57 | ``` 58 | Configure: 59 | - Edit interfaces (zfw-tunnel) note: ziti-router will automatically add lanIf: from config.yml 60 | ``` 61 | sudo cp /opt/openziti/etc/ebpf_config.json.sample /opt/openziti/etc/ebpf_config.json 62 | sudo vi /opt/openziti/etc/ebpf_config.json 63 | ``` 64 | - Adding interfaces 65 | Replace ens33 in line with:{"InternalInterfaces":[{"Name":"ens33" ,"OutboundPassThroughTrack": false, "PerInterfaceRules": false}], "ExternalInterfaces":[]} 66 | Replace with interface that you want to enable for ingress firewalling / openziti interception and 67 | optionally ExternalInterfaces if running containers or other subtending devices (Described in more detail 68 | later in this README.md). 69 | ``` 70 | i.e. ens33 71 | {"InternalInterfaces":[{"Name":"ens33"}], "ExternalInterfaces":[]} 72 | Note if you want to add more than one add to list 73 | {"InternalInterfaces":[{"Name":"ens33"}, {"Name":"ens37"}], "ExternalInterfaces":[]} 74 | ``` 75 | 76 | - Add user configured rules: 77 | ``` 78 | sudo cp /opt/openziti/bin/user/user_rules.sh.sample /opt/openziti/bin/user/user_rules.sh 79 | sudo vi /opt/openziti/bin/user/user_rules.sh 80 | ``` 81 | 82 | - Enable services:(zfw-tunnel) 83 | ``` 84 | sudo systemctl enable ziti-fw-init.service 85 | sudo systemctl enable ziti-wrapper.service 86 | sudo systemctl restart ziti-edge-tunnel.service 87 | ``` 88 | 89 | - Enable services:(zfw-router) 90 | ``` 91 | sudo /opt/openziti/bin/start_ebpf_router.py 92 | ``` 93 | 94 | The Service/Scripts will automatically configure ufw (if enabled) to hand off to ebpf on configured interface(s). Exception is icmp 95 | which must be manually enabled if it's been disabled in ufw. 96 | 97 | /etc/ufw/before.rules: 98 | ``` 99 | -A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT 100 | ``` 101 | 102 | Also to allow icmp echos to reach the ip of attached interface you would need to 103 | set icmp to enabled in the /opt/openziti/bin/user/user_rules.sh file i.e. 104 | ``` 105 | sudo zfw -e ens33 106 | sudo systemctl restart ziti-wrapper.service 107 | ``` 108 | 109 | 110 | Verify running: (zfw-tunnel) 111 | ``` 112 | sudo zfw -L 113 | ``` 114 | If running: 115 | ``` 116 | Assuming you are using the default address range for ziti-edge-tunnel should see output like: 117 | 118 | target proto origin destination mapping: interface list 119 | -------- ----- ----------------- ------------------ ------------------------------------------------------- ----------------- 120 | TUNMODE tcp 0.0.0.0/0 100.64.0.0/10 dpts=1:65535 TUNMODE redirect:tun0 [] 121 | TUNMODE udp 0.0.0.0/0 100.64.0.0/10 dpts=1:65535 TUNMODE redirect:tun0 [] 122 | ``` 123 | 124 | Verify running: (zfw-router) 125 | ``` 126 | sudo zfw -L 127 | ``` 128 | If running: 129 | ``` 130 | Assuming no services configured yet: 131 | 132 | target proto origin destination mapping: interface list 133 | -------- ----- ----------------- ------------------ ------------------------------------------------------- ----------------- 134 | Rule Count: 0 135 | prefix_tuple_count: 0 / 100000 136 | 137 | ``` 138 | 139 | If not running: 140 | ``` 141 | Not enough privileges or ebpf not enabled! 142 | Run as "sudo" with ingress tc filter [filter -X, --set-tc-filter] set on at least one interface 143 | 144 | ``` 145 | Verify running on the configured interface i.e. 146 | ``` 147 | sudo tc filter show dev ens33 ingress 148 | ``` 149 | If running on interface: 150 | ``` 151 | filter protocol all pref 1 bpf chain 0 152 | filter protocol all pref 1 bpf chain 0 handle 0x1 zfw_tc_ingress.o:[action] direct-action not_in_hw id 26 tag e8986d00fc5c5f5a 153 | filter protocol all pref 2 bpf chain 0 154 | filter protocol all pref 2 bpf chain 0 handle 0x1 zfw_tc_ingress.o:[action/1] direct-action not_in_hw id 31 tag ae5f218d80f4f200 155 | filter protocol all pref 3 bpf chain 0 156 | filter protocol all pref 3 bpf chain 0 handle 0x1 zfw_tc_ingress.o:[action/2] direct-action not_in_hw id 36 tag 751abd4726b3131a 157 | filter protocol all pref 4 bpf chain 0 158 | filter protocol all pref 4 bpf chain 0 handle 0x1 zfw_tc_ingress.o:[action/3] direct-action not_in_hw id 41 tag 63aad9fa64a9e4d2 159 | filter protocol all pref 5 bpf chain 0 160 | filter protocol all pref 5 bpf chain 0 handle 0x1 zfw_tc_ingress.o:[action/4] direct-action not_in_hw id 46 tag 6c63760ceaa339b7 161 | filter protocol all pref 6 bpf chain 0 162 | filter protocol all pref 6 bpf chain 0 handle 0x1 zfw_tc_ingress.o:[action/5] direct-action not_in_hw id 51 tag b7573c4cb901a5da 163 | ``` 164 | 165 | Services configured via the openziti controller for ingress on the running ziti-edge-tunnel/ziti-router identity will auto populate into 166 | the firewall's inbound rule list. 167 | 168 | Also note for zfw-tunnel xdp is enabled on the tunX interface that ziti-edge tunnel is attached to support functions like bi-directional 169 | ip transparency which would otherwise not be possible without this firewall/wrapper. 170 | 171 | You can verify this as follows: 172 | ``` 173 | sudo ip link show tun0 174 | ``` 175 | expected output: 176 | ``` 177 | 9: tun0: mtu 1500 xdpgeneric qdisc fq_codel state UNKNOWN mode DEFAULT group default qlen 500 178 | link/none 179 | prog/xdp id 249 tag 06c4719358c6de42 jited 180 | ``` 181 | 182 | ### Outbound External passthrough traffic 183 | 184 | The firewall can support subtending devices for two interface scenarios i.e. 185 | external and trusted. 186 | 187 | external inet <----> (ens33)[ebpf-router](ens37) <----> trusted client(s) 188 | 189 | with zfw_tc_ingress.o applied ingress on ens33 and zfw_tc_oubound_track.o applied egress on ens33 the router will 190 | statefully track outbound udp and tcp connections on ens33 and allow the associated inbound traffic. While 191 | running in this mode it does not make sense to add ziti tproxy rules and is meant for running as a traditional fw. 192 | As be for you can also create passthrough FW rules (set -t --tproxy-port to 0) which would also make sense in the mode for 193 | specific internet-initiated traffic you might want to allow in. 194 | 195 | TCP: 196 | If the tcp connections close gracefully then the entries will remove upon connection closure. 197 | if not, then there is a 60-minute timeout that will remove the in active state if no traffic seen 198 | in either direction. 199 | 200 | UDP: 201 | State will remain active as long as packets tuples matching SRCIP/SPORT/DSTIP/DPORT are seen in 202 | either direction within 30 seconds. If no packets seen in either direction the state will expire. 203 | If an external packet enters the interface after expiring the entry will be deleted. if an egress 204 | packet fined a matching expired state it will return the state to active. 205 | 206 | In order to support this per interface rule awareness was added which allows each port range within a prefix 207 | to match a list of connected interfaces. On a per interface basis you can decide to honor that list or not via 208 | a per-prefix-rules setting in the following manner via the zfw utility 209 | 210 | 211 | #### Two Interface config with ens33 facing internet and ens37 facing local lan 212 | 213 | ``` 214 | sudo vi /opt/openziti/etc/ebpf_config.json 215 | ``` 216 | ``` 217 | {"InternalInterfaces":[{"Name":"ens37","OutboundPassThroughTrack": false, PerInterfaceRules: false}], 218 | "ExternalInterfaces":[{"Name":"ens33", OutboundPassThroughTrack: true, PerInterfaceRules: true}]} 219 | ``` 220 | The above JSON sets up ens33 to be an internal interface (No outbound tracking) and ens33 as an external interface 221 | with outbound tracking (Default for External Interface). It also automatically adds runs the sudo zfw -P ens33 so ens33 222 | (default for ExternalInterfaces) which requires -N to add inbound rules to it and will ignore rules where it is not in the interface list. 223 | Keys "OutboundPassThroughTrack" and "PerInterfaceRules" are shown with their default values, you only need to add them if you 224 | want change the default operation for the interface type. 225 | 226 | #### Single Interface config with ens33 facing lan local lan 227 | ``` 228 | sudo vi /opt/openziti/etc/ebpf_config.json 229 | ``` 230 | ``` 231 | {"InternalInterfaces":[{"Name":"ens37","OutboundPassthroughTrack": true, PerInterfaceRules: false}], 232 | "ExternalInterfaces":[]} 233 | ``` 234 | **Double check that your json formatting is correct since mistakes could render the firewall inoperable.** 235 | 236 | After editing disable zfw and restart ziti-edge-wrapper service 237 | 238 | (zfw-tunnel) 239 | ``` 240 | sudo zfw -Q 241 | sudo /opt/openziti/bin/start_ebpf_tunnel.py 242 | sudo systemctl restart ziti-edge-wrapper.service 243 | 244 | ``` 245 | 246 | (zfw-router) 247 | ``` 248 | sudo zfw -Q 249 | sudo systemctl restart ziti-router.service 250 | 251 | ``` 252 | 253 | ### Ziti Edge Tunnel Bidirectional Transparency (zfw-tunnel only) 254 | 255 | In order to allow internal tunneler connections over ziti the default operation has been set to not delete any tunX link routes. This will disable the ability to support transparency. There is an environmental variable ```TRANSPARENT_MODE='true'``` that can be set in the ```/opt/openziti/etc/ziti-edge-tunnel.env``` file to enable deletion of tunX routes if bi-directional transparency is required at the expense of disabling internal tunneler interception. 256 | 257 | ### Supporting Internal Containers / VMs 258 | 259 | Traffic from containers like docker appears just like passthrough traffic to ZFW so you configure it the same as described above for 260 | normal external pass-through traffic. 261 | 262 | ### Upgrading zfw-tunnel 263 | ``` 264 | sudo systemctl stop ziti-wrapper.service 265 | sudo dpkg -i _.deb 266 | ``` 267 | After updating reboot the system 268 | ``` 269 | sudo reboot 270 | ``` 271 | 272 | ### Upgrading zfw-router 273 | ``` 274 | sudo dpkg -i _.deb 275 | ``` 276 | After updating reboot the system 277 | ``` 278 | sudo reboot 279 | ``` 280 | 281 | ## Ebpf Map User Space Management 282 | --- 283 | ### User space manual configuration 284 | ziti-edge-tunnel/ziti-router will automatically populate rules for configured ziti services so the following is if 285 | you want to configure additional rules outside of the automated ones. zfw-tunnel will also auto-populate /opt/openziti/bin/user/user_rules.sh 286 | with listening ports in the config.yml. 287 | 288 | **Note the ```zfw-router__.deb``` will install an un-enabled service ```fw-init.service```. If you install the zfw-router package without an OpenZiti ziti-router installation and enable this service it will start the ebpf fw after reboot and load the commands from /opt/openziti/bin/user/user_rules.sh. If you later decide to install ziti-router this service should be disabled and you should run ```/opt/openziti/bin/start_ebpf_router.py``` you will also need to manually copy the /opt/openziti/etc/ebpf_config.json.sample to ebpf_config.json and edit interface name** 289 | 290 | **(All commands listed in this section need to be put in /opt/openziti/bin/user/user_rules.shin order to survive reboot)** 291 | 292 | ### ssh default operation 293 | By default ssh is enabled to pass through to the ip address of the attached interface from any source. 294 | If secondary addresses exist on the interface this will only work for the first 10. After that you would need 295 | to add manual entries via ```zfw -I```. 296 | 297 | The following command will disable default ssh action to pass to the IP addresses of the local interface and will 298 | fall through to rule check instead where a more specific rule could be applied. This is a per 299 | interface setting and can be set for all interfaces except loopback. This would need to be put in 300 | /opt/openziti/bin/user/user_rules.sh to survive reboot. 301 | 302 | - Disable 303 | ``` 304 | sudo zfw -x 305 | ``` 306 | 307 | - Enable 308 | ``` 309 | sudo zfw -x -d 310 | ``` 311 | 312 | ### vrrp passthrough 313 | - Enable 314 | ``` 315 | sudo zfw --vrrp-enable 316 | ``` 317 | 318 | - Disable 319 | ``` 320 | sudo zfw --vrrp-enable -d 321 | ``` 322 | 323 | 324 | ### Inserting / Deleting rules 325 | 326 | The -t, --tproxy-port is has a dual purpose one it to signify the tproxy port used by openziti routers in tproxy mode and the other is to identify either local passthrough with value of 0 and the other is tunnel redirect mode with value of 65535. 327 | 328 | - Example Insert 329 | If you disable default ssh handling with a device interface ip of 172.16.240.1 and you want to insert a user rule with source 330 | filtering that only allows source ip 10.1.1.1/32 to reach 172.16.240.1:22. 331 | 332 | Particularly notice -t 0 which means that matched packets will pass to the local OS stack and are not redirected to tproxy ports or tunnel interface. 333 | ``` 334 | sudo zfw -I -c 172.16.240.1 -m 32 -o 10.1.1.1 -n 32 -p tcp -l 22 -h 22 -t 0 335 | ``` 336 | 337 | - Example Delete 338 | 339 | ``` 340 | sudo zfw -D -c 172.16.240.1 -m 32 -o 10.1.1.1 -n 32 -p tcp -l 22 341 | ``` 342 | 343 | - Example: Remove all rule entries from FW 344 | 345 | ``` 346 | sudo zfw -F 347 | ``` 348 | 349 | ### Debugging 350 | 351 | Example: Monitor ebpf trace messages 352 | 353 | ``` 354 | sudo zfw -M |all 355 | 356 | ``` 357 | 358 | ``` 359 | Jul 26 2023 01:42:24.108913490 : ens33 : TCP :172.16.240.139:51166[0:c:29:6a:d1:61] > 192.168.1.1:5201[0:c:29:bb:24:a1] redirect ---> ziti0 360 | Jul 26 2023 01:42:24.108964534 : ziti0 : TCP :192.168.1.1:0[0:c:29:bb:24:a1] > 172.16.240.139:0[0:c:29:6a:d1:61] redirect ---> ens33 361 | Jul 26 2023 01:42:24.109011595 : ziti0 : TCP :192.168.1.1:0[0:c:29:bb:24:a1] > 172.16.240.139:0[0:c:29:6a:d1:61] redirect ---> ens33 362 | Jul 26 2023 01:42:24.109036999 : ziti0 : TCP :192.168.1.1:0[0:c:29:bb:24:a1] > 172.16.240.139:0[0:c:29:6a:d1:61] redirect ---> ens33 363 | Jul 26 2023 01:42:24.108913490 : ens33 : TCP :172.16.240.139:51166[0:c:29:6a:d1:61] > 192.168.1.1:5201[0:c:29:bb:24:a1] redirect ---> ziti0 364 | Jul 26 2023 01:42:24.108964534 : ziti0 : TCP :192.168.1.1:0[0:c:29:bb:24:a1] > 172.16.240.139:0[0:c:29:6a:d1:61] redirect ---> ens33 365 | Jul 26 2023 01:42:24.109011595 : ziti0 : TCP :192.168.1.1:0[0:c:29:bb:24:a1] > 172.16.240.139:0[0:c:29:6a:d1:61] redirect ---> ens33 366 | ``` 367 | 368 | Example: List all rules in Firewall 369 | 370 | ``` 371 | sudo zfw -L 372 | ``` 373 | ``` 374 | target proto origin destination mapping: interface list 375 | ------ ----- --------------- ------------------ --------------------------------------------------------- ---------------- 376 | TPROXY tcp 0.0.0.0/0 10.0.0.16/28 dpts=22:22 TPROXY redirect 127.0.0.1:33381 [ens33,lo] 377 | TPROXY tcp 0.0.0.0/0 10.0.0.16/28 dpts=30000:40000 TPROXY redirect 127.0.0.1:33381 [] 378 | TPROXY udp 0.0.0.0/0 172.20.1.0/24 dpts=5000:10000 TPROXY redirect 127.0.0.1:59394 [] 379 | TPROXY tcp 0.0.0.0/0 172.16.1.0/24 dpts=22:22 TPROXY redirect 127.0.0.1:33381 [] 380 | TPROXY tcp 0.0.0.0/0 172.16.1.0/24 dpts=30000:40000 TPROXY redirect 127.0.0.1:33381 [] 381 | PASSTHRU udp 0.0.0.0/0 192.168.3.0/24 dpts=5:7 PASSTHRU to 192.168.3.0/24 [] 382 | PASSTHRU udp 10.1.1.1/32 192.168.100.100/32 dpts=50000:60000 PASSTHRU to 192.168.100.100/32 [] 383 | PASSTHRU tcp 10.230.40.1/32 192.168.100.100/32 dpts=60000:65535 PASSTHRU to 192.168.100.100/32 [] 384 | TPROXY udp 0.0.0.0/0 192.168.0.3/32 dpts=5000:10000 TPROXY redirect 127.0.0.1:59394 [] 385 | PASSTHRU tcp 0.0.0.0/0 192.168.100.100/32 dpts=60000:65535 PASSTHRU to 192.168.100.100/32 [] 386 | TUNMODE udp 0.0.0.0/0 100.64.0.0/10 dpts=1:65535 TUNMODE redirect:tun0 [] 387 | ``` 388 | 389 | - Example: List rules in firewall for a given prefix and protocol. If source specific you must include the o 390 | -n 391 | 392 | ``` 393 | sudo zfw -L -c 192.168.100.100 -m 32 -p udp 394 | ``` 395 | ``` 396 | target proto origin destination mapping: interface list 397 | ------ ----- -------- ------------------ --------------------------------------------------------- ------------------ 398 | PASSTHRU udp 0.0.0.0/0 192.168.100.100/32 dpts=50000:60000 PASSTHRU to 192.168.100.100/32 [] 399 | ``` 400 | 401 | - Example: List rules in firewall for a given prefix 402 | Usage: zfw -L -c -m -p 403 | ``` 404 | sudo zfw -L -c 192.168.100.100 -m 32 405 | ``` 406 | ``` 407 | target proto origin destination mapping: interface list 408 | ------ ----- -------- ------------------ --------------------------------------------------------- ------------------- 409 | PASSTHRU udp 0.0.0.0/0 192.168.100.100/32 dpts=50000:60000 PASSTHRU to 192.168.100.100/32 [] 410 | PASSTHRU tcp 0.0.0.0/0 192.168.100.100/32 dpts=60000:65535 PASSTHRU to 192.168.100.100/32 [] 411 | ``` 412 | - Example: List all interface settings 413 | 414 | ``` 415 | sudo zfw -L -E 416 | ``` 417 | ``` 418 | lo: 1 419 | -------------------------- 420 | icmp echo :1 421 | verbose :0 422 | ssh disable :0 423 | per interface :0 424 | tc ingress filter :0 425 | tc egress filter :0 426 | tun mode intercept :0 427 | vrrp enable :0 428 | -------------------------- 429 | 430 | ens33: 2 431 | -------------------------- 432 | icmp echo :0 433 | verbose :0 434 | ssh disable :0 435 | per interface :0 436 | tc ingress filter :1 437 | tc egress filter :1 438 | tun mode intercept :1 439 | vrrp enable :1 440 | -------------------------- 441 | 442 | ens37: 3 443 | -------------------------- 444 | icmp echo :0 445 | verbose :0 446 | ssh disable :0 447 | per interface :0 448 | tc ingress filter :0 449 | tc egress filter :0 450 | tun mode intercept :0 451 | vrrp enable :0 452 | -------------------------- 453 | 454 | tun0: 18 455 | -------------------------- 456 | verbose :0 457 | cidr :100.64.0.0 458 | mask :10 459 | -------------------------- 460 | ``` 461 | 462 | - Example Detaching bpf from interface: 463 | 464 | ``` 465 | sudo zfw --set-tc-filter --direction --disable 466 | ``` 467 | 468 | Example: Remove all tc-ebpf on router 469 | 470 | ``` 471 | sudo zfw --disable-ebpf 472 | ``` 473 | ``` 474 | tc parent del : lo 475 | tc parent del : ens33 476 | tc parent del : ens37 477 | removing /sys/fs/bpf/tc/globals/zt_tproxy_map 478 | removing /sys/fs/bpf/tc/globals/diag_map 479 | removing /sys/fs/bpf/tc/globals/ifindex_ip_map 480 | removing /sys/fs/bpf/tc/globals/tuple_count_map 481 | removing /sys/fs/bpf/tc/globals/prog_map 482 | removing /sys/fs/bpf/tc/globals/udp_map 483 | removing /sys/fs/bpf/tc//globals/matched_map 484 | removing /sys/fs/bpf/tc/globals/tcp_map 485 | ``` 486 | 487 | 488 | -------------------------------------------------------------------------------- /files/bin/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/r-caamano/zfw/724205c6a7a70802657acc137075bffb11a7efa4/files/bin/.gitkeep -------------------------------------------------------------------------------- /files/json/ebpf_config.json.sample: -------------------------------------------------------------------------------- 1 | {"InternalInterfaces":[{"Name":"ens33", "OutboundPassThroughTrack": false, "PerInterfaceRules": false}], 2 | "ExternalInterfaces":[]} 3 | -------------------------------------------------------------------------------- /files/scripts/revert_ebpf_router.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import subprocess 4 | import sys 5 | import json 6 | import yaml 7 | from signal import signal, SIGPIPE, SIG_DFL 8 | signal(SIGPIPE,SIG_DFL) 9 | 10 | 11 | def set_tproxy_mode(): 12 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 13 | try: 14 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 15 | config = yaml.load(config_file, Loader=yaml.FullLoader) 16 | if(config): 17 | if('listeners' in config.keys()): 18 | for key in config['listeners']: 19 | if(('binding' in key.keys()) and (key['binding'] == 'tunnel')): 20 | if('options' in key.keys()): 21 | if('mode' in key['options']): 22 | if(key['options']['mode'] == 'tproxy'): 23 | print("ziti-router config.yml already converted to use tproxy!") 24 | elif(key['options']['mode'] == 'tproxy:/opt/openziti/bin/zfw'): 25 | key['options']['mode'] = 'tproxy' 26 | write_config(config) 27 | return True 28 | else: 29 | print("ziti-router config.yml already converted to use tproxy!") 30 | else: 31 | print('Mandatory key \'options\' missing from binding: tunnel') 32 | sys.exit(1) 33 | else: 34 | print('Mandatory key \'listeners\' missing in config.yml') 35 | sys.exit(1) 36 | except Exception as e: 37 | print(e) 38 | sys.exit(1) 39 | else: 40 | print('ziti-router not installed, skipping ebpf router configuration!') 41 | sys.exit(1) 42 | return False 43 | 44 | def write_config(config): 45 | try: 46 | with open('/opt/openziti/ziti-router/config.yml', 'w') as config_file: 47 | yaml.dump(config, config_file, sort_keys=False) 48 | except Exception as e: 49 | print(e) 50 | sys.exit(1) 51 | 52 | def delete(rule): 53 | os.system('yes | /usr/sbin/ufw delete ' + str(rule) + ' > /dev/null 2>&1') 54 | 55 | def remove_ufw_rule(rule): 56 | process = subprocess.Popen(['ufw', 'status', 'numbered'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 57 | out, err = process.communicate() 58 | data = out.decode().splitlines() 59 | count = 1 60 | for line in data: 61 | if((line.find(rule) >= 0) and (line.find('ALLOW IN') >= 0)): 62 | print("removing:", line) 63 | delete(count) 64 | if(line.startswith('[')): 65 | count = count + 1 66 | 67 | def iterate_rules(intf): 68 | rules = ['Anywhere on ' + intf, 'Anywhere (v6) on ' + intf] 69 | for rule in rules: 70 | remove_ufw_rule(rule) 71 | 72 | if(os.path.exists('/opt/openziti/etc/ebpf_config.json')): 73 | with open('/opt/openziti/etc/ebpf_config.json','r') as jfile: 74 | try: 75 | config = json.loads(jfile.read()) 76 | if(config): 77 | if("InternalInterfaces" in config.keys()): 78 | i_interfaces = config["InternalInterfaces"] 79 | if len(i_interfaces): 80 | for interface in i_interfaces: 81 | if("Name" in interface.keys()): 82 | if(interface["Name"] != "lo"): 83 | print("Attempting to restore ufw state: ",interface["Name"]) 84 | iterate_rules(interface["Name"]) 85 | else: 86 | print('Mandatory key \"Name\" missing skipping internal interface entry!') 87 | else: 88 | print("No internal interfaces listed in /opt/openziti/etc/ebpf_config.json skipping internal interface ufw reversion interface!") 89 | if("ExternalInterfaces" in config.keys()): 90 | e_interfaces = config["ExternalInterfaces"] 91 | if len(e_interfaces): 92 | for interface in e_interfaces: 93 | if("Name" in interface.keys()): 94 | if(interface["Name"] != "lo"): 95 | print("Attempting to restore ufw state: ",interface["Name"]) 96 | iterate_rules(interface["Name"]) 97 | else: 98 | print('Mandatory key \"Name\" missing skipping external interface ufw reversion!') 99 | except Exception as e: 100 | print("Malformed or missing json object in /opt/openziti/etc/ebpf_config.json can't revert ufw!") 101 | 102 | service = False 103 | if(os.path.exists('/etc/systemd/system/ziti-router.service')): 104 | unconfigured = os.system("grep -r 'ExecStartPre\=\-\/opt/openziti\/bin\/start_ebpf_router.py' /etc/systemd/system/ziti-router.service") 105 | if(not unconfigured): 106 | os.system("sed -i 's/#ExecStartPre\=\-\/opt\/netfoundry\/ebpf\/objects\/etables \-F \-r/ExecStartPre\=-\/opt\/netfoundry\/ebpf\/objects\/etables \-F \-r/g' /etc/systemd/system/ziti-router.service") 107 | os.system("sed -i 's/#ExecStartPre\=\-\/opt\/netfoundry\/ebpf\/scripts\/tproxy_splicer_startup.sh/ExecStartPre\=\-\/opt\/netfoundry\/ebpf\/scripts\/tproxy_splicer_startup.sh/g' /etc/systemd/system/ziti-router.service") 108 | test1 = os.system("sed -i '/ExecStartPre\=\-\/opt\/openziti\/bin\/start_ebpf_router.py/d' /etc/systemd/system/ziti-router.service") 109 | if(not test1): 110 | test1 = os.system("systemctl daemon-reload") 111 | if(not test1): 112 | service = True 113 | os.system("/opt/openziti/bin/zfw -Q") 114 | if(os.path.exists("/opt/openziti/etc/ebpf_config.json")): 115 | os.remove("/opt/openziti/etc/ebpf_config.json") 116 | if(os.path.exists("/opt/openziti/bin/user/user_rules.sh")): 117 | os.remove("/opt/openziti/bin/user/user_rules.sh") 118 | print("Successfully reverted ziti-router.service!") 119 | else: 120 | print("Failed to revert ziti-router.service!") 121 | else: 122 | print("ziti-router.service already reverted. Nothing to do!") 123 | else: 124 | print("Skipping ziti-router.service reversal. File does not exist!") 125 | 126 | if(set_tproxy_mode()): 127 | if service: 128 | print("config.yml successfully reverted. restarting ziti-router.service") 129 | os.system('systemctl restart ziti-router.service') 130 | if(not os.system('systemctl is-active --quiet ziti-router.service')): 131 | print("ziti-router.service successfully restarted") 132 | if(os.path.exists('/opt/netfoundry/ziti/ziti-router/config.yml')): 133 | print("Detected Netfoundry install/registration!") 134 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 135 | print("Removing symlink from /opt/openziti/ziti-router to /opt/netfoundry/ziti/ziti-router") 136 | os.unlink('/opt/openziti/ziti-router') 137 | else: 138 | print("No symlink found nothing to do!") 139 | else: 140 | print('ziti-router.service unable to start check router logs') 141 | else: 142 | print("ziti-router config already not set to use ebpf!") 143 | -------------------------------------------------------------------------------- /files/scripts/set_xdp_redirect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import subprocess 3 | import os 4 | 5 | def xdp_status(interface): 6 | process = subprocess.Popen(['/usr/sbin/ip', 'link', 'show', interface], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 7 | out, err = process.communicate() 8 | data = out.decode().splitlines() 9 | if(len(data)): 10 | for line in data: 11 | if(line.find('prog/xdp') >= 0): 12 | return True 13 | else: 14 | return False 15 | 16 | process = subprocess.Popen(['ip', 'add'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 17 | out, err = process.communicate() 18 | data = out.decode().splitlines() 19 | interfaceName = None 20 | ip = '100.64.0.1' 21 | iprange = os.environ.get('ZITI_DNS_IP_RANGE') 22 | if(iprange): 23 | print('Reading ip from ZITI_DNS_IP_RANGE: ' + iprange) 24 | ip = iprange.split('/')[0] 25 | else: 26 | print('Using default tun ip: ' + ip) 27 | for line in data: 28 | if (line.find(ip) != -1): 29 | interfaceName = line.split(" ")[-1] 30 | if interfaceName: 31 | if(not xdp_status(interfaceName)): 32 | os.system('/usr/sbin/ip link set ' + interfaceName + ' xdpgeneric obj /opt/openziti/bin/zfw_xdp_tun_ingress.o sec xdp_redirect') 33 | 34 | -------------------------------------------------------------------------------- /files/scripts/start_ebpf_router.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import sys 4 | import json 5 | import subprocess 6 | import time 7 | import yaml 8 | 9 | def tc_status(interface, direction): 10 | process = subprocess.Popen(['tc', 'filter', 'show', 'dev', interface, direction], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 11 | out, err = process.communicate() 12 | data = out.decode().splitlines() 13 | if(len(data)): 14 | return True 15 | else: 16 | return False 17 | 18 | def add_health_check_rules(lan_ip, lan_mask): 19 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 20 | try: 21 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 22 | config = yaml.load(config_file, Loader=yaml.FullLoader) 23 | if(config): 24 | if('web' in config.keys()): 25 | for key in config['web']: 26 | if(('name' in key.keys()) and (key['name'] == 'health-check')): 27 | if('bindPoints' in key.keys()): 28 | for point in key['bindPoints']: 29 | address = point['address'] 30 | addr_array = address.split(':') 31 | if(len(addr_array)): 32 | try: 33 | port = addr_array[-1].strip() 34 | if(int(port) > 0): 35 | os.system('/opt/openziti/bin/zfw -I -c ' + lan_ip + ' -m ' + lan_mask + ' -l ' + port + ' -h ' + port + ' -t 0 -p tcp') 36 | except Exception as e: 37 | print(e) 38 | pass 39 | except Exception as e: 40 | print(e) 41 | 42 | 43 | def add_link_listener_rules(lan_ip, lan_mask): 44 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 45 | try: 46 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 47 | config = yaml.load(config_file, Loader=yaml.FullLoader) 48 | if(config): 49 | if('link' in config.keys()): 50 | if('listeners' in config['link'].keys()): 51 | for key in config['link']['listeners']: 52 | if(('binding' in key.keys()) and (key['binding'] == 'transport')): 53 | if('bind' in key.keys()): 54 | address = key['bind'] 55 | addr_array = address.split(':') 56 | if(len(addr_array) == 3): 57 | try: 58 | port = addr_array[-1].strip() 59 | if((int(port) > 0) and (addr_array[0] == 'tls')): 60 | os.system('/opt/openziti/bin/zfw -I -c ' + lan_ip + ' -m ' + lan_mask + ' -l ' + port + ' -h ' + port + ' -t 0 -p tcp') 61 | except Exception as e: 62 | print(e) 63 | pass 64 | except Exception as e: 65 | print(e) 66 | 67 | def add_edge_listener_rules(lan_ip, lan_mask): 68 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 69 | try: 70 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 71 | config = yaml.load(config_file, Loader=yaml.FullLoader) 72 | if(config): 73 | if('listeners' in config.keys()): 74 | for key in config['listeners']: 75 | if(('binding' in key.keys()) and (key['binding'] == 'edge')): 76 | if('address' in key.keys()): 77 | address = key['address'] 78 | addr_array = address.split(':') 79 | if(len(addr_array) == 3): 80 | port = addr_array[-1].strip() 81 | try: 82 | port = addr_array[-1].strip() 83 | if((int(port) > 0) and (addr_array[0] == 'tls')): 84 | os.system('/opt/openziti/bin/zfw -I -c ' + lan_ip + ' -m ' + lan_mask + ' -l ' + port + ' -h ' + port + ' -t 0 -p tcp') 85 | except Exception as e: 86 | print(e) 87 | pass 88 | except Exception as e: 89 | print(e) 90 | 91 | def add_resolver_rules(): 92 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 93 | try: 94 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 95 | config = yaml.load(config_file, Loader=yaml.FullLoader) 96 | if(config): 97 | if('listeners' in config.keys()): 98 | for key in config['listeners']: 99 | if(('binding' in key.keys()) and (key['binding'] == 'tunnel')): 100 | if('options' in key.keys()): 101 | if('resolver' in key['options']): 102 | address = key['options']['resolver'] 103 | addr_array = address.split(':') 104 | if(len(addr_array) == 3): 105 | port = addr_array[-1].strip() 106 | lan_ip = addr_array[1].split('//') 107 | lan_mask = '32' 108 | try: 109 | port = addr_array[-1].strip() 110 | lan_ip = addr_array[1].split('//')[1] 111 | if((int(port) > 0)): 112 | os.system('/opt/openziti/bin/zfw -I -c ' + lan_ip + ' -m ' + lan_mask + ' -l ' + port + ' -h ' + port + ' -t 0 -p tcp') 113 | os.system('/opt/openziti/bin/zfw -I -c ' + lan_ip + ' -m ' + lan_mask + ' -l ' + port + ' -h ' + port + ' -t 0 -p udp') 114 | except Exception as e: 115 | print(e) 116 | pass 117 | except Exception as e: 118 | print(e) 119 | 120 | def set_zfw_mode(): 121 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 122 | try: 123 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 124 | config = yaml.load(config_file, Loader=yaml.FullLoader) 125 | if(config): 126 | if('listeners' in config.keys()): 127 | for key in config['listeners']: 128 | if(('binding' in key.keys()) and (key['binding'] == 'tunnel')): 129 | if('options' in key.keys()): 130 | if('mode' in key['options']): 131 | if(key['options']['mode'] == 'tproxy:/opt/openziti/bin/zfw'): 132 | print("ziti-router config already converted to use ebpf diverter!") 133 | else: 134 | key['options']['mode'] = 'tproxy:/opt/openziti/bin/zfw' 135 | write_config(config) 136 | return True 137 | else: 138 | key['options']['mode'] = 'tproxy:/opt/openziti/bin/zfw' 139 | write_config(config) 140 | return True 141 | else: 142 | print('Mandatory key \'options\' missing from binding: tunnel') 143 | else: 144 | print('Mandatory key \'listeners\' missing in config.yml') 145 | except Exception as e: 146 | print(e) 147 | else: 148 | print('ziti-router not installed, skipping ebpf router configuration!') 149 | return False 150 | 151 | def write_config(config): 152 | try: 153 | with open('/opt/openziti/ziti-router/config.yml', 'w') as config_file: 154 | yaml.dump(config, config_file, sort_keys=False) 155 | except Exception as e: 156 | print(e) 157 | 158 | def get_lanIf(): 159 | if(os.path.exists('/opt/openziti/ziti-router/config.yml')): 160 | try: 161 | with open('/opt/openziti/ziti-router/config.yml') as config_file: 162 | config = yaml.load(config_file, Loader=yaml.FullLoader) 163 | if(config): 164 | if('listeners' in config.keys()): 165 | for key in config['listeners']: 166 | if(('binding' in key.keys()) and (key['binding'] == 'tunnel')): 167 | if('options' in key.keys()): 168 | if('lanIf' in key['options']): 169 | return key['options']['lanIf'] 170 | else: 171 | print('Mandatory key \'options\' missing from binding: tunnel') 172 | else: 173 | print('Mandatory key \'listeners\' missing in config.yml') 174 | except Exception as e: 175 | print(e) 176 | else: 177 | print('ziti-router not installed, skipping ebpf router configuration!') 178 | return '' 179 | 180 | def get_if_ip(intf): 181 | process = subprocess.Popen(['ip', 'add'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 182 | out, err = process.communicate() 183 | data = out.decode().splitlines() 184 | for line in data: 185 | if((line.find(intf) >= 0) and (line.find('inet') >= 0)): 186 | search_list = line.strip().split(" ") 187 | if(search_list[-1].strip() == intf): 188 | return search_list[1] 189 | else: 190 | return "" 191 | 192 | def set_local_rules(resolver): 193 | default_ip = '0.0.0.0' 194 | default_mask = '0' 195 | if(len(resolver.split('/')) == 2): 196 | lan_ip = resolver.split('/')[0] 197 | lan_mask = '32' 198 | else: 199 | lan_ip = default_ip 200 | lan_mask = default_mask 201 | add_edge_listener_rules(lan_ip, lan_mask) 202 | add_link_listener_rules(lan_ip, lan_mask) 203 | add_health_check_rules(lan_ip, lan_mask) 204 | add_resolver_rules() 205 | 206 | netfoundry = False 207 | if(os.path.exists('/opt/netfoundry/ziti/ziti-router/config.yml')): 208 | netfoundry = True 209 | print("Detected Netfoundry install/registration!") 210 | if(not os.path.exists('/opt/openziti/ziti-router/config.yml')): 211 | print("Installing symlink from /opt/openziti/ziti-router to /opt/netfoundry/ziti/ziti-router!") 212 | os.symlink('/opt/netfoundry/ziti/ziti-router', '/opt/openziti/ziti-router') 213 | else: 214 | print("Symlink found nothing to do!") 215 | 216 | lanIf = get_lanIf() 217 | if(not len(lanIf)): 218 | print("Unable to retrieve LanIf!") 219 | else: 220 | if(not os.path.exists('/opt/openziti/etc/ebpf_config.json')): 221 | if(os.path.exists('/opt/openziti/etc/ebpf_config.json.sample')): 222 | with open('/opt/openziti/etc/ebpf_config.json.sample','r') as jfile: 223 | try: 224 | config = json.loads(jfile.read()) 225 | if(config): 226 | if("InternalInterfaces" in config.keys()): 227 | interfaces = config["InternalInterfaces"] 228 | if len(interfaces): 229 | interface = interfaces[0] 230 | if("Name" in interface.keys()): 231 | interface['Name'] = lanIf 232 | else: 233 | print('Missing mandatory key: Name') 234 | sys.exit(1) 235 | else: 236 | print('Invalid config no interfaces found!') 237 | sys.exit(1) 238 | with open('/opt/openziti/etc/ebpf_config.json', 'w') as ofile: 239 | json.dump(config, ofile) 240 | except Exception as e: 241 | print('Malformed or missing json object in /opt/openziti/etc/ebpf_config.json.sample') 242 | sys.exit(1) 243 | else: 244 | print('File does not exist: /opt/openziti/etc/ebpf_config.json.sample') 245 | else: 246 | print('File already exist: /opt/openziti/etc/ebpf_config.json') 247 | 248 | router_config = set_zfw_mode() 249 | internal_list = [] 250 | external_list = [] 251 | per_interface_rules = dict() 252 | outbound_passthrough_track = dict() 253 | if(os.path.exists('/opt/openziti/etc/ebpf_config.json')): 254 | with open('/opt/openziti/etc/ebpf_config.json','r') as jfile: 255 | try: 256 | config = json.loads(jfile.read()) 257 | if(config): 258 | if("InternalInterfaces" in config.keys()): 259 | i_interfaces = config["InternalInterfaces"] 260 | if len(i_interfaces): 261 | for interface in i_interfaces: 262 | if("Name" in interface.keys()): 263 | print("Attempting to add ebpf ingress to: ",interface["Name"]) 264 | internal_list.append(interface["Name"]) 265 | if("OutboundPassThroughTrack") in interface.keys(): 266 | if(interface["OutboundPassThroughTrack"]): 267 | outbound_passthrough_track[interface["Name"]] = True; 268 | else: 269 | outbound_passthrough_track[interface["Name"]] = False; 270 | else: 271 | outbound_passthrough_track[interface["Name"]] = False; 272 | if("PerInterfaceRules") in interface.keys(): 273 | if(interface["PerInterfaceRules"]): 274 | per_interface_rules[interface["Name"]] = True; 275 | else: 276 | per_interface_rules[interface["Name"]] = False; 277 | else: 278 | per_interface_rules[interface["Name"]] = False; 279 | else: 280 | print('Mandatory key \"Name\" missing skipping internal interface entry!') 281 | 282 | else: 283 | print("No internal interfaces listed in /opt/openziti/etc/ebpf_config.json add at least one interface") 284 | sys.exit(1) 285 | if("ExternalInterfaces" in config.keys()): 286 | e_interfaces = config["ExternalInterfaces"] 287 | if len(e_interfaces): 288 | for interface in e_interfaces: 289 | if("Name" in interface.keys()): 290 | print("Attempting to add ebpf egress to: ",interface["Name"]) 291 | external_list.append(interface["Name"]) 292 | if("OutboundPassThroughTrack") in interface.keys(): 293 | if(interface["OutboundPassThroughTrack"]): 294 | outbound_passthrough_track[interface["Name"]] = True; 295 | else: 296 | outbound_passthrough_track[interface["Name"]] = False; 297 | else: 298 | outbound_passthrough_track[interface["Name"]] = True; 299 | if("PerInterfaceRules") in interface.keys(): 300 | if(interface["PerInterfaceRules"]): 301 | per_interface_rules[interface["Name"]] = True; 302 | else: 303 | per_interface_rules[interface["Name"]] = False; 304 | else: 305 | per_interface_rules[interface["Name"]] = True; 306 | else: 307 | print('Mandatory key \"Name\" missing skipping external interface entry!') 308 | else: 309 | print("No External interfaces listed in /opt/openziti/etc/ebpf_config.json") 310 | except Exception as e: 311 | print("Malformed or missing json object in /opt/openziti/etc/ebpf_config.json") 312 | sys.exit(1) 313 | else: 314 | print("Missing /opt/openziti/etc/ebpf_config.json can't set ebpf interface config") 315 | sys.exit(1) 316 | 317 | ingress_object_file = '/opt/openziti/bin/zfw_tc_ingress.o' 318 | egress_object_file = '/opt/openziti/bin/zfw_tc_outbound_track.o' 319 | status = subprocess.run(['/opt/openziti/bin/zfw', '-L', '-E'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 320 | if(status.returncode): 321 | test1 = subprocess.run(['/opt/openziti/bin/zfw', '-Q'],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 322 | if(test1.returncode): 323 | print("Ebpf not running no maps to clear") 324 | for i in internal_list: 325 | if(not tc_status(i, "ingress")): 326 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + ingress_object_file + " -z ingress") 327 | time.sleep(1) 328 | if(test1): 329 | print("Cant attach " + i + " to tc ingress with " + ingress_object_file) 330 | continue 331 | else: 332 | print("Attached " + ingress_object_file + " to " + i) 333 | os.system("sudo ufw allow in on " + i + " to any") 334 | if(per_interface_rules[i]): 335 | os.system("/opt/openziti/bin/zfw -P " + i) 336 | if(not tc_status(i, "egress")): 337 | if(outbound_passthrough_track[i]): 338 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + egress_object_file + " -z egress") 339 | if(test1): 340 | print("Cant attach " + i + " to tc egress with " + egress_object_file) 341 | continue 342 | else: 343 | print("Attached " + egress_object_file + " to " + i) 344 | for e in external_list: 345 | if(not tc_status(e, "ingress")): 346 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + ingress_object_file + " -z ingress") 347 | if(test1): 348 | os.system("/opt/openziti/bin/zfw -Q") 349 | print("Cant attach " + e + " to tc ingress with " + ingress_object_file) 350 | continue 351 | else: 352 | print("Attached " + ingress_object_file + " to " + e) 353 | os.system("sudo ufw allow in on " +e + " to any") 354 | time.sleep(1) 355 | if(per_interface_rules[e]): 356 | os.system("/opt/openziti/bin/zfw -P " + e) 357 | if(not tc_status(e, "egress")): 358 | if(outbound_passthrough_track[e]): 359 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + egress_object_file + " -z egress") 360 | if(test1): 361 | print("Cant attach " + e + " to tc egress with " + egress_object_file) 362 | os.system("/opt/openziti/bin/zfw -Q") 363 | continue 364 | else: 365 | print("Attached " + egress_object_file + " to " + e) 366 | if(os.path.exists("/opt/openziti/bin/user/user_rules.sh")): 367 | print("Adding user defined rules") 368 | os.system("/opt/openziti/bin/user/user_rules.sh") 369 | else: 370 | print("ebpf already running!"); 371 | os.system("/usr/sbin/zfw -F -r") 372 | print("Flushed Table") 373 | for i in internal_list: 374 | if(not tc_status(i, "ingress")): 375 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + ingress_object_file + " -z ingress") 376 | time.sleep(1) 377 | if(test1): 378 | print("Cant attach " + i + " to tc ingress with " + ingress_object_file) 379 | else: 380 | print("Attached " + ingress_object_file + " to " + i) 381 | os.system("sudo ufw allow in on " + i + " to any") 382 | if(per_interface_rules[i]): 383 | os.system("/opt/openziti/bin/zfw -P " + i) 384 | if(not tc_status(i, "egress")): 385 | if(outbound_passthrough_track[i]): 386 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + egress_object_file + " -z egress") 387 | if(test1): 388 | print("Cant attach " + i + " to tc egress with " + egress_object_file) 389 | else: 390 | print("Attached " + egress_object_file + " to " + i) 391 | for e in external_list: 392 | if(not tc_status(e, "ingress")): 393 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + ingress_object_file + " -z ingress") 394 | if(test1): 395 | print("Cant attach " + e + " to tc ingress with " + ingress_object_file) 396 | else: 397 | print("Attached " + ingress_object_file + " to " + e) 398 | os.system("sudo ufw allow in on " +e + " to any") 399 | time.sleep(1) 400 | if(per_interface_rules[e]): 401 | os.system("/opt/openziti/bin/zfw -P " + e) 402 | if(not tc_status(e, "egress")): 403 | if(outbound_passthrough_track[e]): 404 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + egress_object_file + " -z egress") 405 | if(test1): 406 | print("Cant attach " + e + " to tc egress with " + egress_object_file) 407 | else: 408 | print("Attached " + egress_object_file + " to " + e) 409 | if(os.path.exists("/opt/openziti/bin/user/user_rules.sh")): 410 | print("Adding user defined rules!") 411 | os.system("/opt/openziti/bin/user/user_rules.sh") 412 | 413 | resolver = get_if_ip(lanIf) 414 | if(len(resolver)): 415 | set_local_rules(resolver) 416 | if(os.path.exists('/etc/systemd/system/ziti-router.service') and router_config): 417 | unconfigured = os.system("grep -r 'ExecStartPre\=\-\/opt/openziti\/bin\/start_ebpf_router.py' /etc/systemd/system/ziti-router.service") 418 | if(unconfigured): 419 | test1 = 1 420 | test1 = os.system("sed -i '/ExecStart=/i ExecStartPre\=\-\/opt\/openziti\/bin\/start_ebpf_router.py' /etc/systemd/system/ziti-router.service") 421 | if(not test1): 422 | test1 = os.system("systemctl daemon-reload") 423 | if(not test1): 424 | print("Successfully converted ziti-router.service. Restarting!") 425 | os.system('systemctl restart ziti-router.service') 426 | if(not os.system('systemctl is-active --quiet ziti-router.service')): 427 | print("ziti-router.service successfully restarted!") 428 | else: 429 | print('ziti-router.service unable to start check router logs!') 430 | else: 431 | print("Failed to convert ziti-router.service!") 432 | else: 433 | print("ziti-router.service already converted. Nothing to do!") 434 | else: 435 | print("Skipping ziti-router.service conversion. File does not exist or is already converted to run ebpf!") 436 | sys.exit(0) 437 | -------------------------------------------------------------------------------- /files/scripts/start_ebpf_tunnel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import sys 4 | import json 5 | import subprocess 6 | import time 7 | 8 | def tc_status(interface, direction): 9 | process = subprocess.Popen(['tc', 'filter', 'show', 'dev', interface, direction], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 10 | out, err = process.communicate() 11 | data = out.decode().splitlines() 12 | if(len(data)): 13 | return True 14 | else: 15 | return False 16 | 17 | internal_list = [] 18 | external_list = [] 19 | per_interface_rules = dict() 20 | outbound_passthrough_track = dict() 21 | if(os.path.exists('/opt/openziti/etc/ebpf_config.json')): 22 | with open('/opt/openziti/etc/ebpf_config.json','r') as jfile: 23 | try: 24 | config = json.loads(jfile.read()) 25 | if(config): 26 | if("InternalInterfaces" in config.keys()): 27 | i_interfaces = config["InternalInterfaces"] 28 | if len(i_interfaces): 29 | for interface in i_interfaces: 30 | if("Name" in interface.keys()): 31 | print("Attempting to add ebpf ingress to: ",interface["Name"]) 32 | internal_list.append(interface["Name"]) 33 | if("OutboundPassThroughTrack") in interface.keys(): 34 | if(interface["OutboundPassThroughTrack"]): 35 | outbound_passthrough_track[interface["Name"]] = True; 36 | else: 37 | outbound_passthrough_track[interface["Name"]] = False; 38 | else: 39 | outbound_passthrough_track[interface["Name"]] = False; 40 | if("PerInterfaceRules") in interface.keys(): 41 | if(interface["PerInterfaceRules"]): 42 | per_interface_rules[interface["Name"]] = True; 43 | else: 44 | per_interface_rules[interface["Name"]] = False; 45 | else: 46 | per_interface_rules[interface["Name"]] = False; 47 | else: 48 | print('Mandatory key \"Name\" missing skipping internal interface entry!') 49 | 50 | else: 51 | print("No internal interfaces listed in /opt/openziti/etc/ebpf_config.json add at least one interface") 52 | sys.exit(1) 53 | if("ExternalInterfaces" in config.keys()): 54 | e_interfaces = config["ExternalInterfaces"] 55 | if len(e_interfaces): 56 | for interface in e_interfaces: 57 | if("Name" in interface.keys()): 58 | print("Attempting to add ebpf egress to: ",interface["Name"]) 59 | external_list.append(interface["Name"]) 60 | if("OutboundPassThroughTrack") in interface.keys(): 61 | if(interface["OutboundPassThroughTrack"]): 62 | outbound_passthrough_track[interface["Name"]] = True; 63 | else: 64 | outbound_passthrough_track[interface["Name"]] = False; 65 | else: 66 | outbound_passthrough_track[interface["Name"]] = True; 67 | if("PerInterfaceRules") in interface.keys(): 68 | if(interface["PerInterfaceRules"]): 69 | per_interface_rules[interface["Name"]] = True; 70 | else: 71 | per_interface_rules[interface["Name"]] = False; 72 | else: 73 | per_interface_rules[interface["Name"]] = True; 74 | else: 75 | print('Mandatory key \"Name\" missing skipping external interface entry!') 76 | else: 77 | print("No External interfaces listed in /opt/openziti/etc/ebpf_config.json") 78 | except Exception as e: 79 | print("Malformed or missing json object in /opt/openziti/etc/ebpf_config.json") 80 | sys.exit(1) 81 | else: 82 | print("Missing /opt/openziti/etc/ebpf_config.json can't set ebpf interface config") 83 | sys.exit(1) 84 | 85 | ingress_object_file = '/opt/openziti/bin/zfw_tc_ingress.o' 86 | egress_object_file = '/opt/openziti/bin/zfw_tc_outbound_track.o' 87 | if os.system("/opt/openziti/bin/zfw -L -E"): 88 | test1 = os.system("/opt/openziti/bin/zfw -Q") 89 | if test1: 90 | print("failed to clear ebpf maps") 91 | for i in internal_list: 92 | if(not tc_status(i, "ingress")): 93 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + ingress_object_file + " -z ingress") 94 | time.sleep(1) 95 | if(test1): 96 | print("Cant attach " + i + " to tc ingress with " + ingress_object_file) 97 | continue 98 | else: 99 | print("Attached " + ingress_object_file + " to " + i) 100 | os.system("sudo ufw allow in on " + i + " to any") 101 | os.system("/opt/openziti/bin/zfw -T " + i) 102 | if(per_interface_rules[i]): 103 | os.system("/opt/openziti/bin/zfw -P " + i) 104 | if(not tc_status(i, "egress")): 105 | if(outbound_passthrough_track[i]): 106 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + egress_object_file + " -z egress") 107 | if(test1): 108 | print("Cant attach " + i + " to tc egress with " + egress_object_file) 109 | continue 110 | else: 111 | print("Attached " + egress_object_file + " to " + i) 112 | for e in external_list: 113 | if(not tc_status(e, "ingress")): 114 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + ingress_object_file + " -z ingress") 115 | if(test1): 116 | os.system("/opt/openziti/bin/zfw -Q") 117 | print("Cant attach " + e + " to tc ingress with " + ingress_object_file) 118 | continue 119 | else: 120 | print("Attached " + ingress_object_file + " to " + e) 121 | os.system("sudo ufw allow in on " +e + " to any") 122 | time.sleep(1) 123 | os.system("/opt/openziti/bin/zfw -T " + e) 124 | if(per_interface_rules[e]): 125 | os.system("/opt/openziti/bin/zfw -P " + e) 126 | if(not tc_status(e, "egress")): 127 | if(outbound_passthrough_track[e]): 128 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + egress_object_file + " -z egress") 129 | if(test1): 130 | print("Cant attach " + e + " to tc egress with " + egress_object_file) 131 | os.system("/opt/openziti/bin/zfw -Q") 132 | continue 133 | else: 134 | print("Attached " + egress_object_file + " to " + e) 135 | if(os.path.exists("/opt/openziti/bin/user/user_rules.sh")): 136 | print("Adding user defined rules") 137 | os.system("/opt/openziti/bin/user/user_rules.sh") 138 | else: 139 | print("ebpf already running!"); 140 | os.system("/usr/sbin/zfw -F") 141 | print("Flushed Table") 142 | for i in internal_list: 143 | if(not tc_status(i, "ingress")): 144 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + ingress_object_file + " -z ingress") 145 | time.sleep(1) 146 | if(test1): 147 | print("Cant attach " + i + " to tc ingress with " + ingress_object_file) 148 | else: 149 | print("Attached " + ingress_object_file + " to " + i) 150 | os.system("sudo ufw allow in on " + i + " to any") 151 | os.system("/opt/openziti/bin/zfw -T " + i) 152 | if(per_interface_rules[i]): 153 | os.system("/opt/openziti/bin/zfw -P " + i) 154 | if(not tc_status(i, "egress")): 155 | if(outbound_passthrough_track[i]): 156 | test1 = os.system("/opt/openziti/bin/zfw -X " + i + " -O " + egress_object_file + " -z egress") 157 | if(test1): 158 | print("Cant attach " + i + " to tc egress with " + egress_object_file) 159 | else: 160 | print("Attached " + egress_object_file + " to " + i) 161 | for e in external_list: 162 | if(not tc_status(e, "ingress")): 163 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + ingress_object_file + " -z ingress") 164 | if(test1): 165 | print("Cant attach " + e + " to tc ingress with " + ingress_object_file) 166 | else: 167 | print("Attached " + ingress_object_file + " to " + e) 168 | os.system("sudo ufw allow in on " +e + " to any") 169 | time.sleep(1) 170 | os.system("/opt/openziti/bin/zfw -T " + e) 171 | if(per_interface_rules[e]): 172 | os.system("/opt/openziti/bin/zfw -P " + e) 173 | if(not tc_status(e, "egress")): 174 | if(outbound_passthrough_track[e]): 175 | test1 = os.system("/opt/openziti/bin/zfw -X " + e + " -O " + egress_object_file + " -z egress") 176 | if(test1): 177 | print("Cant attach " + e + " to tc egress with " + egress_object_file) 178 | else: 179 | print("Attached " + egress_object_file + " to " + e) 180 | if(os.path.exists("/opt/openziti/bin/user/user_rules.sh")): 181 | print("Adding user defined rules") 182 | os.system("/opt/openziti/bin/user/user_rules.sh") 183 | sys.exit(0) 184 | -------------------------------------------------------------------------------- /files/scripts/user_rules.sh.sample: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #sudo /usr/sbin/zfw -I -c 192.168.1.108 -m 32 -l 8000 -h 8000 -t 0 -p tcp 3 | -------------------------------------------------------------------------------- /files/services/fw-init.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Ziti-FW-Init 3 | Requires=network.target 4 | after=network.target 5 | 6 | [Service] 7 | User=root 8 | WorkingDirectory=/opt/openziti/bin 9 | ExecStart=/opt/openziti/bin/start_ebpf_router.py 10 | RestartSec=5 11 | Restart=on-failure 12 | TimeoutStartSec=60 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /files/services/ziti-fw-init.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Ziti-FW-Init 3 | Requires=network.target 4 | after=network.target 5 | 6 | [Service] 7 | User=root 8 | WorkingDirectory=/opt/openziti/bin 9 | ExecStart=/opt/openziti/bin/start_ebpf_tunnel.py 10 | RestartSec=5 11 | Restart=on-failure 12 | TimeoutStartSec=60 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /files/services/ziti-wrapper.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Ziti-Wrapper 3 | BindsTo=ziti-edge-tunnel.service 4 | After=ziti-edge-tunnel.service 5 | 6 | [Service] 7 | User=root 8 | EnvironmentFile=/opt/openziti/etc/ziti-edge-tunnel.env 9 | ExecStartPre=/opt/openziti/bin/start_ebpf_tunnel.py 10 | ExecStart=/opt/openziti/bin/zfw_tunnwrapper 11 | ExecStartPost=-/opt/openziti/bin/set_xdp_redirect.py 12 | Restart=always 13 | RestartSec=3 14 | 15 | [Install] 16 | WantedBy=ziti-edge-tunnel.service 17 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | SHELL=/bin/bash 2 | IDIR = /usr/include/aarch64-linux-gnu/ 3 | CFLAGS=-I$(IDIR) 4 | CC=clang 5 | uname_m := $(shell uname -m) 6 | all: zfw zfw_tc_ingress.o zfw_tc_ingress.o zfw_xdp_tun_ingress.o zfw_tc_outbound_track.o zfw_tunnwrapper 7 | zfw: zfw.c 8 | ifeq ($(uname_m),aarch64) 9 | $(CC) -D BPF_MAX_ENTRIES=100000 -O1 -lbpf -o zfw zfw.c $(CFLAGS) 10 | else 11 | $(CC) -D BPF_MAX_ENTRIES=100000 -O1 -lbpf -o zfw zfw.c 12 | endif 13 | zfw_tc_ingress.o: zfw_tc_ingress.c 14 | ifeq ($(uname_m),aarch64) 15 | $(CC) -D BPF_MAX_ENTRIES=100000 -g -O2 -Wall -Wextra -target bpf -c zfw_tc_ingress.c -o zfw_tc_ingress.o $(CFLAGS) 16 | else 17 | $(CC) -D BPF_MAX_ENTRIES=100000 -g -O2 -Wall -Wextra -target bpf -c zfw_tc_ingress.c -o zfw_tc_ingress.o 18 | endif 19 | zfw_xdp_tun_ingress.o: zfw_xdp_tun_ingress.c 20 | ifeq ($(uname_m),aarch64) 21 | $(CC) -O2 -g -Wall -target bpf -c zfw_xdp_tun_ingress.c -o zfw_xdp_tun_ingress.o $(CFLAGS) 22 | else 23 | $(CC) -O2 -g -Wall -target bpf -c zfw_xdp_tun_ingress.c -o zfw_xdp_tun_ingress.o 24 | endif 25 | zfw_tc_outbound_track.o: zfw_tc_outbound_track.c 26 | ifeq ($(uname_m),aarch64) 27 | $(CC) -g -O2 -Wall -Wextra -target bpf -c -o zfw_tc_outbound_track.o zfw_tc_outbound_track.c $(CFLAGS) 28 | else 29 | $(CC) -g -O2 -Wall -Wextra -target bpf -c -o zfw_tc_outbound_track.o zfw_tc_outbound_track.c 30 | endif 31 | zfw_tunnwrapper: zfw_tunnel_wrapper.c 32 | $(CC) -o zfw_tunnwrapper zfw_tunnel_wrapper.c -l json-c 33 | clean: 34 | rm -fr zfw zfw_tc_ingress.o zfw_tunnwrapper zfw_tc_ingress.o zfw_xdp_tun_ingress.o zfw_tc_outbound_track.o 35 | install: 36 | ./install.sh $(ARGS) 37 | -------------------------------------------------------------------------------- /src/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | if [ $# -lt 1 ]; then 3 | echo "" 4 | echo "Usage:" 5 | echo " $0 " 6 | exit 7 | fi 8 | if [ $1 == "router" ] 9 | then 10 | if [ ! -d "/opt/openziti/bin" ] 11 | then 12 | mkdir -p /opt/openziti/bin/user 13 | fi 14 | if [ ! -d "/opt/openziti/etc" ] 15 | then 16 | mkdir -p /opt/openziti/etc 17 | fi 18 | cp -p zfw /opt/openziti/bin 19 | cp -p zfw_tc_ingress.o /opt/openziti/bin 20 | cp -p zfw_tc_outbound_track.o /opt/openziti/bin 21 | cp -p ../files/scripts/start_ebpf_router.py /opt/openziti/bin 22 | cp -p ../files/scripts/revert_ebpf_router.py /opt/openziti/bin 23 | cp -p ../files/scripts/revert_ebpf_router.py /opt/openziti/bin 24 | cp -p ../files/scripts/user_rules.sh.sample /opt/openziti/bin/user 25 | cp -p ../files/json/ebpf_config.json.sample /opt/openziti/etc 26 | chmod 744 /opt/openziti/bin/start_ebpf_router.py 27 | chmod 744 /opt/openziti/bin/revert_ebpf_router.py 28 | chmod 744 /opt/openziti/bin/user/user_rules.sh.sample 29 | chmod 744 /opt/openziti/bin/zfw 30 | if [ ! -L "/usr/sbin/zfw" ] 31 | then 32 | ln -s /opt/openziti/bin/zfw /usr/sbin/zfw 33 | fi 34 | elif [ $1 == "tunnel" ] 35 | then 36 | if [ -d "/opt/openziti/bin" ] && [ -d "/opt/openziti/etc" ] 37 | then 38 | if [ ! -d "/opt/openziti/bin/user" ] 39 | then 40 | mkdir -p /opt/openziti/bin/user 41 | fi 42 | cp -p zfw /opt/openziti/bin 43 | cp -p zfw_tc_ingress.o /opt/openziti/bin 44 | cp -p zfw_tc_outbound_track.o /opt/openziti/bin 45 | cp -p zfw_xdp_tun_ingress.o /opt/openziti/bin 46 | cp -p zfw_tunnwrapper /opt/openziti/bin 47 | cp -p ../files/scripts/start_ebpf_tunnel.py /opt/openziti/bin 48 | cp -p ../files/scripts/set_xdp_redirect.py /opt/openziti/bin 49 | cp -p ../files/scripts/user_rules.sh.sample /opt/openziti/bin/user 50 | cp -p ../files/json/ebpf_config.json.sample /opt/openziti/etc 51 | cp -p ../files/services/ziti-wrapper.service /etc/systemd/system 52 | cp -p ../files/services/ziti-fw-init.service /etc/systemd/system 53 | chmod 744 /opt/openziti/bin/start_ebpf_tunnel.py 54 | chmod 744 /opt/openziti/bin/set_xdp_redirect.py 55 | chmod 744 /opt/openziti/bin/user/user_rules.sh.sample 56 | chmod 744 /opt/openziti/bin/zfw_tunnwrapper 57 | chmod 744 /opt/openziti/bin/zfw 58 | 59 | if [ ! -L "/usr/sbin/zfw" ] 60 | then 61 | ln -s /opt/openziti/bin/zfw /usr/sbin/zfw 62 | fi 63 | else 64 | echo "ziti-edge-tunnel not installed!" 65 | exit 1 66 | fi 67 | fi 68 | exit 0 69 | -------------------------------------------------------------------------------- /src/zfw_tc_outbound_track.c: -------------------------------------------------------------------------------- 1 | /* Copyright (C) 2022 Robert Caamano */ 2 | /* 3 | * This program is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | 8 | * This program is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * see . 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #define MAX_IF_ENTRIES 256 33 | #define BPF_MAX_SESSIONS 10000 34 | #define IP_HEADER_TOO_BIG 1 35 | #define NO_IP_OPTIONS_ALLOWED 2 36 | #define IP_TUPLE_TOO_BIG 8 37 | #define EGRESS 1 38 | #define CLIENT_SYN_RCVD 7 39 | #define CLIENT_FIN_RCVD 8 40 | #define CLIENT_RST_RCVD 9 41 | #define TCP_CONNECTION_ESTABLISHED 10 42 | #define CLIENT_FINAL_ACK_RCVD 11 43 | #define CLIENT_INITIATED_UDP_SESSION 12 44 | 45 | 46 | struct bpf_event{ 47 | unsigned long long tstamp; 48 | __u32 ifindex; 49 | __u32 tun_ifindex; 50 | __u32 daddr; 51 | __u32 saddr; 52 | __u16 sport; 53 | __u16 dport; 54 | __u16 tport; 55 | __u8 proto; 56 | __u8 direction; 57 | __u8 error_code; 58 | __u8 tracking_code; 59 | unsigned char source[6]; 60 | unsigned char dest[6]; 61 | }; 62 | 63 | /*Key to tcp_map and udp_map*/ 64 | struct tuple_key { 65 | __u32 daddr; 66 | __u32 saddr; 67 | __u16 sport; 68 | __u16 dport; 69 | }; 70 | 71 | /*Value to tcp_map*/ 72 | struct tcp_state { 73 | unsigned long long tstamp; 74 | __u32 sfseq; 75 | __u32 cfseq; 76 | __u8 syn; 77 | __u8 sfin; 78 | __u8 cfin; 79 | __u8 sfack; 80 | __u8 cfack; 81 | __u8 ack; 82 | __u8 rst; 83 | __u8 est; 84 | }; 85 | 86 | /*Value to udp_map*/ 87 | struct udp_state { 88 | unsigned long long tstamp; 89 | }; 90 | 91 | /*value to diag_map*/ 92 | struct diag_ip4 { 93 | bool echo; 94 | bool verbose; 95 | bool per_interface; 96 | bool ssh_disable; 97 | bool tc_ingress; 98 | bool tc_egress; 99 | bool tun_mode; 100 | bool vrrp; 101 | bool eapol; 102 | }; 103 | 104 | //map to keep status of diagnostic rules 105 | struct { 106 | __uint(type, BPF_MAP_TYPE_HASH); 107 | __uint(key_size, sizeof(uint32_t)); 108 | __uint(value_size, sizeof(struct diag_ip4)); 109 | __uint(max_entries, MAX_IF_ENTRIES); 110 | __uint(pinning, LIBBPF_PIN_BY_NAME); 111 | __uint(map_flags, BPF_F_NO_PREALLOC); 112 | } diag_map SEC(".maps"); 113 | 114 | /*Hashmap to track outbound passthrough TCP connections*/ 115 | struct { 116 | __uint(type, BPF_MAP_TYPE_LRU_HASH); 117 | __uint(key_size, sizeof(struct tuple_key)); 118 | __uint(value_size,sizeof(struct tcp_state)); 119 | __uint(max_entries, BPF_MAX_SESSIONS); 120 | __uint(pinning, LIBBPF_PIN_BY_NAME); 121 | } tcp_map SEC(".maps"); 122 | 123 | /*Hashmap to track outbound passthrough UDP connections*/ 124 | struct { 125 | __uint(type, BPF_MAP_TYPE_LRU_HASH); 126 | __uint(key_size, sizeof(struct tuple_key)); 127 | __uint(value_size,sizeof(struct udp_state)); 128 | __uint(max_entries, BPF_MAX_SESSIONS); 129 | __uint(pinning, LIBBPF_PIN_BY_NAME); 130 | } udp_map SEC(".maps"); 131 | 132 | /*Ringbuf map*/ 133 | struct { 134 | __uint(type, BPF_MAP_TYPE_RINGBUF); 135 | __uint(max_entries, 256 * 1024); 136 | __uint(pinning, LIBBPF_PIN_BY_NAME); 137 | } rb_map SEC(".maps"); 138 | 139 | /*Insert entry into tcp state table*/ 140 | static inline void insert_tcp(struct tcp_state tstate, struct tuple_key key){ 141 | bpf_map_update_elem(&tcp_map, &key, &tstate,0); 142 | } 143 | 144 | /*Remove entry into tcp state table*/ 145 | static inline void del_tcp(struct tuple_key key){ 146 | bpf_map_delete_elem(&tcp_map, &key); 147 | } 148 | 149 | /*get entry from tcp state table*/ 150 | static inline struct tcp_state *get_tcp(struct tuple_key key){ 151 | struct tcp_state *ts; 152 | ts = bpf_map_lookup_elem(&tcp_map, &key); 153 | return ts; 154 | } 155 | 156 | /*Insert entry into udp state table*/ 157 | static inline void insert_udp(struct udp_state ustate, struct tuple_key key){ 158 | bpf_map_update_elem(&udp_map, &key, &ustate,0); 159 | } 160 | 161 | /*get entry from udp state table*/ 162 | static inline struct udp_state *get_udp(struct tuple_key key){ 163 | struct udp_state *us; 164 | us = bpf_map_lookup_elem(&udp_map, &key); 165 | return us; 166 | } 167 | 168 | static inline struct diag_ip4 *get_diag_ip4(__u32 key){ 169 | struct diag_ip4 *if_diag; 170 | if_diag = bpf_map_lookup_elem(&diag_map, &key); 171 | 172 | return if_diag; 173 | } 174 | 175 | static inline void send_event(struct bpf_event *new_event){ 176 | struct bpf_event *rb_event; 177 | rb_event = bpf_ringbuf_reserve(&rb_map, sizeof(*rb_event), 0); 178 | if(rb_event){ 179 | rb_event->ifindex = new_event->ifindex; 180 | rb_event->tun_ifindex = new_event->tun_ifindex; 181 | rb_event->tstamp = new_event->tstamp; 182 | //rb_event->tstamp = bpf_ktime_get_ns(); 183 | rb_event->daddr = new_event->daddr; 184 | rb_event->saddr = new_event->saddr; 185 | rb_event->dport = new_event->dport; 186 | rb_event->sport = new_event->sport; 187 | rb_event->tport = new_event->tport; 188 | rb_event->proto = new_event->proto; 189 | rb_event->direction = new_event->direction; 190 | rb_event->tracking_code = new_event->tracking_code; 191 | rb_event->error_code = new_event->error_code; 192 | bpf_ringbuf_submit(rb_event, 0); 193 | } 194 | } 195 | 196 | /* function to determine if an incoming packet is a udp/tcp IP tuple 197 | * or not. If not returns NULL. If true returns a struct bpf_sock_tuple 198 | * from the combined IP SA|DA and the TCP/UDP SP|DP. 199 | */ 200 | static struct bpf_sock_tuple *get_tuple(struct __sk_buff *skb, __u64 nh_off, 201 | __u16 eth_proto, bool *ipv4, bool *ipv6, bool *udp, bool *tcp, bool *arp, bool *icmp, struct bpf_event *event,struct diag_ip4 *local_diag){ 202 | struct bpf_sock_tuple *result; 203 | __u8 proto = 0; 204 | 205 | /* check if ARP */ 206 | if (eth_proto == bpf_htons(ETH_P_ARP)) { 207 | *arp = true; 208 | return NULL; 209 | } 210 | 211 | /* check if IPv6 */ 212 | if (eth_proto == bpf_htons(ETH_P_IPV6)) { 213 | *ipv6 = true; 214 | return NULL; 215 | } 216 | 217 | /* check IPv4 */ 218 | if (eth_proto == bpf_htons(ETH_P_IP)) { 219 | *ipv4 = true; 220 | 221 | /* find ip hdr */ 222 | struct iphdr *iph = (struct iphdr *)(skb->data + nh_off); 223 | 224 | /* ensure ip header is in packet bounds */ 225 | if ((unsigned long)(iph + 1) > (unsigned long)skb->data_end){ 226 | if(local_diag->verbose){ 227 | event->error_code = IP_HEADER_TOO_BIG; 228 | send_event(event); 229 | } 230 | return NULL; 231 | } 232 | /* ip options not allowed */ 233 | if (iph->ihl != 5){ 234 | if(local_diag->verbose){ 235 | event->error_code = NO_IP_OPTIONS_ALLOWED; 236 | send_event(event); 237 | } 238 | return NULL; 239 | } 240 | /* get ip protocol type */ 241 | proto = iph->protocol; 242 | /* check if ip protocol is UDP */ 243 | if (proto == IPPROTO_UDP) { 244 | *udp = true; 245 | } 246 | /* check if ip protocol is TCP */ 247 | if (proto == IPPROTO_TCP) { 248 | *tcp = true; 249 | } 250 | if(proto == IPPROTO_ICMP){ 251 | *icmp = true; 252 | return NULL; 253 | } 254 | /* check if ip protocol is not UDP or TCP. Return NULL if true */ 255 | if ((proto != IPPROTO_UDP) && (proto != IPPROTO_TCP)) { 256 | return NULL; 257 | } 258 | /*return bpf_sock_tuple*/ 259 | result = (struct bpf_sock_tuple *)(void*)(long)&iph->saddr; 260 | } else { 261 | return NULL; 262 | } 263 | return result; 264 | } 265 | 266 | //ebpf tc code entry program 267 | SEC("action") 268 | int bpf_sk_splice(struct __sk_buff *skb){ 269 | struct bpf_sock *sk; 270 | struct bpf_sock_tuple *tuple, reverse_tuple = {0}; 271 | int tuple_len; 272 | bool ipv4 = false; 273 | bool ipv6 = false; 274 | bool udp=false; 275 | bool tcp=false; 276 | bool arp=false; 277 | bool icmp=false; 278 | struct tuple_key tcp_state_key; 279 | struct tuple_key udp_state_key; 280 | 281 | unsigned long long tstamp = bpf_ktime_get_ns(); 282 | struct bpf_event event = { 283 | tstamp, 284 | skb->ifindex, 285 | 0, 286 | 0, 287 | 0, 288 | 0, 289 | 0, 290 | 0, 291 | 0, 292 | EGRESS, 293 | 0, 294 | 0, 295 | {0}, 296 | {0} 297 | }; 298 | 299 | /*look up attached interface inbound diag status*/ 300 | struct diag_ip4 *local_diag = get_diag_ip4(skb->ifindex); 301 | if(!local_diag){ 302 | return TC_ACT_OK; 303 | } 304 | 305 | /* find ethernet header from skb->data pointer */ 306 | struct ethhdr *eth = (struct ethhdr *)(unsigned long)(skb->data); 307 | /* verify its a valid eth header within the packet bounds */ 308 | if ((unsigned long)(eth + 1) > (unsigned long)skb->data_end){ 309 | return TC_ACT_SHOT; 310 | } 311 | 312 | /* check if incoming packet is a UDP or TCP tuple */ 313 | tuple = get_tuple(skb, sizeof(*eth), eth->h_proto, &ipv4,&ipv6, &udp, &tcp, &arp, &icmp, &event, local_diag); 314 | 315 | /* if not tuple forward */ 316 | if (!tuple){ 317 | return TC_ACT_OK; 318 | } 319 | 320 | /* determine length of tuple */ 321 | tuple_len = sizeof(tuple->ipv4); 322 | if ((unsigned long)tuple + tuple_len > (unsigned long)skb->data_end){ 323 | return TC_ACT_SHOT; 324 | } 325 | event.saddr = tuple->ipv4.saddr; 326 | event.daddr = tuple->ipv4.daddr; 327 | event.sport = tuple->ipv4.sport; 328 | event.dport = tuple->ipv4.dport; 329 | 330 | /* if tcp based tuple implement stateful inspection to see if they were 331 | * initiated by the local OS if not then its passthrough traffic and so wee need to 332 | * setup our own state to track the outbound pass through connections in via shared hashmap 333 | * with with ingress tc program*/ 334 | if(tcp){ 335 | event.proto = IPPROTO_TCP; 336 | struct iphdr *iph = (struct iphdr *)(skb->data + sizeof(*eth)); 337 | if ((unsigned long)(iph + 1) > (unsigned long)skb->data_end){ 338 | return TC_ACT_SHOT; 339 | } 340 | struct tcphdr *tcph = (struct tcphdr *)((unsigned long)iph + sizeof(*iph)); 341 | if ((unsigned long)(tcph + 1) > (unsigned long)skb->data_end){ 342 | return TC_ACT_SHOT; 343 | } 344 | reverse_tuple.ipv4.daddr = tuple->ipv4.saddr; 345 | reverse_tuple.ipv4.dport = tuple->ipv4.sport; 346 | reverse_tuple.ipv4.saddr = tuple->ipv4.daddr; 347 | reverse_tuple.ipv4.sport = tuple->ipv4.dport; 348 | sk = bpf_skc_lookup_tcp(skb, &reverse_tuple, sizeof(reverse_tuple.ipv4),BPF_F_CURRENT_NETNS, 0); 349 | if(sk){ 350 | if (sk->state != BPF_TCP_LISTEN){ 351 | bpf_sk_release(sk); 352 | if(local_diag->verbose){ 353 | send_event(&event); 354 | } 355 | return TC_ACT_OK; 356 | } 357 | bpf_sk_release(sk); 358 | } 359 | tcp_state_key.daddr = tuple->ipv4.daddr; 360 | tcp_state_key.saddr = tuple->ipv4.saddr; 361 | tcp_state_key.sport = tuple->ipv4.sport; 362 | tcp_state_key.dport = tuple->ipv4.dport; 363 | unsigned long long tstamp = bpf_ktime_get_ns(); 364 | struct tcp_state *tstate; 365 | if(tcph->syn && !tcph->ack){ 366 | struct tcp_state ts = { 367 | tstamp, 368 | 0, 369 | 0, 370 | 1, 371 | 0, 372 | 0, 373 | 0, 374 | 0, 375 | 0, 376 | 0, 377 | 0 378 | }; 379 | insert_tcp(ts, tcp_state_key); 380 | if(local_diag->verbose){ 381 | event.tracking_code = CLIENT_SYN_RCVD; 382 | send_event(&event); 383 | } 384 | } 385 | else if(tcph->fin){ 386 | tstate = get_tcp(tcp_state_key); 387 | if(tstate){ 388 | tstate->tstamp = tstamp; 389 | tstate->cfin = 1; 390 | tstate->cfseq = tcph->seq; 391 | if(local_diag->verbose){ 392 | event.tracking_code = CLIENT_FIN_RCVD; 393 | send_event(&event); 394 | } 395 | } 396 | } 397 | else if(tcph->rst){ 398 | tstate = get_tcp(tcp_state_key); 399 | if(tstate){ 400 | del_tcp(tcp_state_key); 401 | tstate = get_tcp(tcp_state_key); 402 | if(!tstate){ 403 | if(local_diag->verbose){ 404 | event.tracking_code = CLIENT_RST_RCVD; 405 | send_event(&event); 406 | } 407 | } 408 | } 409 | } 410 | else if(tcph->ack){ 411 | tstate = get_tcp(tcp_state_key); 412 | if(tstate){ 413 | if(tstate->ack && tstate->syn){ 414 | if(local_diag->verbose){ 415 | event.tracking_code = TCP_CONNECTION_ESTABLISHED; 416 | send_event(&event); 417 | } 418 | tstate->tstamp = tstamp; 419 | tstate->syn = 0; 420 | tstate->est = 1; 421 | } 422 | if((tstate->est) && (tstate->sfin == 1) && (tstate->cfin == 1) && (tstate->sfack) && (bpf_htonl(tcph->ack_seq) == (bpf_htonl(tstate->sfseq) + 1))){ 423 | del_tcp(tcp_state_key); 424 | tstate = get_tcp(tcp_state_key); 425 | if(!tstate){ 426 | if(local_diag->verbose){ 427 | event.tracking_code = CLIENT_FINAL_ACK_RCVD; 428 | send_event(&event); 429 | } 430 | } 431 | } 432 | else if((tstate->est) && (tstate->sfin == 1) && (bpf_htonl(tcph->ack_seq) == (bpf_htonl(tstate->sfseq) + 1))){ 433 | tstate->cfack = 1; 434 | tstate->tstamp = tstamp; 435 | } 436 | else{ 437 | tstate->tstamp = tstamp; 438 | } 439 | } 440 | } 441 | }else{ 442 | /* if udp based tuple implement stateful inspection to see if they were 443 | * initiated by the local OS if not then its passthrough traffic and so wee need to 444 | * setup our own state to track the outbound pass through connections in via shared hashmap 445 | * with with ingress tc program */ 446 | event.proto = IPPROTO_UDP; 447 | struct iphdr *iph = (struct iphdr *)(skb->data + sizeof(*eth)); 448 | if ((unsigned long)(iph + 1) > (unsigned long)skb->data_end){ 449 | return TC_ACT_SHOT; 450 | } 451 | struct udphdr *udph = (struct udphdr *)((unsigned long)iph + sizeof(*iph)); 452 | if ((unsigned long)(udph + 1) > (unsigned long)skb->data_end){ 453 | return TC_ACT_SHOT; 454 | } 455 | if ((unsigned long)tuple + tuple_len > (unsigned long)skb->data_end){ 456 | return TC_ACT_SHOT; 457 | } 458 | reverse_tuple.ipv4.daddr = tuple->ipv4.saddr; 459 | reverse_tuple.ipv4.dport = tuple->ipv4.sport; 460 | reverse_tuple.ipv4.saddr = tuple->ipv4.daddr; 461 | reverse_tuple.ipv4.sport = tuple->ipv4.dport; 462 | unsigned long long tstamp = bpf_ktime_get_ns(); 463 | sk = bpf_sk_lookup_udp(skb, &reverse_tuple, sizeof(reverse_tuple.ipv4), BPF_F_CURRENT_NETNS, 0); 464 | if(sk){ 465 | bpf_sk_release(sk); 466 | }else{ 467 | udp_state_key.daddr = tuple->ipv4.daddr; 468 | udp_state_key.saddr = tuple->ipv4.saddr; 469 | udp_state_key.sport = tuple->ipv4.sport; 470 | udp_state_key.dport = tuple->ipv4.dport; 471 | struct udp_state *ustate = get_udp(udp_state_key); 472 | if((!ustate) || (ustate->tstamp > (tstamp + 30000000000))){ 473 | struct udp_state us = { 474 | tstamp 475 | }; 476 | insert_udp(us, udp_state_key); 477 | if(local_diag->verbose){ 478 | event.tracking_code = CLIENT_INITIATED_UDP_SESSION; 479 | send_event(&event); 480 | } 481 | } 482 | else if(ustate){ 483 | ustate->tstamp = tstamp; 484 | } 485 | } 486 | } 487 | return TC_ACT_OK; 488 | } 489 | SEC("license") const char __license[] = "Dual BSD/GPL"; 490 | -------------------------------------------------------------------------------- /src/zfw_tunnel_wrapper.c: -------------------------------------------------------------------------------- 1 | /* Copyright (C) 2022 Robert Caamano */ 2 | /* 3 | * This program is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | 8 | * This program is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * see . 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | #ifndef BPF_MAX_ENTRIES 36 | #define BPF_MAX_ENTRIES 100 //MAX # PREFIXES 37 | #endif 38 | #define MAX_LINE_LENGTH 32766 39 | #define BUFFER_SIZE 512 40 | #define EVENT_BUFFER_SIZE 32768 41 | #define SERVICE_ID_BYTES 32 42 | #define MAX_TRANSP_ROUTES 256 43 | #define SOCK_NAME "/tmp/ziti-edge-tunnel.sock" 44 | #define EVENT_SOCK_NAME "/tmp/ziti-edge-tunnel-event.sock" 45 | #define DUMP_FILE "/tmp/dumpfile.ziti" 46 | const char *transp_map_path = "/sys/fs/bpf/tc/globals/zet_transp_map"; 47 | const char *if_tun_map_path = "/sys/fs/bpf/tc/globals/ifindex_tun_map"; 48 | int ctrl_socket, event_socket; 49 | char tunip_string[16]=""; 50 | char tunip_mask_string[10]=""; 51 | char *tun_ifname; 52 | bool transparent; 53 | union bpf_attr transp_map; 54 | int transp_fd = -1; 55 | union bpf_attr tun_map; 56 | int tun_fd = -1; 57 | typedef unsigned char byte; 58 | void close_maps(int code); 59 | void open_transp_map(); 60 | void open_tun_map(); 61 | void zfw_update(char *ip, char *mask, char *lowport, char *highport, char *protocol, char *action); 62 | void unbind_route_loopback(struct in_addr *address, unsigned short mask); 63 | void INThandler(int sig); 64 | void map_delete_key(char *service_id); 65 | void route_flush(); 66 | int process_bind(json_object *jobj, char *action); 67 | int process_routes(char *service_id); 68 | 69 | /*convert integer ip to dotted decimal string*/ 70 | char *nitoa(uint32_t address) 71 | { 72 | char *ipaddr = malloc(16); 73 | int b0 = (address & 0xff000000) >> 24; 74 | int b1 = (address & 0xff0000) >> 16; 75 | int b2 = (address & 0xff00) >> 8; 76 | int b3 = address & 0xff; 77 | sprintf(ipaddr, "%d.%d.%d.%d", b0, b1, b2, b3); 78 | return ipaddr; 79 | } 80 | 81 | /*key to transp_map*/ 82 | struct transp_key { 83 | char service_id[SERVICE_ID_BYTES]; 84 | }; 85 | 86 | struct transp_entry { 87 | struct in_addr saddr; 88 | __u16 prefix_len; 89 | }; 90 | 91 | /*Value to transp_map*/ 92 | struct transp_value{ 93 | struct transp_entry tentry[MAX_TRANSP_ROUTES]; 94 | __u8 count; 95 | }; 96 | 97 | /*value to ifindex_tun_map*/ 98 | struct ifindex_tun { 99 | uint32_t index; 100 | char ifname[IFNAMSIZ]; 101 | char cidr[16]; 102 | char mask[3]; 103 | bool verbose; 104 | }; 105 | 106 | void INThandler(int sig){ 107 | signal(sig, SIG_IGN); 108 | route_flush(); 109 | close_maps(1); 110 | } 111 | 112 | void close_maps(int code){ 113 | if(event_socket != -1){ 114 | close(event_socket); 115 | } 116 | if(event_socket != -1){ 117 | close(ctrl_socket); 118 | } 119 | if(transp_fd != -1){ 120 | close(transp_fd); 121 | } 122 | if(tun_fd != -1){ 123 | close(tun_fd); 124 | } 125 | exit(code); 126 | } 127 | 128 | void route_flush() 129 | { 130 | struct transp_key init_key = {{0}}; 131 | struct transp_key *key = &init_key; 132 | struct transp_value o_routes; 133 | struct transp_key current_key; 134 | transp_map.key = (uint64_t)&key; 135 | transp_map.value = (uint64_t)&o_routes; 136 | transp_map.map_fd = transp_fd; 137 | transp_map.flags = BPF_ANY; 138 | int ret = 0; 139 | while (true) 140 | { 141 | ret = syscall(__NR_bpf, BPF_MAP_GET_NEXT_KEY, &transp_map, sizeof(transp_map)); 142 | if (ret == -1) 143 | { 144 | break; 145 | } 146 | transp_map.key = transp_map.next_key; 147 | current_key = *(struct transp_key *)transp_map.key; 148 | //map_delete_key(current_key.service_id); 149 | process_routes(current_key.service_id); 150 | } 151 | } 152 | 153 | int process_routes(char *service_id){ 154 | struct transp_key key = {{0}}; 155 | sprintf(key.service_id, "%s", service_id); 156 | struct transp_value o_routes; 157 | transp_map.key = (uint64_t)&key; 158 | transp_map.value = (uint64_t)&o_routes; 159 | transp_map.map_fd = transp_fd; 160 | transp_map.flags = BPF_ANY; 161 | int lookup = syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &transp_map, sizeof(transp_map)); 162 | bool changed = false; 163 | if (!lookup) 164 | { 165 | for(int x = 0; x <= o_routes.count; x++){ 166 | unbind_route_loopback(&o_routes.tentry[x].saddr, o_routes.tentry[x].prefix_len); 167 | } 168 | map_delete_key(service_id); 169 | } 170 | return 0; 171 | } 172 | 173 | 174 | void ebpf_usage() 175 | { 176 | if (access(transp_map_path, F_OK) != 0) 177 | { 178 | printf("Not enough privileges or ebpf not enabled!\n"); 179 | printf("Run as \"sudo\" with ingress tc filter [filter -X, --set-tc-filter] set on at least one interface\n"); 180 | close_maps(1); 181 | } 182 | } 183 | 184 | void open_transp_map(){ 185 | memset(&transp_map, 0, sizeof(transp_map)); 186 | /* set path name with location of map in filesystem */ 187 | transp_map.pathname = (uint64_t)transp_map_path; 188 | transp_map.bpf_fd = 0; 189 | transp_map.file_flags = 0; 190 | /* make system call to get fd for map */ 191 | transp_fd = syscall(__NR_bpf, BPF_OBJ_GET, &transp_map, sizeof(transp_map)); 192 | if (transp_fd == -1) 193 | { 194 | ebpf_usage(); 195 | } 196 | } 197 | 198 | void open_tun_map(){ 199 | memset(&tun_map, 0, sizeof(tun_map)); 200 | tun_map.pathname = (uint64_t)if_tun_map_path; 201 | tun_map.bpf_fd = 0; 202 | tun_map.file_flags = 0; 203 | /* make system call to get fd for map */ 204 | tun_fd = syscall(__NR_bpf, BPF_OBJ_GET, &tun_map, sizeof(tun_map)); 205 | if (tun_fd == -1) 206 | { 207 | printf("BPF_OBJ_GET: tun_if_map %s \n", strerror(errno)); 208 | close_maps(1); 209 | } 210 | } 211 | 212 | 213 | 214 | void map_delete_key(char *service_id) 215 | { 216 | union bpf_attr map; 217 | memset(&map, 0, sizeof(map)); 218 | struct transp_key key = {{0}}; 219 | sprintf(key.service_id, "%s", service_id); 220 | map.pathname = (uint64_t)transp_map_path; 221 | map.bpf_fd = 0; 222 | int fd = syscall(__NR_bpf, BPF_OBJ_GET, &map, sizeof(map)); 223 | if (fd == -1) 224 | { 225 | printf("BPF_OBJ_GET: %s\n", strerror(errno)); 226 | } 227 | // delete element with specified key 228 | map.map_fd = fd; 229 | map.key = (uint64_t)&key; 230 | int result = syscall(__NR_bpf, BPF_MAP_DELETE_ELEM, &map, sizeof(map)); 231 | if (result) 232 | { 233 | printf("MAP_DELETE_ELEM: %s\n", strerror(errno)); 234 | } 235 | else 236 | { 237 | printf("service id: %s removed from trans_map\n", service_id); 238 | } 239 | close(fd); 240 | } 241 | 242 | __u16 len2u16(char *len) 243 | { 244 | char *endPtr; 245 | int32_t tmpint = strtol(len, &endPtr, 10); 246 | if ((tmpint < 0) || (tmpint > 32) || (!(*(endPtr) == '\0'))) 247 | { 248 | printf("Invalid Prefix Length: %s\n", len); 249 | exit(1); 250 | } 251 | __u16 u16int = (__u16)tmpint; 252 | return u16int; 253 | } 254 | 255 | void bind_route(struct in_addr *address, unsigned short mask) 256 | { 257 | char *prefix = inet_ntoa(*address); 258 | char *cidr_block = malloc(19); 259 | sprintf(cidr_block, "%s/%u", prefix, mask); 260 | printf("binding local ip route to %s via loopback\n", cidr_block); 261 | pid_t pid; 262 | char *const parmList[] = {"/usr/sbin/ip", "route", "add", "local", cidr_block, "dev", "lo", NULL}; 263 | if ((pid = fork()) == -1) 264 | { 265 | perror("fork error: can't spawn bind"); 266 | } 267 | else if (pid == 0) 268 | { 269 | execv("/usr/sbin/ip", parmList); 270 | printf("execv error: unknown error binding route"); 271 | } 272 | free(cidr_block); 273 | } 274 | 275 | void unbind_route_loopback(struct in_addr *address, unsigned short mask) 276 | { 277 | char *prefix = inet_ntoa(*address); 278 | char *cidr_block = malloc(19); 279 | sprintf(cidr_block, "%s/%u", prefix, mask); 280 | printf("unbinding route to %s via dev %s\n", cidr_block, "lo"); 281 | pid_t pid; 282 | char *const parmList[] = {"/usr/sbin/ip", "route", "del", "local", cidr_block, "dev", "lo", NULL}; 283 | if ((pid = fork()) == -1) 284 | { 285 | perror("fork error: can't spawn unbind"); 286 | } 287 | else if (pid == 0) 288 | { 289 | execv("/usr/sbin/ip", parmList); 290 | printf("execv error: unknown error unbinding route"); 291 | } 292 | free(cidr_block); 293 | } 294 | 295 | void unbind_route(struct in_addr *address, unsigned short mask, char *dev) 296 | { 297 | char *prefix = inet_ntoa(*address); 298 | char *cidr_block = malloc(19); 299 | sprintf(cidr_block, "%s/%u", prefix, mask); 300 | printf("unbinding route to %s via dev %s\n", cidr_block, dev); 301 | pid_t pid; 302 | char *const parmList[] = {"/usr/sbin/ip", "route", "del", cidr_block, "dev", dev, NULL}; 303 | if ((pid = fork()) == -1) 304 | { 305 | perror("fork error: can't spawn unbind"); 306 | } 307 | else if (pid == 0) 308 | { 309 | execv("/usr/sbin/ip", parmList); 310 | printf("execv error: unknown error unbinding route"); 311 | } 312 | free(cidr_block); 313 | } 314 | 315 | void setpath(char *dirname, char *filename, char * slink) 316 | { 317 | char buf[PATH_MAX + 1]; 318 | DIR *directory; 319 | struct dirent *file; 320 | struct stat statbuf; 321 | if((directory = opendir(dirname)) == NULL) { 322 | fprintf(stderr,"cannot open directory: %s\n", dirname); 323 | return; 324 | } 325 | chdir(dirname); 326 | while((file = readdir(directory)) != NULL) { 327 | lstat(file->d_name,&statbuf); 328 | if(S_ISDIR(statbuf.st_mode)) { 329 | if(strcmp(".",file->d_name) == 0 || strcmp("..",file->d_name) == 0){ 330 | continue; 331 | } 332 | setpath(file->d_name, filename, slink); 333 | }else if((strcmp(filename,file->d_name) == 0)){ 334 | realpath(file->d_name,buf); 335 | //printf("buf=%s\n",buf); 336 | if(strstr((char *)buf, "/.ziti/")){ 337 | unlink(slink); 338 | symlink(buf,slink); 339 | } 340 | } 341 | } 342 | chdir(".."); 343 | closedir(directory); 344 | } 345 | 346 | 347 | void string2Byte(char* string, byte* bytes) 348 | { 349 | int si; 350 | int bi; 351 | 352 | si = 0; 353 | bi = 0; 354 | 355 | while(string[si] != '\0') 356 | { 357 | bytes[bi++] = string[si++]; 358 | } 359 | } 360 | 361 | void zfw_update(char *ip, char *mask, char *lowport, char *highport, char *protocol, char *action){ 362 | if (access("/usr/sbin/zfw", F_OK) != 0) 363 | { 364 | printf("ebpf not running: Cannot find /usr/sbin/zfw\n"); 365 | return; 366 | } 367 | pid_t pid; 368 | //("%s, %s\n", action ,rules_temp->parmList[3]); 369 | char *const parmList[15] = {"/usr/sbin/zfw", action, "-c", ip, "-m", mask, "-l", 370 | lowport, "-h", highport, "-t", "65535", "-p", protocol, NULL}; 371 | if ((pid = fork()) == -1){ 372 | perror("fork error: can't spawn bind"); 373 | }else if (pid == 0) { 374 | execv("/usr/sbin/zfw", parmList); 375 | printf("execv error: unknown error binding\n"); 376 | }else{ 377 | int status =0; 378 | if(!(waitpid(pid, &status, 0) > 0)){ 379 | if(WIFEXITED(status) && !WEXITSTATUS(status)){ 380 | printf("zfw %s action for : %s not set\n", action, ip); 381 | } 382 | } 383 | } 384 | } 385 | 386 | int process_bind(json_object *jobj, char *action) 387 | { 388 | if (transp_fd == -1) 389 | { 390 | open_transp_map(); 391 | } 392 | char service_id[32]; 393 | struct json_object *id_obj = json_object_object_get(jobj, "Id"); 394 | if(id_obj) 395 | { 396 | if((strlen(json_object_get_string(id_obj)) + 1 ) <= 32) 397 | { 398 | sprintf(service_id, "%s", json_object_get_string(id_obj)); 399 | struct json_object *addresses_obj = json_object_object_get(jobj, "Addresses"); 400 | if(addresses_obj && !strcmp(action,"-I")) 401 | { 402 | int addresses_obj_len = json_object_array_length(addresses_obj); 403 | // enum json_type type; 404 | struct json_object *allowedSourceAddresses = json_object_object_get(jobj, "AllowedSourceAddresses"); 405 | if (allowedSourceAddresses) 406 | { 407 | int allowedSourceAddresses_len = json_object_array_length(allowedSourceAddresses); 408 | printf("allowedSourceAddresses key exists: binding addresses to loopback\n"); 409 | int j; 410 | for (j = 0; j < allowedSourceAddresses_len; j++) 411 | { 412 | struct json_object *address_obj = json_object_array_get_idx(allowedSourceAddresses, j); 413 | if (address_obj) 414 | { 415 | struct json_object *host_obj = json_object_object_get(address_obj, "IsHost"); 416 | if(host_obj){ 417 | bool is_host = json_object_get_boolean(host_obj); 418 | char ip[16]; 419 | char mask[10]; 420 | if(is_host) 421 | { 422 | printf("Invalid: Hostnames not supported for AllowedSourceAddress\n"); 423 | }else 424 | { 425 | struct json_object *ip_obj = json_object_object_get(address_obj, "IP"); 426 | printf("\n\nIP intercept:\n"); 427 | if(ip_obj) 428 | { 429 | struct json_object *prefix_obj = json_object_object_get(address_obj, "Prefix"); 430 | if(prefix_obj){ 431 | char ip[strlen(json_object_get_string(ip_obj) + 1)]; 432 | sprintf(ip,"%s", json_object_get_string(ip_obj)); 433 | int smask = sprintf(mask, "%d", json_object_get_int(prefix_obj)); 434 | printf("Service_IP=%s\n", ip); 435 | struct in_addr tuncidr; 436 | if (inet_aton(ip, &tuncidr)){ 437 | bind_route(&tuncidr, len2u16(mask)); 438 | if (j < MAX_TRANSP_ROUTES) 439 | { 440 | struct transp_key key = {{0}}; 441 | sprintf(key.service_id, "%s", service_id); 442 | struct transp_value o_routes; 443 | transp_map.key = (uint64_t)&key; 444 | transp_map.value = (uint64_t)&o_routes; 445 | transp_map.map_fd = transp_fd; 446 | transp_map.flags = BPF_ANY; 447 | int lookup = syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &transp_map, sizeof(transp_map)); 448 | bool changed = false; 449 | if (lookup) 450 | { 451 | o_routes.tentry[j].saddr = tuncidr; 452 | o_routes.tentry[j].prefix_len = len2u16(mask); 453 | o_routes.count = j; 454 | int result = syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &transp_map, sizeof(transp_map)); 455 | if (result) 456 | { 457 | printf("MAP_UPDATE_ELEM: %s \n", strerror(errno)); 458 | } 459 | } 460 | else 461 | { 462 | o_routes.tentry[j].saddr = tuncidr; 463 | o_routes.tentry[j].prefix_len = len2u16(mask); 464 | o_routes.count = j; 465 | int result = syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &transp_map, sizeof(transp_map)); 466 | if (result) 467 | { 468 | printf("MAP_UPDATE_ELEM: %s \n", strerror(errno)); 469 | } 470 | } 471 | 472 | } 473 | else 474 | { 475 | printf("Can't store more than %d transparency routes per service\n", MAX_TRANSP_ROUTES); 476 | } 477 | } 478 | } 479 | } 480 | } 481 | } 482 | } 483 | } 484 | } 485 | }else{ 486 | process_routes(service_id); 487 | } 488 | } 489 | } 490 | return 0; 491 | } 492 | 493 | int process_dial(json_object *jobj, char *action){ 494 | struct json_object *addresses_obj = json_object_object_get(jobj, "Addresses"); 495 | if(addresses_obj) 496 | { 497 | int addresses_obj_len = json_object_array_length(addresses_obj); 498 | //printf("There are %d addresses\n", addresses_len); 499 | struct json_object *ports_obj = json_object_object_get(jobj, "Ports"); 500 | if(ports_obj){ 501 | int ports_obj_len = json_object_array_length(ports_obj); 502 | //printf("There are %d portRanges\n", portRanges_len); 503 | struct json_object *protocols_obj = json_object_object_get(jobj, "Protocols"); 504 | if(protocols_obj){ 505 | int protocols_obj_len = json_object_array_length(protocols_obj); 506 | //printf("There are %d protocols\n", protocols_len); 507 | int i; 508 | int j; 509 | int k; 510 | for(i=0; i < protocols_obj_len ; i++){ 511 | struct json_object *protocol_obj = json_object_array_get_idx(protocols_obj, i); 512 | if(protocol_obj){ 513 | for(j=0; j < addresses_obj_len ; j++){ 514 | char protocol[4]; 515 | sprintf(protocol, "%s", json_object_get_string(protocol_obj)); 516 | struct json_object *address_obj = json_object_array_get_idx(addresses_obj, j); 517 | if(address_obj){ 518 | //printf("Add: %s\n",json_object_get_string(addressobj)); 519 | for(k=0; k < ports_obj_len ; k++){ 520 | struct json_object *port_obj = json_object_array_get_idx(ports_obj, k); 521 | if(port_obj){ 522 | struct json_object *range_low_obj = json_object_object_get(port_obj, "Low"); 523 | struct json_object *range_high_obj = json_object_object_get(port_obj, "High"); 524 | char lowport[7]; 525 | char highport[7]; 526 | sprintf(lowport,"%d", json_object_get_int(range_low_obj)); 527 | sprintf(highport,"%d", json_object_get_int(range_high_obj)); 528 | struct json_object *host_obj = json_object_object_get(address_obj, "IsHost"); 529 | if(host_obj){ 530 | bool is_host = json_object_get_boolean(host_obj); 531 | char ip[16]; 532 | char mask[10]; 533 | if(is_host) 534 | { 535 | struct json_object *hostname_obj = json_object_object_get(address_obj, "HostName"); 536 | printf("\n\nHost intercept: Skipping ebpf\n"); 537 | if(hostname_obj){ 538 | char hostname[strlen(json_object_get_string(address_obj)) + 1]; 539 | sprintf(hostname, "%s", json_object_get_string(hostname_obj)); 540 | if(!strcmp("-I", action)){ 541 | struct addrinfo hints_1, *res_1; 542 | memset(&hints_1, '\0', sizeof(hints_1)); 543 | 544 | int err = getaddrinfo( hostname, lowport, &hints_1, &res_1); 545 | if(err){ 546 | printf("Unable to resolve: %s\n", hostname); 547 | continue; 548 | } 549 | 550 | inet_ntop(AF_INET, &res_1->ai_addr->sa_data[2], ip, sizeof(ip)); 551 | printf("Hostname=%s\n", hostname); 552 | printf ("Resolved_IP=%s\n", ip); 553 | printf("Protocol=%s\n", protocol); 554 | printf("Low=%s\n", lowport); 555 | printf("High=%s\n\n", highport); 556 | 557 | /*if(strlen(ip) > 7 && strlen(ip) < 16){ 558 | zfw_update(ip, mask, lowport, highport, protocol, action); 559 | }*/ 560 | }else{ 561 | printf("Hostname=%s\n", hostname); 562 | printf("Can't Resolve on Delete Service since resolver is removed\n\n"); 563 | } 564 | 565 | } 566 | } 567 | else{ 568 | struct json_object *ip_obj = json_object_object_get(address_obj, "IP"); 569 | printf("\n\nIP intercept:\n"); 570 | if(ip_obj) 571 | { 572 | struct json_object *prefix_obj = json_object_object_get(address_obj, "Prefix"); 573 | char ip[strlen(json_object_get_string(ip_obj) + 1)]; 574 | sprintf(ip,"%s", json_object_get_string(ip_obj)); 575 | int smask = sprintf(mask, "%d", json_object_get_int(prefix_obj)); 576 | printf("Service_IP=%s\n", ip); 577 | printf("Protocol=%s\n", protocol); 578 | printf("Low=%s\n", lowport); 579 | printf("high=%s\n\n", highport); 580 | struct in_addr tuncidr; 581 | char *transp_mode = "TRANSPARENT_MODE"; 582 | char *mode = getenv(transp_mode); 583 | if(mode){ 584 | if(!strcmp(mode,"true")){ 585 | if (inet_aton(ip, &tuncidr) && tun_ifname){ 586 | unbind_route(&tuncidr, len2u16(mask), tun_ifname); 587 | } 588 | } 589 | } 590 | zfw_update(ip, mask, lowport, highport, protocol, action); 591 | } 592 | } 593 | } 594 | } 595 | } 596 | } 597 | } 598 | } 599 | } 600 | } 601 | } 602 | } 603 | return 0; 604 | } 605 | 606 | void enumerate_service(struct json_object *services_obj, char *action){ 607 | int services_obj_len = json_object_array_length(services_obj); 608 | for(int s = 0; s < services_obj_len; s++){ 609 | struct json_object *service_obj = json_object_array_get_idx(services_obj, s); 610 | struct json_object *service_id_obj = json_object_object_get(service_obj, "Id"); 611 | char service_id[strlen(json_object_get_string(service_id_obj)) + 1]; 612 | sprintf(service_id, "%s", json_object_get_string(service_id_obj)); 613 | printf("\n\n###########################################\n"); 614 | printf("Service Id=%s\n", service_id); 615 | struct json_object *service_permissions_obj = json_object_object_get(service_obj, "Permissions"); 616 | if(service_permissions_obj){ 617 | struct json_object *service_bind_obj = json_object_object_get(service_permissions_obj, "Bind"); 618 | struct json_object *service_dial_obj = json_object_object_get(service_permissions_obj, "Dial"); 619 | bool dial = json_object_get_boolean(service_dial_obj); 620 | bool bind = json_object_get_boolean(service_bind_obj); 621 | if(dial){ 622 | printf("Service policy is Dial\n"); 623 | process_dial(service_obj, action); 624 | } 625 | if(bind){ 626 | if(transp_fd == -1){ 627 | open_transp_map(); 628 | } 629 | printf("Service policy is Bind\n"); 630 | process_bind(service_obj, action); 631 | } 632 | } 633 | } 634 | } 635 | 636 | void get_string(char source[4096], char dest[2048]){ 637 | int count = 0; 638 | while((source[count] != '\n') && (count < 1023)){ 639 | dest[count] = source[count]; 640 | count++; 641 | } 642 | dest[count]='\n'; 643 | dest[count + 1] = '\0'; 644 | } 645 | 646 | int run(){ 647 | signal(SIGINT, INThandler); 648 | system("clear"); 649 | setpath("/tmp/", "ziti-edge-tunnel.sock",SOCK_NAME); 650 | setpath("/tmp/", "ziti-edge-tunnel-event.sock",EVENT_SOCK_NAME); 651 | struct sockaddr_un ctrl_addr; 652 | struct sockaddr_un event_addr; 653 | int new_count = 0; 654 | int old_count =0; 655 | char* command = "{\"Command\":\"ZitiDump\",\"Data\":{\"DumpPath\": \"/tmp/.ziti\"}}"; 656 | int command_len = strlen(command); 657 | byte cmdbytes[command_len]; 658 | string2Byte(command, cmdbytes); 659 | char *val_type_str, *str; 660 | int val_type; 661 | int ret; 662 | 663 | 664 | char event_buffer[EVENT_BUFFER_SIZE]; 665 | //open Unix client ctrl socket 666 | event_socket = socket(AF_UNIX, SOCK_STREAM, 0); 667 | if (ctrl_socket == -1) { 668 | perror("socket"); 669 | printf("%s\n", strerror(errno)); 670 | return 1; 671 | } 672 | //open Unix client ctrl socket 673 | ctrl_socket = socket(AF_UNIX, SOCK_STREAM, 0); 674 | if (ctrl_socket == -1) { 675 | perror("socket"); 676 | printf("%s\n", strerror(errno)); 677 | return 1; 678 | } 679 | //zero sockaddr_un for compatibility 680 | memset(&event_addr, 0, sizeof(struct sockaddr_un)); 681 | memset(&ctrl_addr, 0, sizeof(struct sockaddr_un)); 682 | ctrl_addr.sun_family = AF_UNIX; 683 | event_addr.sun_family = AF_UNIX; 684 | //copy string path of symbolic link to Sun Paths 685 | strncpy(event_addr.sun_path, EVENT_SOCK_NAME, sizeof(event_addr.sun_path) - 1); 686 | strncpy(ctrl_addr.sun_path, SOCK_NAME, sizeof(ctrl_addr.sun_path) - 1); 687 | //connect to ziti-edge-tunnel unix sockets 688 | ret = connect(event_socket, (const struct sockaddr *) &event_addr,sizeof(struct sockaddr_un)); 689 | if (ret == -1) { 690 | fprintf(stderr, "The ziti-edge-tunnel-event sock is down.\n"); 691 | printf("%s\n", strerror(errno)); 692 | return -1; 693 | } 694 | ret = connect (ctrl_socket, (const struct sockaddr *) &ctrl_addr,sizeof(struct sockaddr_un)); 695 | if (ret == -1) { 696 | fprintf(stderr, "The ziti-edge-tunnel sock is down.\n"); 697 | printf("%s\n", strerror(errno)); 698 | return -1; 699 | } 700 | while(true) 701 | { 702 | memset(&event_buffer, 0, EVENT_BUFFER_SIZE); 703 | char ch[1]; 704 | int count = 0; 705 | while((read(event_socket, ch, 1 ) != 0) && count < MAX_LINE_LENGTH){ 706 | if(ch[0] != '\n'){ 707 | //printf("%c", ch[0]); 708 | event_buffer[count] = ch[0]; 709 | }else{ 710 | //printf("%c\n", ch[0]); 711 | event_buffer[count + 1] = '\0'; 712 | break; 713 | } 714 | count++; 715 | } 716 | 717 | /* Ensure buffer is 0-terminated. */ 718 | event_buffer[EVENT_BUFFER_SIZE - 1] = '\0'; 719 | char *event_jString = (char*)event_buffer; 720 | if(strlen(event_jString)) 721 | { 722 | struct json_object *event_jobj = json_tokener_parse(event_jString); 723 | struct json_object *op_obj = json_object_object_get(event_jobj, "Op"); 724 | if(op_obj){ 725 | char operation[strlen(json_object_get_string(op_obj)) + 1]; 726 | sprintf(operation, "%s", json_object_get_string(op_obj)); 727 | if(strcmp(operation, "metrics")){ 728 | printf("%s\n\n",json_object_to_json_string_ext(event_jobj,JSON_C_TO_STRING_PLAIN)); 729 | } 730 | if(!strcmp("status", operation)){ 731 | struct json_object *status_obj = json_object_object_get(event_jobj, "Status"); 732 | 733 | if(status_obj){ 734 | if(tun_fd == -1){ 735 | open_tun_map(); 736 | } 737 | uint32_t key = 0; 738 | struct ifindex_tun o_tunif; 739 | tun_map.key = (uint64_t)&key; 740 | tun_map.value = (uint64_t)&o_tunif; 741 | tun_map.map_fd = tun_fd; 742 | int lookup = syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &tun_map, sizeof(tun_map)); 743 | if (!lookup) 744 | { 745 | if((sizeof(o_tunif.cidr) > 0) && (sizeof(o_tunif.mask) >0)){ 746 | sprintf(tunip_string, "%s" , o_tunif.cidr); 747 | sprintf(tunip_mask_string, "%s", o_tunif.mask); 748 | zfw_update(tunip_string, tunip_mask_string, "1", "65535", "tcp", "-I"); 749 | zfw_update(tunip_string, tunip_mask_string, "1", "65535", "udp", "-I"); 750 | tun_ifname = o_tunif.ifname; 751 | } 752 | } 753 | struct json_object *identities_obj = json_object_object_get(status_obj, "Identities"); 754 | if(identities_obj){ 755 | int identities_len = json_object_array_length(identities_obj); 756 | if(identities_len){ 757 | for(int i = 0; i < identities_len; i++){ 758 | struct json_object *ident_obj = json_object_array_get_idx(identities_obj, i); 759 | if(ident_obj){ 760 | struct json_object *services_obj = json_object_object_get(ident_obj, "Services"); 761 | if(services_obj){ 762 | enumerate_service(services_obj, "-I"); 763 | } 764 | } 765 | } 766 | } 767 | } 768 | } 769 | } 770 | else if(!strcmp("bulkservice", operation)){ 771 | struct json_object *services_obj = json_object_object_get(event_jobj, "RemovedServices"); 772 | if(services_obj){ 773 | enumerate_service(services_obj, "-D"); 774 | } 775 | services_obj = json_object_object_get(event_jobj, "AddedServices"); 776 | if(services_obj){ 777 | enumerate_service(services_obj, "-I"); 778 | } 779 | } 780 | else if(!strcmp("identity", operation)){ 781 | struct json_object *action_obj = json_object_object_get(event_jobj, "Action"); 782 | if(action_obj){ 783 | char action_string[strlen(json_object_get_string(action_obj)) + 1]; 784 | sprintf(action_string, "%s", json_object_get_string(action_obj)); 785 | if(!strcmp("updated", action_string)){ 786 | struct json_object *ident_obj = json_object_object_get(event_jobj, "Id"); 787 | if(ident_obj){ 788 | struct json_object *ident_services_obj = json_object_object_get(ident_obj, "Services"); 789 | if(ident_services_obj){ 790 | enumerate_service(ident_services_obj, "-I"); 791 | } 792 | } 793 | } 794 | } 795 | } 796 | 797 | } 798 | json_object_put(event_jobj); 799 | } 800 | sleep(1); 801 | } 802 | return 0; 803 | } 804 | 805 | int main(int argc, char *argv[]) { 806 | signal(SIGINT, INThandler); 807 | signal(SIGTERM, INThandler); 808 | //system("clear"); 809 | system("clear"); 810 | while(true){ 811 | if(transp_fd == -1){ 812 | open_transp_map(); 813 | } 814 | if(tun_fd == -1){ 815 | open_tun_map(); 816 | } 817 | run(); 818 | if(event_socket != -1){ 819 | close(event_socket); 820 | } 821 | if(event_socket != -1){ 822 | close(ctrl_socket); 823 | } 824 | sleep(1); 825 | } 826 | return 0; 827 | } 828 | -------------------------------------------------------------------------------- /src/zfw_xdp_tun_ingress.c: -------------------------------------------------------------------------------- 1 | /* Copyright (C) 2022 Robert Caamano */ 2 | /* 3 | * This program is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | 8 | * This program is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * see . 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #ifndef memcpy 28 | #define memcpy(dest, src, n) __builtin_memcpy((dest), (src), (n)) 29 | #endif 30 | #define MAX_IF_ENTRIES 30 31 | #define BPF_MAX_SESSIONS 10000 32 | #define INGRESS 0 33 | #define NO_REDIRECT_STATE_FOUND 10 34 | 35 | struct bpf_event{ 36 | unsigned long long tstamp; 37 | __u32 ifindex; 38 | __u32 tun_ifindex; 39 | __u32 daddr; 40 | __u32 saddr; 41 | __u16 sport; 42 | __u16 dport; 43 | __u16 tport; 44 | __u8 proto; 45 | __u8 direction; 46 | __u8 error_code; 47 | __u8 tracking_code; 48 | unsigned char source[6]; 49 | unsigned char dest[6]; 50 | }; 51 | 52 | /*Key to tun_map, tcp_map and udp_map*/ 53 | struct tuple_key { 54 | __u32 daddr; 55 | __u32 saddr; 56 | __u16 sport; 57 | __u16 dport; 58 | }; 59 | 60 | /*Key to tun_map*/ 61 | struct tun_key { 62 | __u32 daddr; 63 | __u32 saddr; 64 | }; 65 | 66 | /*Value to tun_map*/ 67 | struct tun_state { 68 | unsigned long long tstamp; 69 | unsigned int ifindex; 70 | unsigned char source[6]; 71 | unsigned char dest[6]; 72 | }; 73 | 74 | /*value to ifindex_tun_map*/ 75 | struct ifindex_tun { 76 | uint32_t index; 77 | char ifname[IFNAMSIZ]; 78 | char cidr[16]; 79 | char mask[3]; 80 | bool verbose; 81 | }; 82 | 83 | /*tun ifindex map*/ 84 | struct { 85 | __uint(type, BPF_MAP_TYPE_ARRAY); 86 | __uint(key_size, sizeof(uint32_t)); 87 | __uint(value_size, sizeof(struct ifindex_tun)); 88 | __uint(max_entries, 1); 89 | __uint(pinning, LIBBPF_PIN_BY_NAME); 90 | } ifindex_tun_map SEC(".maps"); 91 | 92 | /*Ringbuf map*/ 93 | struct { 94 | __uint(type, BPF_MAP_TYPE_RINGBUF); 95 | __uint(max_entries, 256 * 1024); 96 | __uint(pinning, LIBBPF_PIN_BY_NAME); 97 | } rb_map SEC(".maps"); 98 | 99 | /*Hashmap to track tun interface inbound passthrough connections*/ 100 | struct { 101 | __uint(type, BPF_MAP_TYPE_LRU_HASH); 102 | __uint(key_size, sizeof(struct tun_key)); 103 | __uint(value_size,sizeof(struct tun_state)); 104 | __uint(max_entries, BPF_MAX_SESSIONS); 105 | __uint(pinning, LIBBPF_PIN_BY_NAME); 106 | } tun_map SEC(".maps"); 107 | 108 | static inline struct tun_state *get_tun(struct tun_key key){ 109 | struct tun_state *ts; 110 | ts = bpf_map_lookup_elem(&tun_map, &key); 111 | return ts; 112 | } 113 | 114 | /*get entry from tun ifindex map*/ 115 | static inline struct ifindex_tun *get_tun_index(uint32_t key){ 116 | struct ifindex_tun *iftun; 117 | iftun = bpf_map_lookup_elem(&ifindex_tun_map, &key); 118 | return iftun; 119 | } 120 | 121 | static inline void send_event(struct bpf_event *new_event){ 122 | struct bpf_event *rb_event; 123 | rb_event = bpf_ringbuf_reserve(&rb_map, sizeof(*rb_event), 0); 124 | if(rb_event){ 125 | rb_event->ifindex = new_event->ifindex; 126 | rb_event->tun_ifindex = new_event->tun_ifindex; 127 | rb_event->tstamp = new_event->tstamp; 128 | rb_event->daddr = new_event->daddr; 129 | rb_event->saddr = new_event->saddr; 130 | rb_event->dport = new_event->dport; 131 | rb_event->sport = new_event->sport; 132 | rb_event->tport = new_event->tport; 133 | rb_event->proto = new_event->proto; 134 | rb_event->direction = new_event->direction; 135 | rb_event->tracking_code = new_event->tracking_code; 136 | rb_event->error_code = new_event->error_code; 137 | for(int x =0; x < 6; x++){ 138 | rb_event->source[x] = new_event->source[x]; 139 | rb_event->dest[x] = new_event->dest[x]; 140 | } 141 | bpf_ringbuf_submit(rb_event, 0); 142 | } 143 | } 144 | 145 | SEC("xdp_redirect") 146 | int xdp_redirect_prog(struct xdp_md *ctx) 147 | { 148 | /*look up attached interface inbound diag status*/ 149 | struct ifindex_tun *tun_diag = get_tun_index(0); 150 | if (!tun_diag) 151 | { 152 | return XDP_PASS; 153 | } 154 | struct iphdr *iph = (struct iphdr *)(unsigned long)(ctx->data); 155 | /* ensure ip header is in packet bounds */ 156 | if ((unsigned long)(iph + 1) > (unsigned long)ctx->data_end){ 157 | return XDP_PASS; 158 | } 159 | /* ip options not allowed */ 160 | if (iph->ihl != 5){ 161 | 162 | return XDP_PASS; 163 | } 164 | unsigned long long tstamp = bpf_ktime_get_ns(); 165 | struct bpf_event event = { 166 | tstamp, 167 | ctx->ingress_ifindex, 168 | 0, 169 | 0, 170 | 0, 171 | 0, 172 | 0, 173 | 0, 174 | 0, 175 | INGRESS, 176 | 0, 177 | 0, 178 | {0}, 179 | {0} 180 | }; 181 | 182 | struct tun_key tun_state_key; 183 | tun_state_key.daddr = iph->saddr; 184 | tun_state_key.saddr = iph->daddr; 185 | struct tun_state *tus = get_tun(tun_state_key); 186 | if(tus){ 187 | bpf_xdp_adjust_head(ctx, -14); 188 | struct ethhdr *eth = (struct ethhdr *)(unsigned long)(ctx->data); 189 | /* verify its a valid eth header within the packet bounds */ 190 | if ((unsigned long)(eth + 1) > (unsigned long)ctx->data_end){ 191 | return XDP_PASS; 192 | } 193 | if(tun_diag->verbose){ 194 | struct iphdr *iph = (struct iphdr *)(ctx->data + sizeof(*eth)); 195 | /* ensure ip header is in packet bounds */ 196 | if ((unsigned long)(iph + 1) > (unsigned long)ctx->data_end){ 197 | return XDP_PASS; 198 | } 199 | __u8 protocol = iph->protocol; 200 | if(protocol == IPPROTO_TCP){ 201 | struct tcphdr *tcph = (struct tcphdr *)((unsigned long)iph + sizeof(*iph)); 202 | if ((unsigned long)(tcph + 1) > (unsigned long)ctx->data_end){ 203 | return XDP_PASS; 204 | } 205 | event.dport = tcph->dest; 206 | event.sport = tcph->source; 207 | }else if (protocol == IPPROTO_UDP){ 208 | struct udphdr *udph = (struct udphdr *)((unsigned long)iph + sizeof(*iph)); 209 | if ((unsigned long)(udph + 1) > (unsigned long)ctx->data_end){ 210 | return XDP_PASS; 211 | } 212 | event.dport = udph->dest; 213 | event.sport = udph->source; 214 | } 215 | event.tun_ifindex = tus->ifindex; 216 | event.proto = protocol; 217 | event.saddr = iph->saddr; 218 | event.daddr = iph->daddr; 219 | memcpy(&event.source, &tus->dest, 6); 220 | memcpy(&event.dest, &tus->source, 6); 221 | send_event(&event); 222 | } 223 | memcpy(ð->h_dest, &tus->source,6); 224 | memcpy(ð->h_source, &tus->dest,6); 225 | unsigned short proto = bpf_htons(ETH_P_IP); 226 | memcpy(ð->h_proto, &proto, sizeof(proto)); 227 | return bpf_redirect(tus->ifindex,0); 228 | } 229 | if(tun_diag->verbose){ 230 | event.error_code = NO_REDIRECT_STATE_FOUND; 231 | send_event(&event); 232 | } 233 | return XDP_PASS; 234 | } 235 | 236 | char _license[] SEC("license") = "GPL"; 237 | --------------------------------------------------------------------------------