diff --git a/.github/workflows/angular.yml b/.github/workflows/angular.yml index dd16cd02f..b0db0369e 100644 --- a/.github/workflows/angular.yml +++ b/.github/workflows/angular.yml @@ -6,6 +6,8 @@ on: - 'desktop/angular/**' branches: - main + - no-spn-no-telemetry + - release-candidate/** - development - v1-legacy - v1-legacy-develop @@ -60,4 +62,4 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build angular projects - run: earthly --ci --remote-cache=ghcr.io/safing/build-cache --push +angular-ci + run: earthly --ci ${{ github.repository_owner == 'safing' && '--remote-cache=ghcr.io/safing/build-cache --push' || '' }} +angular-ci diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 9c7a0298b..b0fd34a1b 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -4,12 +4,19 @@ on: push: paths: - '**.go' + - 'go.mod' + - 'go.sum' + - 'Earthfile' + - '.golangci.yml' + - '.github/workflows/go.yml' - 'cmds/**' - 'runtime/**' - 'service/**' - 'spn/**' branches: - main + - no-spn-no-telemetry + - release-candidate/** - development - v1-legacy - v1-legacy-develop @@ -17,6 +24,11 @@ on: pull_request: paths: - '**.go' + - 'go.mod' + - 'go.sum' + - 'Earthfile' + - '.golangci.yml' + - '.github/workflows/go.yml' - 'cmds/**' - 'runtime/**' - 'service/**' @@ -34,19 +46,27 @@ jobs: steps: - name: Check out code uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + # Full history, so that pull requests can be linted against the + # merge base with their base branch. + fetch-depth: 0 - name: Setup Go uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 with: - go-version: '^1.26' + go-version: '^1.27' cache: false + # For pull requests, new issues are determined via git against the merge + # base. The action's only-new-issues fetches the PR diff from the GitHub + # API instead, which fails for diffs over 20000 lines and then reports + # every pre-existing issue of the code base. - name: Run golangci-lint uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0 with: - version: v2.12.2 - only-new-issues: true - args: -c ./.golangci.yml --timeout 15m + version: v2.15.0 + only-new-issues: ${{ github.event_name != 'pull_request' }} + args: -c ./.golangci.yml --timeout 15m ${{ github.event_name == 'pull_request' && format('--new-from-merge-base=origin/{0}', github.base_ref) || '' }} - name: Run go vet run: go vet ./... @@ -68,4 +88,4 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Run Go Tests & Build - run: earthly --ci --remote-cache=ghcr.io/safing/build-cache --push +go-ci + run: earthly --ci ${{ github.repository_owner == 'safing' && '--remote-cache=ghcr.io/safing/build-cache --push' || '' }} +go-ci diff --git a/.github/workflows/kext.yml b/.github/workflows/kext.yml index e1a2bbb99..774f8ecd5 100644 --- a/.github/workflows/kext.yml +++ b/.github/workflows/kext.yml @@ -6,6 +6,8 @@ on: - 'windows_kext/**' branches: - main + - no-spn-no-telemetry + - release-candidate/** - development - v1-legacy - v1-legacy-develop @@ -37,4 +39,4 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build Kernel Extension - run: earthly --ci --remote-cache=ghcr.io/safing/build-cache --push +kext-ci + run: earthly --ci ${{ github.repository_owner == 'safing' && '--remote-cache=ghcr.io/safing/build-cache --push' || '' }} +kext-ci diff --git a/.github/workflows/no-telemetry-ci.yml b/.github/workflows/no-telemetry-ci.yml new file mode 100644 index 000000000..0b9eb46a7 --- /dev/null +++ b/.github/workflows/no-telemetry-ci.yml @@ -0,0 +1,156 @@ +name: No-Telemetry CI + +on: + push: + branches: [no-spn-no-telemetry, 'release-candidate/**'] + pull_request: + branches: [development] + +permissions: + contents: read + +jobs: + full-go-build-and-test: + name: Full Go Build & Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + check-latest: true + cache: true + - name: Download modules + run: go mod download + - name: Verify go.mod / go.sum are tidy + run: | + go mod tidy + git diff --exit-code -- go.mod go.sum + - name: Build all packages + run: go build ./... + - name: Vet all packages + run: go vet ./... + # Upstream also runs the suite with -short (see Earthfile +go-test): + # "long" tests require a full desktop system. + - name: Test all packages + run: go test -short -count=1 ./... + - name: Race check on privacy-critical packages + run: go test -race -short -count=1 ./service/network/... ./service/netquery/... ./service/sync/... ./spn/access/... + + no-telemetry-guard: + name: No telemetry and no network account API + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Reject known Safing account endpoints + run: | + ! grep -RInE 'account\.safing\.io|telemetry\.safing\.io|api\.safing\.io' service/sync spn/access + - name: Reject outbound HTTP clients in sync and removed account packages + # service/sync serves the local import/export API and needs net/http + # for status codes, but must never send requests itself. + run: | + ! grep -RInE 'net/http' spn/access + ! grep -RInE 'http\.Client|http\.NewRequest|http\.(Get|Post|Head|PostForm)\(|DefaultClient' service/sync spn/access + - name: Reject Safing online check and tracking parameters + run: | + ! grep -RIn --include='*.go' 'online-check\.safing\.io' service base + ! grep -RIn 'source=Portmaster' service base desktop/angular/src desktop/angular/projects desktop/tauri/src-tauri/src + - name: Reject the Safing support hub in the UI + run: | + ! grep -RIn 'support\.safing\.io' desktop/angular/src desktop/angular/projects + - name: Reject spn/access imports anywhere in service/ + run: | + ! grep -RIn --include='*.go' '"github.com/safing/portmaster/spn/access' service + - name: Reject subscription gating of settings + run: | + ! grep -RIn --include='*.go' 'RequiresFeatureIDAnnotation:' service + - name: Ensure the obsolete login testsuite is excluded + run: grep -q '^//go:build ignore$' cmds/testsuite/login.go + + angular-ui-build: + name: Angular UI Build (no account API) + runs-on: ubuntu-latest + defaults: + run: + working-directory: desktop/angular + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + cache-dependency-path: desktop/angular/package-lock.json + - name: Install + run: npm ci --no-audit --no-fund + - name: Reject account/SPN API calls in the API library + run: | + ! grep -RInE 'v1/spn/account|v1/account/features|account\.safing\.io|core:spn/account' projects/safing/portmaster-api/src + - name: Build libraries and UI + run: npm run build + - name: Reject account API calls in the production bundle + run: | + ! grep -lE 'v1/spn/account|v1/account/features' dist/*.js + + tauri-clippy: + name: Tauri (Rust) clippy, no warnings + runs-on: ubuntu-latest + timeout-minutes: 40 + defaults: + run: + working-directory: desktop/tauri/src-tauri + steps: + - uses: actions/checkout@v4 + - name: Install Tauri system dependencies + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends \ + libsoup-3.0-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libgtk-3-dev + # Same Rust version as the builds (rust_version in the Earthfile), so + # that a new stable release cannot break this job without a change + # here. + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.89" + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: desktop/tauri/src-tauri -> target + key: clippy-linux + - name: Create empty UI dist so the build script is satisfied + run: mkdir -p ../../angular/dist/tauri-builtin + - name: Clippy (all targets, deny warnings) + run: cargo clippy --all-targets --all-features -- -D warnings + - name: Reject SPN leftovers in the tray/UI shell + run: | + ! grep -rnE 'spn_toggle|set_spn_enabled|SPNStatus|models::spn' src + + tauri-clippy-windows: + # The Windows-only code of the UI (notifications, service control) is not + # compiled by the Linux job, so check it for the target of the installer. + name: Tauri (Rust) clippy for Windows, no warnings + runs-on: ubuntu-latest + timeout-minutes: 40 + defaults: + run: + working-directory: desktop/tauri/src-tauri + steps: + - uses: actions/checkout@v4 + - name: Install MinGW cross toolchain + # A hanging mirror once blocked this step until the job timeout. + timeout-minutes: 10 + run: | + sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 update -qq + sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 install -y -qq --no-install-recommends mingw-w64 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.89" + targets: x86_64-pc-windows-gnu + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: desktop/tauri/src-tauri -> target + key: clippy-windows + - name: Create empty UI dist so the build script is satisfied + run: mkdir -p ../../angular/dist/tauri-builtin + - name: Clippy (Windows target, deny warnings) + run: cargo clippy --target x86_64-pc-windows-gnu --all-features -- -D warnings diff --git a/.github/workflows/release-windows-installer.yml b/.github/workflows/release-windows-installer.yml new file mode 100644 index 000000000..0025705cb --- /dev/null +++ b/.github/workflows/release-windows-installer.yml @@ -0,0 +1,195 @@ +name: Release Windows Installer + +# Builds the Windows x64 NSIS installer from Linux (cross-build, see BUILDING.md §7b) +# and attaches it together with the core binaries to an existing GitHub release. +# +# Triggers: +# - push of a tag v* : creates the GitHub release (pre-release when the tag contains a '-', +# e.g. v0.1.0-rc1) with notes from CHANGELOG.md and attaches the assets. +# - workflow_dispatch : attaches the assets to an existing release/draft for the given tag. + +on: + push: + tags: + - "v*" + workflow_dispatch: + inputs: + tag: + description: "Release tag to attach the assets to (e.g. v0.1.0-rc1)" + required: true + type: string + +permissions: + contents: write + +concurrency: + group: release-windows-installer-${{ inputs.tag || github.ref_name }} + cancel-in-progress: false + +env: + TAURI_CLI_VERSION: "2.2.7" + RUST_TARGET: x86_64-pc-windows-gnu + +jobs: + core-dll: + # Built here instead of taking the upstream DLL: that one needs the VC++ + # runtime, which a clean Windows does not have. + uses: ./.github/workflows/windows-dll.yml + with: + ref: ${{ inputs.tag || github.ref_name }} + + windows-installer: + name: Cross-build Windows installer and upload release assets + needs: core-dll + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag || github.ref_name }} + + - name: Derive version from tag + id: ver + run: | + TAG="${{ inputs.tag || github.ref_name }}" + case "$TAG" in v[0-9]*) ;; *) echo "::error::tag must look like vX.Y.Z[-pre]"; exit 1;; esac + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + case "$TAG" in *-*) echo "prerelease=true" >> "$GITHUB_OUTPUT";; *) echo "prerelease=false" >> "$GITHUB_OUTPUT";; esac + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + cache-dependency-path: desktop/angular/package-lock.json + + - name: Install NSIS and MinGW cross toolchain + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq nsis mingw-w64 lld llvm zip + + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ env.RUST_TARGET }} + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: desktop/tauri/src-tauri -> target + key: ${{ env.RUST_TARGET }} + + - name: Install tauri-cli (prebuilt) + run: | + curl -sSfL -o /tmp/tauri-cli.tgz \ + "https://github.com/tauri-apps/tauri/releases/download/tauri-cli-v${TAURI_CLI_VERSION}/cargo-tauri-x86_64-unknown-linux-gnu.tgz" + tar xzf /tmp/tauri-cli.tgz -C /tmp + install -m 0755 /tmp/cargo-tauri "$HOME/.cargo/bin/cargo-tauri" + cargo tauri -V + + - name: Build Angular UI and asset bundles + working-directory: desktop/angular + run: | + npm ci --no-audit --no-fund + npm run build + NODE_ENV=production npx ng build --configuration production tauri-builtin + mkdir -p ../../dist/binary/all + (cd dist && zip -qr ../../../dist/binary/all/portmaster.zip ./ -x "tauri-builtin/*") + (cd ../../assets/data && zip -qr -9 -X ../../dist/binary/all/assets.zip *) + # Guard: production bundle must not call account endpoints. + ! grep -lE 'v1/spn/account|v1/account/features' dist/*.js + + - name: Build portmaster-core (windows/amd64, linux/amd64) and updatemgr + env: + VERSION: ${{ steps.ver.outputs.version }} + SHA: ${{ steps.ver.outputs.sha }} + run: | + BT=$(date -u +%Y-%m-%dT%H:%M:%SZ) + LDF="-X github.com/safing/portmaster/base/info.version=${VERSION} -X github.com/safing/portmaster/base/info.buildSource=${SHA} -X github.com/safing/portmaster/base/info.buildTime=${BT}" + mkdir -p dist/binary/windows_amd64 dist/binary/linux_amd64 + CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath -ldflags="$LDF" -o dist/binary/windows_amd64/portmaster-core.exe ./cmds/portmaster-core + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="$LDF" -o dist/binary/linux_amd64/portmaster-core ./cmds/portmaster-core + CGO_ENABLED=0 go build -trimpath -o /tmp/updatemgr ./cmds/updatemgr + dist/binary/linux_amd64/portmaster-core version + + - name: Fetch signed kernel driver and intel data (upstream stable) + run: | + mkdir -p dist/downloaded/windows_amd64 dist/intel + /tmp/updatemgr download https://updates.safing.io/stable.v3.json --platform windows_amd64 dist/downloaded/windows_amd64 + find dist/downloaded/windows_amd64 -type f ! -name "portmaster-kext.sys" -delete + /tmp/updatemgr download https://updates.safing.io/intel.v3.json dist/intel + ls -la dist/intel + + - name: Use the core DLL built with the static C runtime + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: portmaster-core-dll + path: dist/downloaded/windows_amd64 + + - name: Cross-build Tauri UI (portmaster.exe) + working-directory: desktop/tauri/src-tauri + run: cargo tauri build --ci --target ${{ env.RUST_TARGET }} --no-bundle + + - name: Assemble installer inputs and build NSIS installer + env: + VERSION: ${{ steps.ver.outputs.version }} + run: | + T=desktop/tauri/src-tauri + rm -rf "$T/binary" "$T/intel" && mkdir -p "$T/binary" "$T/intel" + cp dist/downloaded/windows_amd64/portmaster-kext.sys dist/downloaded/windows_amd64/portmaster-core.dll \ + dist/binary/windows_amd64/portmaster-core.exe dist/binary/all/portmaster.zip dist/binary/all/assets.zip \ + "$T/target/${RUST_TARGET}/release/WebView2Loader.dll" "$T/binary/" + cp dist/intel/* "$T/intel/" + python3 packaging/windows/render_nsis_linux.py "$VERSION" + + - name: Collect assets and checksums + env: + VERSION: ${{ steps.ver.outputs.version }} + run: | + mkdir -p release + cp "dist/windows_amd64/portmasterpro_${VERSION}_x64-setup.exe" release/ + cp dist/binary/windows_amd64/portmaster-core.exe "release/portmaster-core_${VERSION}_windows_amd64.exe" + cp dist/binary/linux_amd64/portmaster-core "release/portmaster-core_${VERSION}_linux_amd64" + cp dist/binary/all/portmaster.zip "release/portmaster-ui_${VERSION}.zip" + (cd release && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt) + + - uses: actions/upload-artifact@v4 + with: + name: portmasterpro-${{ steps.ver.outputs.version }}-windows + path: release/ + retention-days: 14 + + - name: Create the GitHub release if it does not exist yet + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ steps.ver.outputs.tag }} + VERSION: ${{ steps.ver.outputs.version }} + PRERELEASE: ${{ steps.ver.outputs.prerelease }} + run: | + if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "release $TAG exists, only uploading assets"; exit 0 + fi + # Release notes: the CHANGELOG section for this version, or a short fallback. + python3 - "$VERSION" > /tmp/notes.md <<'PY' + import re, sys + v = sys.argv[1] + try: + text = open("CHANGELOG.md", encoding="utf-8").read() + except FileNotFoundError: + text = "" + m = re.search(r"^## \[?" + re.escape(v) + r"\]?[^\n]*\n(.*?)(?=^## |\Z)", text, re.S | re.M) + body = m.group(1).strip() if m else f"portmasterpro {v}. See BUILDING.md and desktop/CHANGES.md." + print(body) + PY + ARGS=(--repo "$GITHUB_REPOSITORY" --title "portmasterpro $VERSION" --notes-file /tmp/notes.md --verify-tag) + [ "$PRERELEASE" = "true" ] && ARGS+=(--prerelease) + gh release create "$TAG" "${ARGS[@]}" + + - name: Upload assets to the GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release upload "${{ steps.ver.outputs.tag }}" release/* --clobber --repo "${{ github.repository }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b42c0ddca..0b3712c18 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,9 +5,6 @@ on: branches: - main - development - - tags: - - v* workflow_dispatch: jobs: @@ -28,7 +25,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build all artifacts - run: earthly --remote-cache=ghcr.io/safing/build-cache --push +release-prep + run: earthly +release-prep - name: Upload Dist uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -56,7 +53,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build linux installers - run: earthly --ci --remote-cache=ghcr.io/safing/build-cache --push +installer-linux + run: earthly --ci ${{ github.repository_owner == 'safing' && '--remote-cache=ghcr.io/safing/build-cache --push' || '' }} +installer-linux # --ci include --no-output flag - name: Upload Installers diff --git a/.github/workflows/tauri.yml b/.github/workflows/tauri.yml index 665bad054..effdab12b 100644 --- a/.github/workflows/tauri.yml +++ b/.github/workflows/tauri.yml @@ -6,6 +6,8 @@ on: - 'desktop/tauri/**' branches: - main + - no-spn-no-telemetry + - release-candidate/** - development - v1-legacy - v1-legacy-develop @@ -37,7 +39,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build tauri project - run: earthly --ci --remote-cache=ghcr.io/safing/build-cache --push +tauri-ci + run: earthly --ci ${{ github.repository_owner == 'safing' && '--remote-cache=ghcr.io/safing/build-cache --push' || '' }} +tauri-ci lint: name: Linter @@ -56,4 +58,4 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build tauri project - run: earthly --ci --remote-cache=ghcr.io/safing/build-cache --push +tauri-lint + run: earthly --ci ${{ github.repository_owner == 'safing' && '--remote-cache=ghcr.io/safing/build-cache --push' || '' }} +tauri-lint diff --git a/.github/workflows/upstream-sync.yml b/.github/workflows/upstream-sync.yml new file mode 100644 index 000000000..758d2b1e1 --- /dev/null +++ b/.github/workflows/upstream-sync.yml @@ -0,0 +1,69 @@ +name: Upstream Sync + +# Checks safing/portmaster `development` for new commits and opens a pull request into the +# fork mainline so upstream fixes are reviewed and merged regularly. +# Runs weekly; can be triggered manually. Needs "Allow GitHub Actions to create and approve +# pull requests" enabled in the repository settings (Settings → Actions → General). + +on: + schedule: + - cron: "17 5 * * 1" + workflow_dispatch: + +permissions: + contents: write + pull-requests: write + +env: + UPSTREAM_REPO: https://github.com/safing/portmaster.git + UPSTREAM_BRANCH: development + TARGET_BRANCH: no-spn-no-telemetry + +jobs: + sync: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.TARGET_BRANCH }} + fetch-depth: 0 + + - name: Fetch upstream and detect new commits + id: diff + run: | + git remote add upstream "$UPSTREAM_REPO" + git fetch --no-tags upstream "$UPSTREAM_BRANCH" + NEW=$(git rev-list --count "HEAD..upstream/$UPSTREAM_BRANCH") + echo "new=$NEW" >> "$GITHUB_OUTPUT" + echo "upstream_sha=$(git rev-parse --short upstream/$UPSTREAM_BRANCH)" >> "$GITHUB_OUTPUT" + echo "$NEW new upstream commit(s)" + git log --oneline "HEAD..upstream/$UPSTREAM_BRANCH" | head -50 > /tmp/upstream-commits.txt || true + + - name: Open or update the sync pull request + if: steps.diff.outputs.new != '0' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + UPSTREAM_SHA: ${{ steps.diff.outputs.upstream_sha }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + BRANCH="upstream-sync/$UPSTREAM_SHA" + git checkout -B "$BRANCH" "upstream/$UPSTREAM_BRANCH" + git push -f origin "$BRANCH" + if gh pr list --repo "$GITHUB_REPOSITORY" --head "$BRANCH" --base "$TARGET_BRANCH" --json number --jq 'length' | grep -q '^0$'; then + { + echo "Upstream \`safing/portmaster:$UPSTREAM_BRANCH\` has ${{ steps.diff.outputs.new }} new commit(s) up to \`$UPSTREAM_SHA\`." + echo + echo "Merge checklist:" + echo "- [ ] conflicts resolved (typical: \`Cargo.toml\` version, \`service/instance.go\`, \`spn/access\`)" + echo "- [ ] no SPN/account references re-introduced into \`service/\` (CI guard)" + echo "- [ ] all workflows green" + echo + echo '```'; cat /tmp/upstream-commits.txt; echo '```' + } > /tmp/body.md + gh pr create --repo "$GITHUB_REPOSITORY" --base "$TARGET_BRANCH" --head "$BRANCH" \ + --title "chore: sync upstream development ($UPSTREAM_SHA)" --body-file /tmp/body.md + else + echo "PR already open for $BRANCH" + fi diff --git a/.github/workflows/windows-dll.yml b/.github/workflows/windows-dll.yml index a439dafd3..58d7917bb 100644 --- a/.github/workflows/windows-dll.yml +++ b/.github/workflows/windows-dll.yml @@ -4,6 +4,7 @@ on: push: paths: - 'windows_core_dll/**' + - '.github/workflows/windows-dll.yml' branches: - main - development @@ -13,6 +14,7 @@ on: pull_request: paths: - 'windows_core_dll/**' + - '.github/workflows/windows-dll.yml' branches: - main - development @@ -20,6 +22,13 @@ on: - v1-legacy-develop workflow_dispatch: + # Used by the release workflow, which ships this DLL in the installer. + workflow_call: + inputs: + ref: + description: "Git ref to build (defaults to the triggering ref)" + required: false + type: string jobs: build: @@ -28,6 +37,8 @@ jobs: steps: - name: Checkout Repository uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + ref: ${{ inputs.ref || github.ref }} - name: Add msbuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # v2 - name: Build DLL @@ -39,6 +50,20 @@ jobs: Write-Error "DLL build failed: portmaster-core.dll not found" exit 1 } + - name: Check that the DLL does not need the VC++ runtime + # A clean Windows has no VCRUNTIME140.dll, and the DLL then fails to load + # with "module not found", so the C runtime must be linked statically. + shell: pwsh + run: | + $vs = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationPath + $dumpbin = Get-ChildItem "$vs\VC\Tools\MSVC" -Recurse -Filter dumpbin.exe | + Where-Object FullName -Match 'Hostx64\\x64' | Select-Object -First 1 + $deps = & $dumpbin.FullName /dependents windows_core_dll\x64\Release\portmaster-core.dll + $deps + if ($deps -match 'VCRUNTIME|MSVCP|api-ms-win-crt') { + Write-Error "portmaster-core.dll depends on the VC++ runtime" + exit 1 + } - name: Upload artifacts uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: diff --git a/.gitignore b/.gitignore index 7bc2f2a01..523e77f20 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,10 @@ go.mod.* vendor # testing -testdata +# Ignore the contents of testdata dirs, but track Go fuzzing corpora +# (crashers found by `go test -fuzz` are regression tests). +**/testdata/* +!**/testdata/fuzz/ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.a diff --git a/.golangci.yml b/.golangci.yml index 6e24cae05..3e16ae33e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -7,6 +7,7 @@ linters: - cyclop - depguard - exhaustruct + - exhaustruct_v5 # exhaustruct under its name in newer golangci-lint versions - forbidigo - funlen - gochecknoglobals @@ -14,6 +15,7 @@ linters: - gocognit - gocyclo - gomoddirectives + - gomodguard - interfacebloat - ireturn - lll @@ -49,9 +51,6 @@ linters: exclusions: generated: lax rules: - - linters: - - golint - text: a blank import .* - linters: - staticcheck text: 'ST1000: at least one file in a package should have a package comment.*' diff --git a/BUILDING.md b/BUILDING.md new file mode 100644 index 000000000..dacf997fd --- /dev/null +++ b/BUILDING.md @@ -0,0 +1,341 @@ +# portmasterpro — Build & Test Guide + +Diese Anleitung beschreibt wie du portmasterpro lokal kompilierst, testest +und die `no-spn-no-telemetry`-Änderungen verifizierst. + +--- + +## Voraussetzungen + +| Tool | Mindestversion | Installieren | +|---|---|---| +| Go | 1.26 (siehe `go.mod`, `toolchain go1.26.3` wird bei Bedarf automatisch geladen) | https://go.dev/dl/ | +| Git | beliebig | https://git-scm.com | +| Node.js | 20 LTS | https://nodejs.org (nur für Desktop-Tests) | +| pnpm / npm | beliebig | `npm i -g pnpm` (nur für Desktop-Tests) | +| gcc / build-essential | beliebig | `sudo apt install build-essential` (Linux) | + +> **Windows:** Nutze WSL2 (Ubuntu 22.04+) oder installiere +> [TDM-GCC](https://jmeubank.github.io/tdm-gcc/) für cgo-Support. + +--- + +## 1 · Repository klonen + +```bash +git clone https://github.com/0n113/portmasterpro.git +cd portmasterpro + +# Branch mit den Telemetrie-/SPN-Bereinigungen auschecken +git checkout no-spn-no-telemetry +``` + +--- + +## 2 · Go-Abhängigkeiten laden & aufräumen + +```bash +# Abhängigkeiten herunterladen +go mod download + +# Nicht mehr benötigte Einträge aus go.mod / go.sum entfernen +# (nach dem Entfernen der SPN-Pakete wichtig) +go mod tidy +``` + +> `go mod tidy` aktualisiert `go.sum` automatisch. +> Veränderte Dateien danach committen: +> ```bash +> git add go.mod go.sum +> git commit -m "chore: go mod tidy after SPN removal" +> ``` + +--- + +## 3 · Go-Code kompilieren + +### Nur prüfen ob alles kompiliert (kein Binary) + +```bash +go build ./... +``` + +Erwartete Ausgabe: keine Fehler, kein Output. + +### Binary bauen (Linux) + +```bash +mkdir -p build +go build -o build/portmasterpro ./cmds/portmaster-core/ +``` + +### Binary bauen (Windows, in WSL2) + +```bash +CGO_ENABLED=1 GOOS=windows GOARCH=amd64 \ + CC=x86_64-w64-mingw32-gcc \ + go build -o build/portmasterpro.exe ./cmds/portmaster-core/ +``` + +--- + +## 4 · Go-Tests ausführen + +### Alle Tests (wie in der CI) + +```bash +go test -short -count=1 ./... +``` + +`-short` entspricht der Upstream-Konvention (`Earthfile`, Target `+go-test`): +"lange" Tests brauchen ein vollständiges Desktop-System. + +**Bekannte umgebungsabhängige Fehler** (treten identisch im unveränderten +Upstream `development` auf, keine Regression dieses Branches): + +| Paket / Test | Ursache | +|---|---| +| `service/compat` · `TestIPTablesChains` | benötigt `iptables` im PATH | +| `service/netenv` · `TestCheckOnlineStatus` | benötigt Internetzugang | +| `service/resolver` · `TestResolveIPAndValidate` | benötigt Internetzugang (Reverse-DNS) | +| `service/profile/binmeta` · `TestFindIcon` | benötigt Desktop-Icons (evolution, nextcloud) | +| `service/profile/endpoints` · `TestEndpointMatching` | benötigt GeoIP-Datenbank | +| `spn/crew` · `TestConnectOp` | schlägt auch upstream fehl (EOF) | + +`spn/docks · TestExpansion` wird bewusst per `t.Skip` übersprungen: Der Test +authentifiziert sich mit SPN-Zugangstokens, die in portmasterpro nicht mehr +existieren. + +### Nur die Telemetrie-/SPN-Stub-Tests + +```bash +# service/sync — Stub startet/stoppt ohne Fehler, kein Manager +go test -v ./service/sync/... + +# spn/access — kein Login, alle Features offen, kein Manager +go test -v ./spn/access/... + +# service/netquery — Endpoints ungated, kein SPN-Import +go test -v ./service/netquery/... +``` + +### Erwartete Ausgabe (Beispiel `spn/access`) + +``` +=== RUN TestAccessStubNoOp +--- PASS: TestAccessStubNoOp (0.00s) +=== RUN TestAccessStubNotLoggedIn +--- PASS: TestAccessStubNotLoggedIn (0.00s) +=== RUN TestAccessStubAllFeaturesUnlocked +--- PASS: TestAccessStubAllFeaturesUnlocked (0.00s) +=== RUN TestAccessStubManagerIsNil +--- PASS: TestAccessStubManagerIsNil (0.00s) +PASS +ok github.com/safing/portmaster/spn/access +``` + +### Mit Race-Detector (empfohlen vor einem Merge) + +```bash +go test -race ./service/sync/... ./spn/access/... ./service/netquery/... +``` + +### go vet (statische Analyse) + +```bash +go vet ./... +``` + +--- + +## 5 · Manuelle Telemetrie-Prüfung + +Sicherstellen dass keine bekannten Safing-Telemetrie-URLs mehr im Code sind: + +```bash +# Sollte keine Ausgabe liefern: +grep -r 'account.safing.io\|updates.safing.io\|telemetry.safing.io\|api.safing.io' \ + ./service/sync/ ./spn/access/ + +echo "Exit $?: 0 = sauber, alles andere = Fund" +``` + +Sicherstellen dass `service/netquery` keine SPN-Pakete importiert: + +```bash +# Sollte keine Ausgabe liefern: +grep -r 'safing/portmaster/spn' ./service/netquery/ + +echo "Exit $?: 0 = sauber" +``` + +--- + +## 6 · Desktop-Frontend bauen (Angular 16, Node 20) + +Das produktive UI ist die Angular-App unter `desktop/angular`. Die gesamte +Account-/SPN-Logik ist zentral in `projects/safing/portmaster-api/src/lib/spn.service.ts` +neutralisiert (statisches lokales Profil, SPN dauerhaft `disabled`, keine HTTP- +Aufrufe an Account-Endpunkte). Details: `desktop/CHANGES.md`. + +```bash +cd desktop/angular + +# Abhängigkeiten exakt nach package-lock.json installieren +npm ci --no-audit --no-fund + +# Bibliotheken (@safing/ui, @safing/portmaster-api) + App als Production-Build +npm run build +``` + +Erwartung: Exit-Code 0. Upstream-Warnungen zu CommonJS-Abhängigkeiten +(`js-yaml-loader`, `data-urls`) und zum überschrittenen Bundle-Budget sind +bekannt und unkritisch. + +--- + +## 7 · Frontend-Guards + +```bash +cd desktop/angular + +# API-Bibliothek darf keine Account-Endpunkte mehr ansprechen (keine Ausgabe erwartet): +grep -rnE 'v1/spn/account|v1/account/features|account\.safing\.io|core:spn/account' \ + projects/safing/portmaster-api/src + +# Production-Bundle darf keine Account-API-Aufrufe enthalten (keine Ausgabe erwartet): +grep -lE 'v1/spn/account|v1/account/features' dist/*.js +``` + +Verbleibende `account.safing.io`-Strings im Bundle stammen aus nicht mehr +gerenderten Komponenten (`spn-login`, `spn-account-details`); sie lösen keine +Requests aus. + +--- + +## 7b · Windows-Installer unter Linux bauen (Cross-Build) + +Die Tauri-CLI verweigert `--bundles nsis` auf Nicht-Windows-Hosts, der Bundler-Code +unterstützt es aber. `packaging/windows/render_nsis_linux.py` rendert das originale +Tauri-NSIS-Template (inkl. `templates/nsis/install_hooks.nsh` für Dienst, Treiber und +Intel-Daten) und ruft `makensis` auf. + +```bash +# Toolchain +sudo apt install nsis mingw-w64 lld llvm +curl https://sh.rustup.rs -sSf | sh -s -- -y -t x86_64-pc-windows-gnu +# tauri-cli 2.2.7 (prebuilt): https://github.com/tauri-apps/tauri/releases/tag/tauri-cli-v2.2.7 + +# 1. Frontend +cd desktop/angular && npm ci && npm run build && NODE_ENV=production npx ng build --configuration production tauri-builtin +(cd dist && zip -r ../../../dist/binary/all/portmaster.zip ./ -x "tauri-builtin/*") +(cd ../../assets/data && zip -r -9 -X ../../dist/binary/all/assets.zip *) + +# 2. Core (Upstream-Konvention: CGO_ENABLED=0) +CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath \ + -ldflags="-X github.com/safing/portmaster/base/info.version= ..." \ + -o dist/binary/windows_amd64/portmaster-core.exe ./cmds/portmaster-core + +# 3. Signierter Kext + core.dll aus dem Upstream-Stable, Intel-Daten +go build -o /tmp/updatemgr ./cmds/updatemgr +/tmp/updatemgr download https://updates.safing.io/stable.v3.json --platform windows_amd64 dist/downloaded/windows_amd64 +/tmp/updatemgr download https://updates.safing.io/intel.v3.json dist/intel + +# 4. Tauri-UI (portmaster.exe + WebView2Loader.dll) +cd desktop/tauri/src-tauri && cargo tauri build --ci --target x86_64-pc-windows-gnu --no-bundle + +# 5. Dateien bereitstellen und Installer bauen +mkdir -p binary intel +cp ../../../dist/downloaded/windows_amd64/{portmaster-kext.sys,portmaster-core.dll} \ + ../../../dist/binary/windows_amd64/portmaster-core.exe ../../../dist/binary/all/*.zip \ + target/x86_64-pc-windows-gnu/release/WebView2Loader.dll binary/ +cp ../../../dist/intel/* intel/ +cd ../../.. && python3 packaging/windows/render_nsis_linux.py +# → dist/windows_amd64/portmasterpro__x64-setup.exe +``` + +Hinweise: +- Der Kernel-Treiber (`portmaster-kext.sys`) ist unverändert Safings signierter Treiber + (Stable 2.2.3, FileVersion 2.1.1.0). Das Split-Tunnel-Feature aus `development` + benötigt einen neueren Treiber und bleibt standardmäßig aus (`splittun/enable=false`). +- Installer und Binaries sind **nicht signiert** → SmartScreen-Warnung beim ersten Start. +- Der Installer ersetzt eine bestehende Portmaster-Installation (gleicher Dienstname + `PortmasterCore`, gleiches Installationsverzeichnis). + +--- + +## 8 · Vollständiger Check-Ablauf vor dem Merge + +Diesen Block einmalig von oben nach unten durchlaufen: + +```bash +# 1. Sauber starten +git checkout no-spn-no-telemetry +git pull + +# 2. Deps aufräumen +go mod tidy + +# 3. Kompilieren +go build ./... + +# 4. Vet +go vet ./... + +# 5. Tests (CI-Konvention) + Race-Detector auf den privacy-kritischen Paketen +go test -short -count=1 ./... +go test -race -short -count=1 ./service/network/... ./service/netquery/... ./service/sync/... ./spn/access/... + +# 6. Telemetrie-URLs prüfen +grep -r 'account.safing.io\|updates.safing.io\|api.safing.io' \ + ./service/sync/ ./spn/access/ && echo "FUND!" || echo "Sauber." + +# 7. SPN-/Account-Imports prüfen +grep -r 'safing/portmaster/spn' ./service/netquery/ && echo "FUND!" || echo "Sauber." +grep -rn --include='*.go' '"github.com/safing/portmaster/spn/access' ./service/ && echo "FUND!" || echo "Sauber." +grep -rn --include='*.go' 'RequiresFeatureIDAnnotation:' ./service/ && echo "FUND!" || echo "Sauber." + +# 8. Frontend (Angular, siehe Hinweis in Abschnitt 6) +cd desktop/angular && npm ci && npm run build +``` + +Wenn alle Schritte ohne Fehler und ohne "FUND!" durchlaufen → Branch ist merge-ready. +Für ein Release zusätzlich die Checkliste in `RELEASE.md` abarbeiten; ein Tag `vX.Y.Z[-rcN]` +erzeugt das GitHub-Release mit Installer und Checksummen automatisch (`release-windows-installer.yml`). + +--- + +## Troubleshooting + +### `undefined: mgr.Manager` beim Kompilieren +Die Stub-Dateien importieren `service/mgr`. Stelle sicher dass du auf dem +richtigen Branch bist und `go mod tidy` ausgeführt hast. + +```bash +git branch # muss 'no-spn-no-telemetry' zeigen +go mod tidy +go build ./... +``` + +### `cgo: C compiler not found` + +```bash +# Ubuntu/Debian +sudo apt install build-essential + +# Fedora/Rocky +sudo dnf groupinstall 'Development Tools' +``` + +### `pnpm: command not found` + +```bash +npm install -g pnpm +``` + +### Test schlägt fehl mit `only one instance allowed` +Das `shimLoaded`-Flag in `netquery` ist prozessweit. Tests einzeln ausführen: + +```bash +go test -v -count=1 -run TestNetqueryEndpointPathsPresent ./service/netquery/ +``` diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..b3abfb7f5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,46 @@ +# Changelog — portmasterpro + +All notable changes to this fork relative to upstream [safing/portmaster](https://github.com/safing/portmaster). +Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follow SemVer; pre-releases carry a `-rcN` suffix. + +## [Unreleased] + +### Changed +- Merged upstream `development` up to `21a2b064` (2.2.3 release line: updates path-traversal fix, + profile lookup/geo-rule fixes, iptables crash-safety, UI fixes, tray icon OS theme). +- Release workflow now creates the GitHub release automatically on `v*` tag push (pre-release + when the tag contains `-`), with notes taken from this changelog. + +### Added +- `CHANGELOG.md`, `RELEASE.md` (release checklist) and a scheduled upstream-sync workflow that + opens a pull request when upstream `development` has new commits. + +## [0.1.0-rc1] - 2026-10-01 + +First public release candidate. + +### Removed +- SPN (Safing Privacy Network), Safing account/login, subscription and feature gating. +- Telemetry / cloud sync (`service/sync` is a no-op). +- SPN navigation, `/spn` route, login/subscribe header, upsell widgets and "Portmaster Plus/Pro" + copy in the Angular UI; SPN entries in the tray menu. + +### Changed +- Network History and Bandwidth Visibility are available locally for everyone; history follows the + per-app setting. +- Upstream **software** update checks are opt-in (`core/automaticUpdates=false`): upstream + binaries would replace this build. Intelligence data updates (filter lists, GeoIP) stay enabled. +- `spn/access` reduced to an offline compatibility shim so remaining SPN packages compile but are + never started. + +### Added +- `no-telemetry-ci.yml`: full Go build/vet/test, race checks, Angular production build and guards + against account/telemetry endpoints in Go sources and the built UI bundle. +- Linux cross-build of the Windows NSIS installer (`packaging/windows/render_nsis_linux.py`) and the + `release-windows-installer.yml` workflow. +- `BUILDING.md` with the full build, test and installer flow. + +### Security +- No connection to `account.safing.io`; the only remaining upstream endpoint is + `updates.safing.io` for intelligence data (and, if enabled, binary update checks). +- Installer and binaries are unsigned; the kernel driver is Safing's signed stable driver (2.2.3). diff --git a/Earthfile b/Earthfile index 0de1a9dcc..987929bd4 100644 --- a/Earthfile +++ b/Earthfile @@ -4,7 +4,7 @@ VERSION 0.8 # Usage example: earthly --build-arg custom_version="1.2.3" + ARG --global custom_version = "" -ARG --global go_version = 1.26 +ARG --global go_version = 1.27 ARG --global node_version = 18 ARG --global rust_version = 1.89 ARG --global tauri_version = "2.2.5" diff --git a/README.md b/README.md index 81498a102..e70307ae0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,16 @@ +> ## portmasterpro — privacy-focused fork +> This repository is a fork of [safing/portmaster](https://github.com/safing/portmaster) **without SPN, Safing accounts, +> subscriptions or telemetry**. Network History and Bandwidth Visibility work locally for everyone. +> Upstream binary update checks are off by default (upstream binaries would replace this build); filter lists and +> GeoIP data still update from `updates.safing.io`. +> +> - **Download:** [Releases](https://github.com/0n113/portmasterpro/releases) (Windows x64 installer; unsigned → SmartScreen warning) +> - **Build & test:** [BUILDING.md](BUILDING.md) · **Changes:** [CHANGELOG.md](CHANGELOG.md), [desktop/CHANGES.md](desktop/CHANGES.md) · **Release process:** [RELEASE.md](RELEASE.md) +> - **Branches:** `no-spn-no-telemetry` (fork mainline), `release-candidate/*` (frozen RCs), `development` (upstream mirror) +> - The kernel driver is Safing's signed stable driver, unchanged. Not affiliated with or endorsed by Safing. +> +> The original upstream README follows. + # Get Peace of Mind
with [Easy Privacy](https://safing.io/) Portmaster is a free and open-source application firewall that does the heavy lifting for you. diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 000000000..9a424c0db --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,41 @@ +# Release-Checkliste (portmasterpro) + +Ziel: reproduzierbares, geprüftes Release ohne Überraschungen. Alle Punkte abhaken. + +## 1 · Code einfrieren +- [ ] Upstream `development` gemergt (`git fetch upstream && git merge upstream/development`), Konflikte gelöst, keine SPN/Account-Rückstände: + `grep -RIn 'account.safing.io\|/v1/spn/account\|/v1/account/features' service spn desktop/angular/projects` → leer +- [ ] `go build ./... && go vet ./... && go test -short -count=1 ./...` lokal grün (bekannte Umgebungsfehler laut BUILDING.md §5 ausgenommen) +- [ ] `desktop/angular`: `npm ci && npm run build` grün, Bundle-Guard leer (BUILDING.md §7) +- [ ] `CHANGELOG.md`: Abschnitt `## [X.Y.Z] - YYYY-MM-DD` aus `[Unreleased]` erzeugt +- [ ] Version gesetzt: `desktop/tauri/src-tauri/Cargo.toml` (`version = "X.Y.Z"`) und `Cargo.lock` (Paket `portmaster`) +- [ ] `release-candidate/X.Y.Z` Branch vom Stand erstellt, PR gegen `development` offen, **alle** Workflows grün + (No-Telemetry CI, Go, Angular, Windows Kernel Extension, Tauri) + +## 2 · Release Candidate +- [ ] Tag `vX.Y.Z-rcN` auf den eingefrorenen Commit pushen → Workflow erstellt Pre-Release + Assets automatisch +- [ ] Installer auf einer **echten Windows-Maschine** testen: + - [ ] Installation über bestehende Portmaster-/portmasterpro-Installation (Einstellungen bleiben) + - [ ] Dienst `PortmasterCore` startet, Treiber lädt (Log: `windowskext2`), UI verbindet + - [ ] Network History bleibt über Neustart erhalten; Bandbreiten-Charts füllen sich + - [ ] Keine Verbindung zu `account.safing.io`; nur `updates.safing.io` für Intel-Daten + - [ ] Intel-Update läuft durch (`filterlists: ... update complete`) + - [ ] Deinstallation entfernt Dienst, Treiber und Autostart-Eintrag +- [ ] Linux-Core-Smoke (`--disable-interception`, unprivilegiert): alle Module starten/stoppen sauber +- [ ] Mindestens 7 Tage Betrieb ohne Blocker-Report + +## 3 · Full Release +- [ ] Nur Fixes seit RC, kein neues Feature; letzte Fixes als `-rcN+1` erneut durchlaufen +- [ ] Tag `vX.Y.Z` (ohne Suffix) pushen → Workflow erstellt das finale Release +- [ ] Release-Seite prüfen: 5 Assets, `SHA256SUMS.txt` stimmt mit lokal geprüftem Installer überein +- [ ] PR nach `development` mergen (oder Default-Branch auf die Fork-Mainline setzen, siehe unten) +- [ ] Projekt-Wiki/Memory aktualisieren + +## Hinweise +- GitHub startet `workflow_dispatch`- und `schedule`-Workflows nur vom **Default-Branch**. Solange `development` + der Upstream-Spiegel ist, müssen Workflow-Änderungen dorthin gespiegelt werden. Empfehlung: Default-Branch + auf die Fork-Mainline umstellen (z. B. `main` = heutiger `no-spn-no-telemetry`). +- Upstream-Treiber: Split Tunnel benötigt einen neueren signierten Kext als Stable 2.2.3. Erst aktivieren, + wenn Upstream einen passenden signierten Treiber veröffentlicht hat. +- Signatur: ohne Code-Signing-Zertifikat warnt SmartScreen. Option: eigenes Zertifikat + (`packaging/windows/sign_binaries_in_dist.ps1`) — der Kext muss weiterhin der signierte Upstream-Treiber bleiben. diff --git a/assets/data/img/spn-feature-carousel/access-regional-content-easily.png b/assets/data/img/spn-feature-carousel/access-regional-content-easily.png deleted file mode 100644 index a90eba8e6..000000000 Binary files a/assets/data/img/spn-feature-carousel/access-regional-content-easily.png and /dev/null differ diff --git a/assets/data/img/spn-feature-carousel/built-from-the-ground-up.png b/assets/data/img/spn-feature-carousel/built-from-the-ground-up.png deleted file mode 100644 index bb8c0d6aa..000000000 Binary files a/assets/data/img/spn-feature-carousel/built-from-the-ground-up.png and /dev/null differ diff --git a/assets/data/img/spn-feature-carousel/bye-bye-vpns.png b/assets/data/img/spn-feature-carousel/bye-bye-vpns.png deleted file mode 100644 index e3bb65a6e..000000000 Binary files a/assets/data/img/spn-feature-carousel/bye-bye-vpns.png and /dev/null differ diff --git a/assets/data/img/spn-feature-carousel/easily-control-your-privacy.png b/assets/data/img/spn-feature-carousel/easily-control-your-privacy.png deleted file mode 100644 index 0d386b5f1..000000000 Binary files a/assets/data/img/spn-feature-carousel/easily-control-your-privacy.png and /dev/null differ diff --git a/assets/data/img/spn-feature-carousel/multiple-identities-for-each-app.png b/assets/data/img/spn-feature-carousel/multiple-identities-for-each-app.png deleted file mode 100644 index b5082f73f..000000000 Binary files a/assets/data/img/spn-feature-carousel/multiple-identities-for-each-app.png and /dev/null differ diff --git a/assets/data/img/spn-login.png b/assets/data/img/spn-login.png deleted file mode 100644 index 4a5541fba..000000000 Binary files a/assets/data/img/spn-login.png and /dev/null differ diff --git a/base/api/authentication.go b/base/api/authentication.go index 2ea09f7aa..788c142c4 100644 --- a/base/api/authentication.go +++ b/base/api/authentication.go @@ -335,8 +335,13 @@ func checkAPIKey(r *http.Request) *AuthToken { // Check if the provided API key exists. token, ok := apiKeys[key] if !ok { + // The key is client-controlled and may be shorter than the logged prefix. + keyPrefix := key + if len(keyPrefix) > 4 { + keyPrefix = keyPrefix[:4] + } log.Tracer(r.Context()).Tracef( - "api: provided api key %s... is unknown", key[:4], + "api: provided api key %s... is unknown", keyPrefix, ) return nil } diff --git a/base/api/authentication_test.go b/base/api/authentication_test.go index 40ce0efe7..95ee5da1c 100644 --- a/base/api/authentication_test.go +++ b/base/api/authentication_test.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net/http" + "net/http/httptest" "testing" "github.com/stretchr/testify/assert" @@ -177,6 +178,32 @@ func TestPermissions(t *testing.T) { } } +func TestCheckAPIKeyShortUnknownKey(t *testing.T) { + t.Parallel() + + for _, header := range []string{ + "Bearer ", + "Bearer a", + "Bearer abc", + "Basic ", // Invalid base64: empty user and pass. + "Basic YTo=", // "a:" + } { + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.Header.Set("Authorization", header) + + func() { + defer func() { + if v := recover(); v != nil { + t.Errorf("checkAPIKey panicked with Authorization %q: %v", header, v) + } + }() + if token := checkAPIKey(r); token != nil { + t.Errorf("checkAPIKey returned a token for unknown key %q", header) + } + }() + } +} + func TestPermissionDefinitions(t *testing.T) { t.Parallel() diff --git a/base/api/database.go b/base/api/database.go index 55edac08d..73cda0967 100644 --- a/base/api/database.go +++ b/base/api/database.go @@ -4,8 +4,10 @@ import ( "bytes" "errors" "fmt" + "net" "net/http" "sync" + "time" "github.com/gorilla/websocket" "github.com/tevino/abool" @@ -40,6 +42,30 @@ const ( var ( dbAPISeperatorBytes = []byte(dbAPISeperator) dbCompatibilityPermission = PermitAdmin + + // dbAPIWriteTimeout is the maximum time a single websocket message write + // may take. It is deliberately generous: it only exists to detect a peer + // that keeps the connection open but stopped reading (frozen process, + // half-open TCP), which would otherwise block the writer forever. + dbAPIWriteTimeout = 60 * time.Second + + // dbAPIReadLimit is the maximum size of a single message a client may send + // over the database websocket API. Without a limit, a single message of + // arbitrary size is buffered completely in memory. + // + // The largest legitimate client messages are record creates, updates and + // inserts (opID|cmd|key|), eg. profiles with their settings or + // config values. These are in the range of kilobytes up to a few hundred + // kilobytes for very large rule lists; profile icons are not part of the + // profile record, they are uploaded via the HTTP API (profile/icon) and + // only referenced by file name. + // + // The limit is deliberately generous and the same as the HTTP API request + // body limit (maxRequestBodySize), so that anything that can be written + // via the HTTP API can also be written via the websocket API. It only + // exists to keep a single client from exhausting the memory of the + // service. It is a variable only so that tests can lower it. + dbAPIReadLimit int64 = maxRequestBodySize ) func init() { @@ -104,6 +130,9 @@ func startDatabaseWebsocketAPI(w http.ResponseWriter, r *http.Request) { http.Error(w, errMsg, http.StatusBadRequest) return } + // Limit the size of incoming messages. When exceeded, the connection is + // closed with 1009 (message too big) and the reader fails. + wsConn.SetReadLimit(dbAPIReadLimit) newDBAPI := &DatabaseWebsocketAPI{ DatabaseAPI: DatabaseAPI{ @@ -118,9 +147,7 @@ func startDatabaseWebsocketAPI(w http.ResponseWriter, r *http.Request) { conn: wsConn, } - newDBAPI.sendBytes = func(data []byte) { - newDBAPI.sendQueue <- data - } + newDBAPI.sendBytes = newDBAPI.queueMessage module.mgr.Go("database api handler", newDBAPI.handler) module.mgr.Go("database api writer", newDBAPI.writer) @@ -128,6 +155,17 @@ func startDatabaseWebsocketAPI(w http.ResponseWriter, r *http.Request) { log.Tracer(r.Context()).Infof("api request: init websocket %s %s", r.RemoteAddr, r.RequestURI) } +// queueMessage queues a message for sending to the client. +// If the connection is shutting down, the message is dropped. Without this, +// senders would block forever on a full queue after the writer has exited, +// leaking the goroutine and the queries and subscriptions it holds. +func (api *DatabaseWebsocketAPI) queueMessage(data []byte) { + select { + case api.sendQueue <- data: + case <-api.shutdownSignal: + } +} + func (api *DatabaseWebsocketAPI) handler(_ *mgr.WorkerCtx) error { defer func() { _ = api.shutdown(nil) @@ -165,8 +203,20 @@ func (api *DatabaseWebsocketAPI) writer(ctx *mgr.WorkerCtx) error { } // log.Tracef("api: sending %s", string(*msg)) + // Set a deadline for every single write, so that a peer that stopped + // reading cannot block the writer (and everything feeding the send + // queue) forever. After a write timeout the connection is corrupt and + // must not be used anymore: shutdown closes it. + err = api.conn.SetWriteDeadline(time.Now().Add(dbAPIWriteTimeout)) + if err != nil { + return api.shutdown(err) + } err = api.conn.WriteMessage(websocket.BinaryMessage, data) if err != nil { + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + err = fmt.Errorf("write timed out after %s, closing connection: %w", dbAPIWriteTimeout, err) + } return api.shutdown(err) } } @@ -507,6 +557,9 @@ func (api *DatabaseAPI) handleQsub(opID []byte, queryText string) { } ok = api.processQuery(opID, q) if !ok { + // The subscription was already registered with the database and must + // be canceled, or it will be fed (and matched against) forever. + _ = sub.Cancel() return } api.processSub(opID, sub) @@ -605,7 +658,17 @@ func (api *DatabaseAPI) handleInsert(opID []byte, key string, data []byte) { return } + // The database may return a record instance that is shared with other + // users, so it may only be modified while holding its lock. + // It must be unlocked again before saving, as Put locks it itself. + r.Lock() acc := r.GetAccessor(r) + if acc == nil { + // Eg. wrapped records in a format other than JSON have no accessor. + r.Unlock() + api.send(opID, dbMsgTypeError, "record does not support inserting values", nil) + return + } result := gjson.ParseBytes(data) anythingPresent := false @@ -627,6 +690,7 @@ func (api *DatabaseAPI) handleInsert(opID []byte, key string, data []byte) { insertError = acc.Set(key.String(), value.Value()) return insertError == nil }) + r.Unlock() if insertError != nil { api.send(opID, dbMsgTypeError, insertError.Error(), nil) diff --git a/base/api/database_test.go b/base/api/database_test.go new file mode 100644 index 000000000..db092310d --- /dev/null +++ b/base/api/database_test.go @@ -0,0 +1,322 @@ +package api + +import ( + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/tevino/abool" + + "github.com/safing/portmaster/base/database" + "github.com/safing/portmaster/base/database/iterator" + _ "github.com/safing/portmaster/base/database/storage/hashmap" +) + +var initTestDatabaseOnce sync.Once + +// initTestDatabase initializes the database system with a hashmap database +// named "api-test" for tests. +func initTestDatabase(t *testing.T) { + t.Helper() + + initTestDatabaseOnce.Do(func() { + dir := filepath.Join(t.TempDir(), "databases") + err := database.Initialize(dir) + if err != nil { + panic(err) + } + _, err = database.Register(&database.Database{ + Name: "api-test", + Description: "Unit Test Database", + StorageType: "hashmap", + }) + if err != nil { + panic(err) + } + }) +} + +// TestDatabaseAPIInsertLocksRecord checks that the insert operation modifies +// the record only while holding its lock, as the database may hand out the +// same record instance to other users. +func TestDatabaseAPIInsertLocksRecord(t *testing.T) { + t.Parallel() + initTestDatabase(t) + + db := database.NewInterface(nil) + r := &actionTestRecord{Msg: "initial"} + r.SetKey("api-test:insert-lock") + err := db.Put(r) + if err != nil { + t.Fatal(err) + } + + replies := make(chan string, 100) + api := &DatabaseAPI{ + shutdownSignal: make(chan struct{}), + shuttingDown: abool.NewBool(false), + db: db, + sendBytes: func(data []byte) { + replies <- string(data) + }, + } + + // Concurrently read the record under its lock, like any other user of + // the shared record does. + stop := make(chan struct{}) + readerDone := make(chan struct{}) + go func() { + defer close(readerDone) + for { + select { + case <-stop: + return + default: + } + _, marshalErr := MarshalRecord(r, true) + if marshalErr != nil { + t.Error(marshalErr) + return + } + } + }() + + for i := range 20 { + api.handleInsert([]byte("1"), "api-test:insert-lock", fmt.Appendf(nil, `{"Msg":"insert %d"}`, i)) + if reply := <-replies; reply != "1|success" { + t.Fatalf("unexpected reply: %s", reply) + } + } + close(stop) + <-readerDone + + r.Lock() + defer r.Unlock() + if r.Msg != "insert 19" { + t.Fatalf("unexpected record value: %q", r.Msg) + } +} + +// TestDatabaseWebsocketQueueMessageShutdown checks that senders do not block +// forever on a full send queue after the connection was shut down. +func TestDatabaseWebsocketQueueMessageShutdown(t *testing.T) { + t.Parallel() + + wsAPI := &DatabaseWebsocketAPI{ + DatabaseAPI: DatabaseAPI{ + shutdownSignal: make(chan struct{}), + shuttingDown: abool.NewBool(false), + }, + sendQueue: make(chan []byte, 1), + } + + // Fill the queue, there is no writer. + wsAPI.queueMessage([]byte("a")) + + done := make(chan struct{}) + go func() { + defer close(done) + wsAPI.queueMessage([]byte("b")) + }() + + // The sender must block while the connection is alive. + select { + case <-done: + t.Fatal("sender did not wait for space in the send queue") + case <-time.After(50 * time.Millisecond): + } + + // The sender must be released when the connection shuts down. + close(wsAPI.shutdownSignal) + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("sender is still blocked after shutdown") + } +} + +// TestDatabaseWebsocketWriteTimeout checks that the websocket writer gives up +// on a peer that keeps the connection open but stopped reading, and shuts the +// connection down instead of blocking forever. +func TestDatabaseWebsocketWriteTimeout(t *testing.T) { //nolint:paralleltest // Modifies package variable. + oldTimeout := dbAPIWriteTimeout + dbAPIWriteTimeout = 200 * time.Millisecond + defer func() { dbAPIWriteTimeout = oldTimeout }() + + // Server side: upgrade and hand over the connection. + serverConns := make(chan *websocket.Conn, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upgrader := websocket.Upgrader{WriteBufferSize: 65536} + c, err := upgrader.Upgrade(w, r, nil) + if err != nil { + t.Error(err) + return + } + serverConns <- c + })) + defer srv.Close() + + // Client side: connect, but never read. + clientConn, resp, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + defer func() { _ = clientConn.Close() }() + + var serverConn *websocket.Conn + select { + case serverConn = <-serverConns: + case <-time.After(5 * time.Second): + t.Fatal("websocket upgrade did not complete") + } + + api := &DatabaseWebsocketAPI{ + DatabaseAPI: DatabaseAPI{ + queries: make(map[string]*iterator.Iterator), + subs: make(map[string]*database.Subscription), + shutdownSignal: make(chan struct{}), + shuttingDown: abool.NewBool(false), + }, + sendQueue: make(chan []byte, 100), + conn: serverConn, + } + module.mgr.Go("database api writer test", api.writer) + + // Feed messages until the socket buffers are full and the writer blocks. + // The writer must then time out and shut the connection down. + msg := make([]byte, 1<<20) + giveUp := time.After(10 * time.Second) + for { + select { + case api.sendQueue <- msg: + case <-api.shutdownSignal: + if !api.shuttingDown.IsSet() { + t.Fatal("shutdown signal closed without shutting down") + } + return + case <-giveUp: + t.Fatal("websocket writer blocked on a peer that stopped reading") + } + } +} + +// TestDatabaseAPIInsertWithoutAccessor checks that inserting into a record +// that does not provide an accessor (eg. a wrapped non-JSON record) is +// rejected instead of panicking. Database API operations run in their own +// goroutines, so a panic there crashes the whole process. +func TestDatabaseAPIInsertWithoutAccessor(t *testing.T) { + t.Parallel() + initTestDatabase(t) + + replies := make(chan string, 100) + api := &DatabaseAPI{ + shutdownSignal: make(chan struct{}), + shuttingDown: abool.NewBool(false), + db: database.NewInterface(nil), + sendBytes: func(data []byte) { + replies <- string(data) + }, + } + + // Store a CBOR record (format identifier "C") through the API. + api.handlePut([]byte("1"), "api-test:insert-cbor", []byte("C\xa0"), false) + if reply := <-replies; reply != "1|success" { + t.Fatalf("unexpected reply: %s", reply) + } + + // Try to insert a value into it. + func() { + defer func() { + if v := recover(); v != nil { + t.Fatalf("insert panicked: %v", v) + } + }() + api.handleInsert([]byte("2"), "api-test:insert-cbor", []byte(`{"a":1}`)) + }() + if reply := <-replies; !strings.HasPrefix(reply, "2|error|") { + t.Fatalf("unexpected reply: %s", reply) + } +} + +// TestDatabaseWebsocketReadLimit checks that the database websocket API +// closes the connection on a client message exceeding the read limit, while +// large legitimate messages are still accepted. +func TestDatabaseWebsocketReadLimit(t *testing.T) { //nolint:paralleltest // Modifies package variable. + initTestDatabase(t) + + // The production limit must not be smaller than the HTTP API body limit. + if dbAPIReadLimit < maxRequestBodySize { + t.Fatalf("websocket read limit %d is smaller than the HTTP request body limit %d", dbAPIReadLimit, maxRequestBodySize) + } + + // Lower the limit to keep the test fast. + oldLimit := dbAPIReadLimit + dbAPIReadLimit = 2 << 20 // 2MiB + defer func() { dbAPIReadLimit = oldLimit }() + + srv := httptest.NewServer(http.HandlerFunc(startDatabaseWebsocketAPI)) + defer srv.Close() + + clientConn, resp, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + defer func() { _ = clientConn.Close() }() + + // updateMsg returns an update message of exactly the given size. + updateMsg := func(opID string, size int) []byte { + prefix := opID + `|update|api-test:ws-read-limit|J{"Msg":"` + suffix := `"}` + return []byte(prefix + strings.Repeat("a", size-len(prefix)-len(suffix)) + suffix) + } + + // A large but legitimate message (1MiB) is accepted. + err = clientConn.WriteMessage(websocket.BinaryMessage, updateMsg("1", 1<<20)) + if err != nil { + t.Fatal(err) + } + _ = clientConn.SetReadDeadline(time.Now().Add(10 * time.Second)) + _, reply, err := clientConn.ReadMessage() + if err != nil { + t.Fatalf("1MiB message: connection failed: %s", err) + } + if string(reply) != "1|"+dbMsgTypeSuccess { + t.Fatalf("1MiB message: unexpected reply: %s", reply) + } + + // A message slightly over the limit closes the connection. + // Write in the background, as the server may stop reading mid-message. + writeDone := make(chan struct{}) + go func() { + defer close(writeDone) + _ = clientConn.WriteMessage(websocket.BinaryMessage, updateMsg("2", int(dbAPIReadLimit)+1)) + }() + _ = clientConn.SetReadDeadline(time.Now().Add(10 * time.Second)) + _, reply, err = clientConn.ReadMessage() + switch { + case err == nil: + t.Errorf("oversized message: connection still open, got reply: %.100s", reply) + case websocket.IsCloseError(err, websocket.CloseMessageTooBig): + // Expected. + default: + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + t.Errorf("oversized message: connection was not closed: %s", err) + } else { + // The connection may also be reset before the close message is read. + t.Logf("oversized message: connection closed without close message: %s", err) + } + } + _ = clientConn.Close() + <-writeDone +} diff --git a/base/api/endpoints.go b/base/api/endpoints.go index 6c8be79ec..0628f81bd 100644 --- a/base/api/endpoints.go +++ b/base/api/endpoints.go @@ -21,7 +21,7 @@ import ( // Endpoint describes an API Endpoint. // Path and at least one permission are required. // As is exactly one function. -type Endpoint struct { //nolint:maligned +type Endpoint struct { // Name is the human reabable name of the endpoint. Name string // Description is the human readable description and documentation of the endpoint. @@ -460,7 +460,7 @@ func (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { case e.RecordFunc != nil: var rec record.Record rec, err = e.RecordFunc(apiRequest) - if err == nil && r != nil { + if err == nil && rec != nil { responseData, err = MarshalRecord(rec, false) } @@ -504,18 +504,27 @@ func (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +// maxRequestBodySize is the maximum accepted size of a request body. +const maxRequestBodySize = 20000000 // 20MB + func readBody(w http.ResponseWriter, r *http.Request) (inputData []byte, ok bool) { // Check for too long content in order to prevent death. - if r.ContentLength > 20000000 { // 20MB + if r.ContentLength > maxRequestBodySize { http.Error(w, "too much input data", http.StatusRequestEntityTooLarge) return nil, false } // Read and close body. - inputData, err := io.ReadAll(r.Body) + // The declared content length may be missing (eg. with chunked transfer + // encoding), so also limit the actual amount of data read. + inputData, err := io.ReadAll(io.LimitReader(r.Body, maxRequestBodySize+1)) if err != nil { http.Error(w, "failed to read body"+err.Error(), http.StatusInternalServerError) return nil, false } + if len(inputData) > maxRequestBodySize { + http.Error(w, "too much input data", http.StatusRequestEntityTooLarge) + return nil, false + } return inputData, true } diff --git a/base/api/endpoints_debug.go b/base/api/endpoints_debug.go index 06de4cd5a..c24cd72c6 100644 --- a/base/api/endpoints_debug.go +++ b/base/api/endpoints_debug.go @@ -135,7 +135,7 @@ func ping(ar *Request) (msg string, err error) { // ready checks if Portmaster has completed starting. func ready(ar *Request) (msg string, err error) { - if module.instance.Ready() { + if !module.instance.Ready() { return "", ErrorWithStatus(errors.New("portmaster is not ready, reload (F5) to try again"), http.StatusTooEarly) } return "Portmaster is ready.", nil diff --git a/base/api/endpoints_debug_test.go b/base/api/endpoints_debug_test.go new file mode 100644 index 000000000..9079a14cb --- /dev/null +++ b/base/api/endpoints_debug_test.go @@ -0,0 +1,41 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestReadyEndpoint checks that the ready endpoint reports success only once +// Portmaster has completed starting, and 425 Too Early before that. +func TestReadyEndpoint(t *testing.T) { //nolint:paralleltest // Modifies the shared test instance. + stub, ok := module.instance.(*testInstance) + if !ok { + t.Fatalf("unexpected test instance type %T", module.instance) + } + defer stub.notReady.Store(false) + + testHandler := &mainHandler{ + mux: mainMux, + } + get := func() *httptest.ResponseRecorder { + w := httptest.NewRecorder() + testHandler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, apiV1Path+"ready", nil)) + return w + } + + // Still starting. + stub.notReady.Store(true) + w := get() + if w.Code != http.StatusTooEarly { + t.Errorf("not ready: expected status %d, got %d: %s", http.StatusTooEarly, w.Code, strings.TrimSpace(w.Body.String())) + } + + // Started. + stub.notReady.Store(false) + w = get() + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Portmaster is ready.") { + t.Errorf("ready: expected status %d with ready message, got %d: %s", http.StatusOK, w.Code, strings.TrimSpace(w.Body.String())) + } +} diff --git a/base/api/endpoints_test.go b/base/api/endpoints_test.go index d24ead0ca..f6147239a 100644 --- a/base/api/endpoints_test.go +++ b/base/api/endpoints_test.go @@ -2,6 +2,9 @@ package api import ( "errors" + "io" + "net/http" + "net/http/httptest" "sync" "testing" @@ -115,6 +118,75 @@ func TestEndpoints(t *testing.T) { assert.HTTPBodyContains(t, testHandler.ServeHTTP, "GET", apiV1Path+"test/record-err", nil, failedMsg) } +// TestEndpointRecordFuncNilRecord checks that a RecordFunc returning neither +// a record nor an error results in an empty response, like the other handler +// types, instead of a panic. +func TestEndpointRecordFuncNilRecord(t *testing.T) { + t.Parallel() + + testHandler := &mainHandler{ + mux: mainMux, + } + + assert.NoError(t, RegisterEndpoint(Endpoint{ + Path: "test/record-nil", + Read: PermitAnyone, + RecordFunc: func(_ *Request) (r record.Record, err error) { + return nil, nil + }, + })) + + r := httptest.NewRequest(http.MethodGet, apiV1Path+"test/record-nil", nil) + w := httptest.NewRecorder() + testHandler.ServeHTTP(w, r) + assert.Equal(t, http.StatusNoContent, w.Code, "body: %s", w.Body.String()) + assert.Empty(t, w.Body.String()) +} + +// zeroReader endlessly returns zero bytes. +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +func TestEndpointBodyLimitWithoutContentLength(t *testing.T) { + t.Parallel() + + testHandler := &mainHandler{ + mux: mainMux, + } + + var receivedBytes int + assert.NoError(t, RegisterEndpoint(Endpoint{ + Path: "test/body-limit", + Write: PermitAnyone, + ActionFunc: func(ar *Request) (msg string, err error) { + receivedBytes = len(ar.InputData) + return successMsg, nil + }, + })) + + // A body without a declared length (as with chunked transfer encoding) + // must not bypass the body size limit. + body := io.LimitReader(zeroReader{}, maxRequestBodySize+1) + r := httptest.NewRequest(http.MethodPost, apiV1Path+"test/body-limit", body) + r.ContentLength = -1 + w := httptest.NewRecorder() + testHandler.ServeHTTP(w, r) + assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code, "received %d bytes", receivedBytes) + + // A body at the limit is still accepted. + body = io.LimitReader(zeroReader{}, maxRequestBodySize) + r = httptest.NewRequest(http.MethodPost, apiV1Path+"test/body-limit", body) + r.ContentLength = -1 + w = httptest.NewRecorder() + testHandler.ServeHTTP(w, r) + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, maxRequestBodySize, receivedBytes) +} + func TestActionRegistration(t *testing.T) { t.Parallel() diff --git a/base/api/init_test.go b/base/api/init_test.go index a7e04c51f..7c36dac00 100644 --- a/base/api/init_test.go +++ b/base/api/init_test.go @@ -1,6 +1,7 @@ package api import ( + "sync/atomic" "testing" "github.com/safing/portmaster/base/config" @@ -8,6 +9,10 @@ import ( type testInstance struct { config *config.Config + + // notReady makes Ready report false. Tests changing it must not run in + // parallel. + notReady atomic.Bool } var _ instance = &testInstance{} @@ -19,7 +24,7 @@ func (stub *testInstance) Config() *config.Config { func (stub *testInstance) SetCmdLineOperation(f func() error) {} func (stub *testInstance) Ready() bool { - return true + return !stub.notReady.Load() } func TestMain(m *testing.M) { diff --git a/base/api/router.go b/base/api/router.go index 53c37495f..cd5a685ef 100644 --- a/base/api/router.go +++ b/base/api/router.go @@ -26,10 +26,16 @@ var ( // mainMux is the main mux router. mainMux = mux.NewRouter() + // serverReadHeaderTimeout is the maximum time a client may take to send + // the request headers. It protects against slow header (slowloris) + // connections. There are deliberately no read, write or idle timeouts, as + // these would break long-lived websocket connections. + // It is a variable only so that tests can lower it. + serverReadHeaderTimeout = 10 * time.Second + // server is the main server. - server = &http.Server{ - ReadHeaderTimeout: 10 * time.Second, - } + server = newServer() + handlerLock sync.RWMutex allowedDevCORSOrigins = []string{ @@ -38,6 +44,13 @@ var ( } ) +// newServer returns a new, unstarted API HTTP server. +func newServer() *http.Server { + return &http.Server{ + ReadHeaderTimeout: serverReadHeaderTimeout, + } +} + // RegisterHandler registers a handler with the API endpoint. func RegisterHandler(path string, handler http.Handler) *mux.Route { handlerLock.Lock() @@ -149,7 +162,7 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error { w.Header().Set( "Content-Security-Policy", "default-src 'self'; "+ - "connect-src https://*.safing.io 'self'; "+ + "connect-src 'self'; "+ "style-src 'self' 'unsafe-inline'; "+ "img-src 'self' data: blob:", ) @@ -227,7 +240,12 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error { // See github.com/gorilla/mux.ServeHTTP for reference. var match mux.RouteMatch var handler http.Handler - if mh.mux.Match(r, &match) { + // Routes may be registered while the server is running, so guard the + // route table against concurrent modification. + handlerLock.RLock() + matched := mh.mux.Match(r, &match) + handlerLock.RUnlock() + if matched { handler = match.Handler apiRequest.Route = match.Route apiRequest.URLVars = match.Vars diff --git a/base/api/router_test.go b/base/api/router_test.go new file mode 100644 index 000000000..5bc04896d --- /dev/null +++ b/base/api/router_test.go @@ -0,0 +1,61 @@ +package api + +import ( + "io" + "net" + "net/http" + "testing" + "time" +) + +// TestServerReadHeaderTimeout checks that the API server closes connections +// that do not complete their request headers in time (slowloris). +func TestServerReadHeaderTimeout(t *testing.T) { //nolint:paralleltest // Modifies package variable. + // The server used for serving must be configured with the timeout. + if server.ReadHeaderTimeout != serverReadHeaderTimeout || server.ReadHeaderTimeout <= 0 { + t.Fatalf("API server has read header timeout %s, expected %s", server.ReadHeaderTimeout, serverReadHeaderTimeout) + } + + // Run a server configured the same way, with a lower timeout. + oldTimeout := serverReadHeaderTimeout + serverReadHeaderTimeout = 200 * time.Millisecond + defer func() { serverReadHeaderTimeout = oldTimeout }() + + srv := newServer() + srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Serve(ln) }() + defer func() { _ = srv.Close() }() + + // Start measuring before connecting: the server starts the timeout when it + // accepts the connection, which may happen before Dial returns. + start := time.Now() + conn, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + + // Send an incomplete request header and then stall. + _, err = io.WriteString(conn, "GET /api/v1/ping HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Slow: ") + if err != nil { + t.Fatal(err) + } + + // The server must close the connection after the timeout. + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + _, err = io.Copy(io.Discard, conn) + elapsed := time.Since(start) + if err != nil { + t.Fatalf("connection was not closed by the server after %s: %s", elapsed, err) + } + if elapsed < serverReadHeaderTimeout { + t.Fatalf("connection was closed after %s, before the read header timeout", elapsed) + } + t.Logf("connection closed by the server after %s", elapsed) +} diff --git a/base/apprise/notify.go b/base/apprise/notify.go index 2040171c7..57b5e38b5 100644 --- a/base/apprise/notify.go +++ b/base/apprise/notify.go @@ -79,6 +79,9 @@ const ( FormatHTML MsgFormat = "html" ) +// maxErrorBodySize is the maximum amount of bytes read from an error response. +const maxErrorBodySize = 64 * 1024 + type errorResponse struct { Error string `json:"error"` } @@ -122,7 +125,9 @@ func (n *Notifier) Send(ctx context.Context, m *Message) error { return nil default: // Try to tease body contents. - if body, err := io.ReadAll(resp.Body); err == nil && len(body) > 0 { + // Limit the read, as the body is only used for the error message. + body, err := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize)) + if err == nil && len(body) > 0 { // Try to parse json response. errorResponse := &errorResponse{} if err := json.Unmarshal(body, errorResponse); err == nil && errorResponse.Error != "" { diff --git a/base/apprise/notify_test.go b/base/apprise/notify_test.go new file mode 100644 index 000000000..041e0a4cd --- /dev/null +++ b/base/apprise/notify_test.go @@ -0,0 +1,69 @@ +package apprise + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestSendErrorWithEndlessBody(t *testing.T) { + t.Parallel() + + // Server that responds with an error and a body that never ends. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + chunk := []byte(strings.Repeat("x", 4096)) + for r.Context().Err() == nil { + _, err := w.Write(chunk) + if err != nil { + return + } + } + })) + t.Cleanup(srv.Close) + + n := &Notifier{ + URL: srv.URL, + AllowUntagged: true, + } + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + errs := make(chan error, 1) + go func() { + errs <- n.Send(ctx, &Message{Body: "test"}) + }() + + select { + case err := <-errs: + if err == nil { + t.Fatal("expected an error") + } + if !strings.Contains(err.Error(), "500") { + t.Fatalf("unexpected error: %s", err) + } + case <-time.After(5 * time.Second): + cancel() + t.Fatal("Send did not return: error response body is read without limit") + } +} + +func TestSendErrorMessage(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"no such tag"}`)) + })) + t.Cleanup(srv.Close) + + n := &Notifier{URL: srv.URL, DefaultTag: "tag"} + err := n.Send(context.Background(), &Message{Body: "test"}) + if err == nil || !strings.Contains(err.Error(), "no such tag") { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/base/config/flatten_test.go b/base/config/flatten_test.go new file mode 100644 index 000000000..a77b35e75 --- /dev/null +++ b/base/config/flatten_test.go @@ -0,0 +1,18 @@ +package config + +import "testing" + +func TestFlattenDuplicateKeys(t *testing.T) { + t.Parallel() + + // Map order is random; repeat to catch order-dependent results. + for range 50 { + flat := Flatten(map[string]any{ + "core": map[string]any{"devMode": true}, + "core/devMode": false, + }) + if v, ok := flat["core/devMode"].(bool); !ok || v { + t.Fatalf("core/devMode = %v, want false (the flattened key wins)", flat["core/devMode"]) + } + } +} diff --git a/base/config/get-safe.go b/base/config/get-safe.go index f03d4532e..fcbf28fb6 100644 --- a/base/config/get-safe.go +++ b/base/config/get-safe.go @@ -1,112 +1,28 @@ package config -import "sync" - type safe struct{} // Concurrent makes concurrency safe get methods available. +// The regular GetAs* functions are concurrency safe as well; these methods are +// kept for compatibility and share the same lock-free implementation. var Concurrent = &safe{} // GetAsString returns a function that returns the wanted string with high performance. func (cs *safe) GetAsString(name string, fallback string) StringOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeString) - value := fallback - if valueCache != nil { - value = valueCache.stringVal - } - var lock sync.Mutex - - return func() string { - lock.Lock() - defer lock.Unlock() - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeString) - if valueCache != nil { - value = valueCache.stringVal - } else { - value = fallback - } - } - return value - } + return GetAsString(name, fallback) } -// GetAsStringArray returns a function that returns the wanted string with high performance. +// GetAsStringArray returns a function that returns the wanted string array with high performance. func (cs *safe) GetAsStringArray(name string, fallback []string) StringArrayOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeStringArray) - value := fallback - if valueCache != nil { - value = valueCache.stringArrayVal - } - var lock sync.Mutex - - return func() []string { - lock.Lock() - defer lock.Unlock() - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeStringArray) - if valueCache != nil { - value = valueCache.stringArrayVal - } else { - value = fallback - } - } - return value - } + return GetAsStringArray(name, fallback) } // GetAsInt returns a function that returns the wanted int with high performance. func (cs *safe) GetAsInt(name string, fallback int64) IntOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeInt) - value := fallback - if valueCache != nil { - value = valueCache.intVal - } - var lock sync.Mutex - - return func() int64 { - lock.Lock() - defer lock.Unlock() - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeInt) - if valueCache != nil { - value = valueCache.intVal - } else { - value = fallback - } - } - return value - } + return GetAsInt(name, fallback) } -// GetAsBool returns a function that returns the wanted int with high performance. +// GetAsBool returns a function that returns the wanted bool with high performance. func (cs *safe) GetAsBool(name string, fallback bool) BoolOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeBool) - value := fallback - if valueCache != nil { - value = valueCache.boolVal - } - var lock sync.Mutex - - return func() bool { - lock.Lock() - defer lock.Unlock() - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeBool) - if valueCache != nil { - value = valueCache.boolVal - } else { - value = fallback - } - } - return value - } + return GetAsBool(name, fallback) } diff --git a/base/config/get.go b/base/config/get.go index 3d41a2184..a89389e47 100644 --- a/base/config/get.go +++ b/base/config/get.go @@ -1,6 +1,10 @@ package config import ( + "sync/atomic" + + "github.com/tevino/abool" + "github.com/safing/portmaster/base/log" ) @@ -48,96 +52,68 @@ func getValueCache(name string, option *Option, requestedType OptionType) (*Opti return option, option.activeFallbackValue } -// GetAsString returns a function that returns the wanted string with high performance. -func GetAsString(name string, fallback string) StringOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeString) - value := fallback - if valueCache != nil { - value = valueCache.stringVal - } +// cachedValue is an immutable snapshot of an option value, valid as long as +// its validity flag is set. +type cachedValue[T any] struct { + valid *abool.AtomicBool + option *Option + value T +} - return func() string { - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeString) - if valueCache != nil { - value = valueCache.stringVal - } else { - value = fallback - } +// newCachedGetter returns a lock-free getter for the given option. +// The cached state is swapped atomically, so the returned function is safe +// for concurrent use and never exposes a torn string or slice value. +func newCachedGetter[T any](name string, optType OptionType, fallback T, extract func(*valueCache) T) func() T { + load := func(option *Option) *cachedValue[T] { + // Get the validity flag first, so that a change during loading + // invalidates the result and triggers another load. + c := &cachedValue[T]{ + valid: getValidityFlag(), + value: fallback, + } + var vc *valueCache + c.option, vc = getValueCache(name, option, optType) + if vc != nil { + c.value = extract(vc) } - return value + return c } -} -// GetAsStringArray returns a function that returns the wanted string with high performance. -func GetAsStringArray(name string, fallback []string) StringArrayOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeStringArray) - value := fallback - if valueCache != nil { - value = valueCache.stringArrayVal - } + var current atomic.Pointer[cachedValue[T]] + current.Store(load(nil)) - return func() []string { - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeStringArray) - if valueCache != nil { - value = valueCache.stringArrayVal - } else { - value = fallback - } + return func() T { + c := current.Load() + if !c.valid.IsSet() { + c = load(c.option) + current.Store(c) } - return value + return c.value } } +// GetAsString returns a function that returns the wanted string with high performance. +// The returned function is safe for concurrent use. +func GetAsString(name string, fallback string) StringOption { + return newCachedGetter(name, OptTypeString, fallback, func(vc *valueCache) string { return vc.stringVal }) +} + +// GetAsStringArray returns a function that returns the wanted string array with high performance. +// The returned function is safe for concurrent use. +func GetAsStringArray(name string, fallback []string) StringArrayOption { + return newCachedGetter(name, OptTypeStringArray, fallback, func(vc *valueCache) []string { return vc.stringArrayVal }) +} + // GetAsInt returns a function that returns the wanted int with high performance. +// The returned function is safe for concurrent use. func GetAsInt(name string, fallback int64) IntOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeInt) - value := fallback - if valueCache != nil { - value = valueCache.intVal - } - - return func() int64 { - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeInt) - if valueCache != nil { - value = valueCache.intVal - } else { - value = fallback - } - } - return value - } + return newCachedGetter(name, OptTypeInt, fallback, func(vc *valueCache) int64 { return vc.intVal }) } -// GetAsBool returns a function that returns the wanted int with high performance. +// GetAsBool returns a function that returns the wanted bool with high performance. +// The returned function is safe for concurrent use. func GetAsBool(name string, fallback bool) BoolOption { - valid := getValidityFlag() - option, valueCache := getValueCache(name, nil, OptTypeBool) - value := fallback - if valueCache != nil { - value = valueCache.boolVal - } - - return func() bool { - if !valid.IsSet() { - valid = getValidityFlag() - option, valueCache = getValueCache(name, option, OptTypeBool) - if valueCache != nil { - value = valueCache.boolVal - } else { - value = fallback - } - } - return value - } + return newCachedGetter(name, OptTypeBool, fallback, func(vc *valueCache) bool { return vc.boolVal }) } /* diff --git a/base/config/persistence.go b/base/config/persistence.go index 87fd9e91c..6f9a13531 100644 --- a/base/config/persistence.go +++ b/base/config/persistence.go @@ -1,14 +1,19 @@ package config import ( + "bytes" "encoding/json" "fmt" + "maps" "os" "path" + "path/filepath" + "slices" "strings" "sync" "github.com/safing/portmaster/base/log" + "github.com/safing/portmaster/base/utils" ) var ( @@ -58,32 +63,41 @@ func loadConfig(requireValidConfig bool) error { return nil } +// saveConfigLock serializes SaveConfig, so that a save that snapshotted older +// values can never overwrite the file after a save with newer values. +var saveConfigLock sync.Mutex + // SaveConfig saves the current configuration to file. // It will acquire a read-lock on the global options registry -// lock and must lock each option! +// lock and will lock each option, one at a time. func SaveConfig() error { - optionsLock.RLock() - defer optionsLock.RUnlock() + saveConfigLock.Lock() + defer saveConfigLock.Unlock() // check if persistence is configured if configFilePath == "" { return nil } - // extract values + // Extract values. + // Lock only one option at a time: holding all option locks at once, acquired + // in random map order, deadlocks concurrent saves (AB-BA lock order). + // The value caches are never modified in place, so copying the string + // slices is enough to make the snapshot independent of later changes. activeValues := make(map[string]interface{}) + optionsLock.RLock() for key, option := range options { - // we cannot immedately unlock the option afger - // getData() because someone could lock and change it - // while we are marshaling the value (i.e. for string slices). - // We NEED to keep the option locks until we finsihed. option.Lock() - defer option.Unlock() - if option.activeValue != nil { - activeValues[key] = option.activeValue.getData(option) + data := option.activeValue.getData(option) + if s, ok := data.([]string); ok { + data = slices.Clone(s) + } + activeValues[key] = data } + option.Unlock() } + optionsLock.RUnlock() // convert to JSON data, err := MapToJSON(activeValues) @@ -92,8 +106,13 @@ func SaveConfig() error { return err } - // write file - return os.WriteFile(configFilePath, data, 0o0600) + // Write file atomically (temp file in the same directory, fsync, rename), + // so that a failed or interrupted write never leaves a truncated config + // file behind, which would fail to load on the next start. + return utils.CreateAtomic(configFilePath, bytes.NewReader(data), &utils.AtomicFileOptions{ + Mode: 0o0600, + TempDir: filepath.Dir(configFilePath), + }) } // JSONToMap parses and flattens a hierarchical json object. @@ -115,7 +134,11 @@ func Flatten(config map[string]interface{}) (flattenedConfig map[string]interfac } func flattenMap(rootMap, subMap map[string]interface{}, subKey string) { - for key, entry := range subMap { + // Iterate in sorted order, so that a key set both nested and flattened + // (e.g. "core": {"devMode": ...} and "core/devMode") resolves the same way + // on every start: the flattened key sorts after its parent and wins. + for _, key := range slices.Sorted(maps.Keys(subMap)) { + entry := subMap[key] // get next level key subbedKey := path.Join(subKey, key) diff --git a/base/config/persistence_concurrency_test.go b/base/config/persistence_concurrency_test.go new file mode 100644 index 000000000..819bbd95d --- /dev/null +++ b/base/config/persistence_concurrency_test.go @@ -0,0 +1,46 @@ +package config + +import ( + "fmt" + "path/filepath" + "sync" + "testing" + "time" +) + +// TestConcurrentSaveConfig checks that concurrent saves (as triggered by +// concurrent SetConfigOption calls) do not deadlock. +func TestConcurrentSaveConfig(t *testing.T) { //nolint:paralleltest // Uses global state. + options = make(map[string]*Option) + for i := range 50 { + quickRegister(t, fmt.Sprintf("concurrent/opt%d", i), OptTypeString, "default") + } + + oldPath := configFilePath + configFilePath = filepath.Join(t.TempDir(), "config.json") + defer func() { configFilePath = oldPath }() + + var wg sync.WaitGroup + for i := range 8 { + wg.Go(func() { + for j := range 20 { + err := setConfigOption(fmt.Sprintf("concurrent/opt%d", (i*7+j)%50), fmt.Sprintf("v%d-%d", i, j), false) + if err != nil { + t.Error(err) + return + } + } + }) + } + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatal("concurrent config saves deadlocked") + } +} diff --git a/base/config/persistence_write_linux_test.go b/base/config/persistence_write_linux_test.go new file mode 100644 index 000000000..2ce0a6c92 --- /dev/null +++ b/base/config/persistence_write_linux_test.go @@ -0,0 +1,65 @@ +//go:build linux + +package config + +import ( + "os" + "os/signal" + "path/filepath" + "syscall" + "testing" +) + +// TestSaveConfigFailedWriteKeepsOldFile checks that a write that fails midway +// (here: exceeding RLIMIT_FSIZE, like a full disk) does not destroy the +// previously persisted config file. +func TestSaveConfigFailedWriteKeepsOldFile(t *testing.T) { //nolint:paralleltest // Changes process wide resource limits. + options = make(map[string]*Option) + quickRegister(t, "persist/a", OptTypeString, "default") + quickRegister(t, "persist/b", OptTypeString, "default") + + oldPath := configFilePath + configFilePath = filepath.Join(t.TempDir(), "config.json") + defer func() { configFilePath = oldPath }() + + // Persist an initial config. + err := setConfigOption("persist/a", "original-value-that-must-survive", false) + if err != nil { + t.Fatal(err) + } + original, err := os.ReadFile(configFilePath) + if err != nil { + t.Fatal(err) + } + + // Make every write beyond a few bytes fail, like a full disk would. + signal.Ignore(syscall.SIGXFSZ) + defer signal.Reset(syscall.SIGXFSZ) + var oldLimit syscall.Rlimit + err = syscall.Getrlimit(syscall.RLIMIT_FSIZE, &oldLimit) + if err != nil { + t.Fatal(err) + } + newLimit := oldLimit + newLimit.Cur = 16 + err = syscall.Setrlimit(syscall.RLIMIT_FSIZE, &newLimit) + if err != nil { + t.Fatal(err) + } + saveErr := setConfigOption("persist/b", "new-value", false) + err = syscall.Setrlimit(syscall.RLIMIT_FSIZE, &oldLimit) + if err != nil { + t.Fatal(err) + } + if saveErr == nil { + t.Fatal("expected save to fail") + } + + current, err := os.ReadFile(configFilePath) + if err != nil { + t.Fatal(err) + } + if string(current) != string(original) { + t.Fatalf("failed save corrupted config file: was %q, now %q", original, current) + } +} diff --git a/base/config/unknown_keys_test.go b/base/config/unknown_keys_test.go new file mode 100644 index 000000000..5e2fa04e1 --- /dev/null +++ b/base/config/unknown_keys_test.go @@ -0,0 +1,76 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +// TestLoadConfigIgnoresUnknownKeys checks that config files written by older +// versions, which still contain settings of removed features (e.g. the SPN +// settings "spn/..."), load without errors and that the unknown keys are +// dropped from the file on the next save. +func TestLoadConfigIgnoresUnknownKeys(t *testing.T) { //nolint:paralleltest // Uses global state. + options = make(map[string]*Option) + quickRegister(t, "test/known", OptTypeString, "default") + + oldPath := configFilePath + configFilePath = filepath.Join(t.TempDir(), "config.json") + defer func() { configFilePath = oldPath }() + + err := os.WriteFile(configFilePath, []byte(`{ + "spn": { + "enable": true, + "use": true, + "routingAlgorithm": "triple-hop", + "exitHubPolicy": ["- DE"] + }, + "test": { + "known": "set" + } +}`), 0o600) + if err != nil { + t.Fatal(err) + } + + // Loading with requireValidConfig must not fail because of unknown keys. + err = loadConfig(true) + if err != nil { + t.Fatalf("loading config with unknown keys failed: %s", err) + } + if errs := GetLoadedConfigValidationErrors(); len(errs) != 0 { + t.Fatalf("unexpected validation errors: %v", errs) + } + if v := GetAsString("test/known", "")(); v != "set" { + t.Fatalf("known key was not loaded: got %q", v) + } + + // Saving writes only registered options, so the unknown keys are dropped. + err = SaveConfig() + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(configFilePath) + if err != nil { + t.Fatal(err) + } + saved, err := JSONToMap(data) + if err != nil { + t.Fatal(err) + } + if len(saved) != 1 || saved["test/known"] != "set" { + t.Fatalf("unexpected saved config: %v", saved) + } + + // Per-app settings (perspectives) ignore unknown keys as well. + perspective, err := NewPerspective(map[string]any{ + "spn": map[string]any{"use": false}, + "test": map[string]any{"known": "app"}, + }) + if err != nil { + t.Fatalf("perspective with unknown keys failed: %s", err) + } + if v, ok := perspective.GetAsString("test/known"); !ok || v != "app" { + t.Fatalf("known key missing from perspective: %q, %v", v, ok) + } +} diff --git a/base/config/validate.go b/base/config/validate.go index 8d3408863..f65e7fb21 100644 --- a/base/config/validate.go +++ b/base/config/validate.go @@ -81,6 +81,12 @@ func migrateValue(option *Option, value any) any { // validateValue ensures that value matches the expected type of option. // It does not create a copy of the value! func validateValue(option *Option, value interface{}) (*valueCache, *ValidationError) { //nolint:gocyclo + // Reject nil (e.g. JSON null) before isAllowedPossibleValue, which cannot + // handle it via reflection. + if value == nil { + return nil, invalid(option, "invalid option value type: %T", value) + } + if option.OptType != OptTypeStringArray { if err := isAllowedPossibleValue(option, value); err != nil { return nil, &ValidationError{ @@ -156,6 +162,9 @@ func validateValue(option *Option, value interface{}) (*valueCache, *ValidationE case int64: validated = &valueCache{intVal: v} case uint: + if uint64(v) > math.MaxInt64 { + return nil, invalid(option, "value out of int64 range") + } validated = &valueCache{intVal: int64(v)} case uint8: validated = &valueCache{intVal: int64(v)} @@ -164,15 +173,15 @@ func validateValue(option *Option, value interface{}) (*valueCache, *ValidationE case uint32: validated = &valueCache{intVal: int64(v)} case float32: - // convert if float has no decimals - if math.Remainder(float64(v), 1) == 0 { + // convert if float has no decimals and fits into an int64 + if floatFitsInt64(float64(v)) { validated = &valueCache{intVal: int64(v)} } else { return nil, invalid(option, "failed to convert float32 to int64") } case float64: - // convert if float has no decimals - if math.Remainder(v, 1) == 0 { + // convert if float has no decimals and fits into an int64 + if floatFitsInt64(v) { validated = &valueCache{intVal: int64(v)} } else { return nil, invalid(option, "failed to convert float64 to int64") @@ -215,6 +224,14 @@ func validateValue(option *Option, value interface{}) (*valueCache, *ValidationE return validated, nil } +// floatFitsInt64 returns whether f has no decimals and is within the int64 +// range, so that converting it to int64 is exact. Converting an out of range +// float to int64 is implementation-defined in Go (MinInt64 on amd64). +func floatFitsInt64(f float64) bool { + // -2^63 and 2^63 are exactly representable as float64. + return f >= -(1<<63) && f < (1<<63) && math.Remainder(f, 1) == 0 +} + // ValidationError error holds details about a config option value validation error. type ValidationError struct { Option *Option diff --git a/base/config/validate_test.go b/base/config/validate_test.go new file mode 100644 index 000000000..1c9e5404b --- /dev/null +++ b/base/config/validate_test.go @@ -0,0 +1,89 @@ +package config + +import ( + "math" + "testing" +) + +// TestIntOutOfRange checks that numbers outside of the int64 range are +// rejected instead of being silently converted to a wrong value. +func TestIntOutOfRange(t *testing.T) { //nolint:paralleltest // Uses global state. + options = make(map[string]*Option) + quickRegister(t, "number", OptTypeInt, 1) + getNumber := GetAsInt("number", 1) + + for _, jsonValue := range []string{"1e19", "-1e19", "9223372036854775807", "1e300"} { + m, err := JSONToMap([]byte(`{"number": ` + jsonValue + `}`)) + if err != nil { + t.Fatal(err) + } + validationErrors, _ := ReplaceConfig(m) + if len(validationErrors) != 1 { + t.Errorf("%s: expected 1 validation error, got %d (value now %d)", jsonValue, len(validationErrors), getNumber()) + } + } + + // Values in range still work. + m, err := JSONToMap([]byte(`{"number": -9223372036854775808}`)) + if err != nil { + t.Fatal(err) + } + validationErrors, _ := ReplaceConfig(m) + if len(validationErrors) != 0 || getNumber() != math.MinInt64 { + t.Errorf("expected min int64 to be accepted, got %d errors and value %d", len(validationErrors), getNumber()) + } + + err = setConfigOption("number", uint(math.MaxUint64), false) + if err == nil { + t.Errorf("expected max uint to be rejected, got value %d", getNumber()) + } +} + +func registerPossibleValuesOption(t *testing.T) *Option { + t.Helper() + + options = make(map[string]*Option) + err := Register(&Option{ + Name: "choice name", + Key: "choice", + Description: "choice description", + ReleaseLevel: ReleaseLevelStable, + ExpertiseLevel: ExpertiseLevelUser, + OptType: OptTypeString, + DefaultValue: "a", + PossibleValues: []PossibleValue{ + {Name: "A", Value: "a"}, + {Name: "B", Value: "b"}, + }, + }) + if err != nil { + t.Fatal(err) + } + opt, err := GetOption("choice") + if err != nil { + t.Fatal(err) + } + return opt +} + +// TestNullValueWithPossibleValues checks that a JSON null for an option with +// possible values is rejected instead of panicking. +func TestNullValueWithPossibleValues(t *testing.T) { //nolint:paralleltest // Uses global state. + opt := registerPossibleValuesOption(t) + + // Via the settings import path. + err := opt.ValidateValue(nil) + if err == nil { + t.Error("expected nil value to be rejected") + } + + // Via a config file containing null. + m, err := JSONToMap([]byte(`{"choice": null}`)) + if err != nil { + t.Fatal(err) + } + validationErrors, _ := ReplaceConfig(m) + if len(validationErrors) != 1 { + t.Errorf("expected 1 validation error, got %d", len(validationErrors)) + } +} diff --git a/base/database/accessor/accessor_test.go b/base/database/accessor/accessor_test.go index 69d41bc9a..0f590c18e 100644 --- a/base/database/accessor/accessor_test.go +++ b/base/database/accessor/accessor_test.go @@ -1,8 +1,9 @@ -//nolint:maligned,unparam +//nolint:unparam package accessor import ( "encoding/json" + "slices" "testing" "github.com/safing/portmaster/base/utils" @@ -150,11 +151,18 @@ func testSet(t *testing.T, acc Accessor, key string, shouldSucceed bool, valueTo func TestAccessor(t *testing.T) { t.Parallel() + // Work on copies of the test data, as the test modifies it through the + // accessors and must be repeatable (go test -count). + jsonCopy := testJSON + jsonBytesCopy := slices.Clone(testJSONBytes) + structCopy := *testStruct + structCopy.A = slices.Clone(testStruct.A) + // Test interface compliance. accs := []Accessor{ - NewJSONAccessor(&testJSON), - NewJSONBytesAccessor(&testJSONBytes), - NewStructAccessor(testStruct), + NewJSONAccessor(&jsonCopy), + NewJSONBytesAccessor(&jsonBytesCopy), + NewStructAccessor(&structCopy), } // get diff --git a/base/database/controller.go b/base/database/controller.go index 5d23c1c83..a78d8ec2e 100644 --- a/base/database/controller.go +++ b/base/database/controller.go @@ -156,25 +156,8 @@ func (c *Controller) Put(r record.Record) (err error) { // PutMany stores many records in the database. It does not // process any hooks or update subscriptions. Use with care! func (c *Controller) PutMany() (chan<- record.Record, <-chan error) { - if shuttingDown.IsSet() { - errs := make(chan error, 1) - errs <- ErrShuttingDown - return make(chan record.Record), errs - } - - if c.ReadOnly() { - errs := make(chan error, 1) - errs <- ErrReadOnly - return make(chan record.Record), errs - } - - if batcher, ok := c.storage.(storage.Batcher); ok { - return batcher.PutMany(c.shadowDelete) - } - - errs := make(chan error, 1) - errs <- ErrNotImplemented - return make(chan record.Record), errs + batch, errs, _ := c.putMany(context.Background()) + return batch, errs } // Query executes the given query on the database. @@ -204,6 +187,27 @@ func (c *Controller) PushUpdate(r record.Record) { } } +// HasSubscribers returns whether there is a subscription that could receive +// an update of the record with the given database key (the key without the +// database name). It does not check permissions or query conditions, so it +// may report subscribers that will not receive a specific record. +// Use it to skip creating a record for PushUpdate that nobody would receive. +func (c *Controller) HasSubscribers(dbKey string) bool { + if c == nil || shuttingDown.IsSet() { + return false + } + + c.subscriptionLock.RLock() + defer c.subscriptionLock.RUnlock() + + for _, sub := range c.subscriptions { + if sub.q.MatchesKey(dbKey) { + return true + } + } + return false +} + func (c *Controller) addSubscription(sub *Subscription) { if shuttingDown.IsSet() { return @@ -283,6 +287,37 @@ func (c *Controller) Shutdown() error { return c.storage.Shutdown() } +// putMany is like PutMany, but uses storage.AbortableBatcher if the storage +// implements it. It then reports the batch as abortable: if abort is done +// before the batch channel is closed, the storage does not store the batch. +// Other storages ignore abort. +func (c *Controller) putMany(abort context.Context) (batch chan<- record.Record, errs <-chan error, abortable bool) { + failed := func(err error) (chan<- record.Record, <-chan error, bool) { + errs := make(chan error, 1) + errs <- err + return make(chan record.Record), errs, false + } + + if shuttingDown.IsSet() { + return failed(ErrShuttingDown) + } + + if c.ReadOnly() { + return failed(ErrReadOnly) + } + + switch batcher := c.storage.(type) { + case storage.AbortableBatcher: + batch, errs = batcher.PutManyAbortable(abort, c.shadowDelete) + return batch, errs, true + case storage.Batcher: + batch, errs = batcher.PutMany(c.shadowDelete) + return batch, errs, false + } + + return failed(ErrNotImplemented) +} + // notifySubscribers notifies all subscribers that are interested // in r. r must be locked when calling notifySubscribers. // Any subscriber that is not blocking on it's feed channel will diff --git a/base/database/controller_subscribers_test.go b/base/database/controller_subscribers_test.go new file mode 100644 index 000000000..f378a3791 --- /dev/null +++ b/base/database/controller_subscribers_test.go @@ -0,0 +1,44 @@ +package database + +import ( + "testing" + + "github.com/safing/portmaster/base/database/query" +) + +func TestControllerHasSubscribers(t *testing.T) { + t.Parallel() + + var nilController *Controller + if nilController.HasSubscribers("a/b") { + t.Error("nil controller reports subscribers") + } + + c := &Controller{} + if c.HasSubscribers("a/b") { + t.Error("controller without subscriptions reports subscribers") + } + + c.subscriptions = append(c.subscriptions, + &Subscription{q: query.New("db:a/").MustBeValid()}, + &Subscription{q: query.New("db:c/d").MustBeValid()}, + ) + for dbKey, expected := range map[string]bool{ + "a/b": true, + "a/": true, + "a": false, + "b/a": false, + "c/d": true, + "c/e": false, + } { + if c.HasSubscribers(dbKey) != expected { + t.Errorf("HasSubscribers(%q) is %v, expected %v", dbKey, !expected, expected) + } + } + + // A subscription to the whole database receives every record. + c.subscriptions = append(c.subscriptions, &Subscription{q: query.New("db:").MustBeValid()}) + if !c.HasSubscribers("b/a") { + t.Error("subscription to the whole database is not reported") + } +} diff --git a/base/database/interface.go b/base/database/interface.go index 04cd46ad8..3bc96f7a5 100644 --- a/base/database/interface.go +++ b/base/database/interface.go @@ -14,12 +14,20 @@ import ( "github.com/safing/portmaster/base/database/iterator" "github.com/safing/portmaster/base/database/query" "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" ) const ( getDBFromKey = "" ) +// PutMany batch errors. +var ( + errPutManyTimeout = errors.New("timeout: putmany unused for too long") + errBatchClosed = errors.New("batch is closed") + errBatchStoppedByStorage = errors.New("storage stopped processing the batch") +) + // Interface provides a method to access the database with attached options. type Interface struct { options *Options @@ -344,6 +352,10 @@ func (i *Interface) PutNew(r record.Record) (err error) { return db.Put(r) } +// putManyIdleTimeout is how long PutMany waits for the next record before +// it stops accepting records. +const putManyIdleTimeout = 1 * time.Second + // PutMany stores many records in the database. // Warning: This is nearly a direct database access and omits many things: // - Record locking @@ -351,6 +363,18 @@ func (i *Interface) PutNew(r record.Record) (err error) { // - Subscriptions // - Caching // Use with care. +// +// Calling put with nil finishes the batch and returns its result. If put is +// not called for one second, the batch is aborted and fails with an error +// that says whether the records submitted before (put returned nil) were +// stored: +// - Storages that implement storage.AbortableBatcher (sqlite, bbolt) discard +// the batch: none of its records are stored. With these storages a batch +// is thus stored completely if put(nil) returns nil, and not at all +// otherwise. +// - Other storages cannot abort a batch: the records submitted before are +// still handed to the storage, which stores them. A timed out batch is +// then not rolled back. func (i *Interface) PutMany(dbName string) (put func(record.Record) error) { interfaceBatch := make(chan record.Record, 100) @@ -377,55 +401,155 @@ func (i *Interface) PutMany(dbName string) (put func(record.Record) error) { } // start database access - dbBatch, errs := db.PutMany() + // Cancelling abortBatch before closing dbBatch aborts the batch, if the + // storage supports it (abortable). + abortBatch, cancelBatch := context.WithCancelCause(context.Background()) + dbBatch, errs, abortable := db.putMany(abortBatch) finished := abool.New() - var internalErr error + // The proxy is the only reader of errs. It sets result to the final error + // of the batch and then closes done when it exits. + done := make(chan struct{}) + var result error + // On the idle timeout, the proxy closes stopping and then sets stopped, + // after which no more records are accepted. All records accepted before + // are still passed on to the storage. + stopping := make(chan struct{}) + var ( + acceptLock sync.Mutex + stopped bool + ) // interface options proxy go func() { - defer close(dbBatch) // signify that we are finished + defer close(done) + // Release the abort context. All paths have closed dbBatch and + // received the result of the storage by now, so this aborts nothing. + defer cancelBatch(nil) + var forwarded int + // The batch is stopped when no record arrives for a second. A single + // timer, reset after every record, avoids allocating a new timer for + // each record of large batches like the filter lists. + idle := time.NewTimer(putManyIdleTimeout) + defer idle.Stop() + // forward passes r on to the storage. If the storage stopped processing + // the batch, it sets result and returns false. + forward := func(r record.Record) bool { + // apply options + i.options.Apply(r) + // pass along, unless the storage stopped processing the batch + select { + case dbBatch <- r: + forwarded++ + return true + case err := <-errs: + close(dbBatch) + result = storageStoppedError(err) + return false + } + } + for { select { case r := <-interfaceBatch: // finished? if r == nil { + close(dbBatch) // signify that we are finished + result = <-errs + return + } + if !forward(r) { return } - // apply options - i.options.Apply(r) - // pass along - dbBatch <- r - case <-time.After(1 * time.Second): - // bail out - internalErr = errors.New("timeout: putmany unused for too long") - finished.Set() + idle.Reset(putManyIdleTimeout) + case err := <-errs: + // The storage stopped processing the batch. + close(dbBatch) + result = storageStoppedError(err) + return + case <-idle.C: + // Bail out. Stop accepting records, then pass on the ones that + // were already accepted, as the caller was told so. + close(stopping) + acceptLock.Lock() + stopped = true + acceptLock.Unlock() + finishing := false + drain: + for { + select { + case r := <-interfaceBatch: + if r == nil { + finishing = true + } else if !forward(r) { + return + } + default: + break drain + } + } + + // The batch is incomplete, unless the caller finished it just + // now. Abort it before closing the batch channel, so that the + // storage discards it. A storage that cannot abort a batch + // commits the records passed on so far when the batch channel + // is closed. Wait for the outcome in both cases, so that the + // caller learns whether they were stored. + if abortable && !finishing { + cancelBatch(errPutManyTimeout) + } + close(dbBatch) + result = putManyTimeoutError(<-errs, forwarded, finishing) return } } }() - return func(r record.Record) error { - // finished? - if finished.IsSet() { - // check for internal error - if internalErr != nil { - return internalErr - } - // check for previous error - select { - case err := <-errs: - return err - default: - return errors.New("batch is closed") - } + // submit passes r (nil finishes the batch) to the proxy and reports + // whether it was accepted. Accepted records are passed on to the storage + // unless the storage stops processing the batch. + submit := func(r record.Record) bool { + acceptLock.Lock() + defer acceptLock.Unlock() + if stopped { + return false + } + select { + case interfaceBatch <- r: + return true + case <-stopping: + return false + case <-done: + return false + } + } + + // batchClosedErr may only be called after done was closed. + batchClosedErr := func() error { + if result != nil { + return result } + return errBatchClosed + } + return func(r record.Record) error { // finish? if r == nil { - finished.Set() - interfaceBatch <- nil // signify that we are finished + if finished.SetToIf(false, true) { + submit(nil) // signify that we are finished + } // do not close, as this fn could be called again with nil. - return <-errs + <-done + return result + } + + // finished? + select { + case <-done: + return batchClosedErr() + default: + } + if finished.IsSet() { + return errBatchClosed } // check record scope @@ -434,15 +558,47 @@ func (i *Interface) PutMany(dbName string) (put func(record.Record) error) { } // submit - select { - case interfaceBatch <- r: + if submit(r) { return nil - case err := <-errs: - return err } + <-done + return batchClosedErr() } } +// putManyTimeoutError returns the result of a batch that was closed because of +// the idle timeout. storageErr is the result of the storage for the forwarded +// records passed on before, which is storage.ErrBatchAborted if the storage +// discarded them. If the caller had finished the batch already +// (finishing), the storage result is returned as is. +func putManyTimeoutError(storageErr error, forwarded int, finishing bool) error { + switch { + case finishing: + return storageErr + case errors.Is(storageErr, storage.ErrBatchAborted): + // The storage discarded the batch. + if forwarded == 0 { + return errPutManyTimeout + } + return fmt.Errorf("%w; the %d records submitted before were not stored: %w", errPutManyTimeout, forwarded, storage.ErrBatchAborted) + case storageErr != nil: + return fmt.Errorf("%w; storing the %d records submitted before failed: %w", errPutManyTimeout, forwarded, storageErr) + case forwarded == 0: + return errPutManyTimeout + default: + return fmt.Errorf("%w; the %d records submitted before were stored", errPutManyTimeout, forwarded) + } +} + +// storageStoppedError returns the error for a storage that stopped processing +// a batch before it was finished. +func storageStoppedError(err error) error { + if err != nil { + return err + } + return errBatchStoppedByStorage +} + // SetAbsoluteExpiry sets an absolute record expiry. func (i *Interface) SetAbsoluteExpiry(key string, time int64) error { r, db, err := i.getRecord(getDBFromKey, key, true) @@ -515,8 +671,18 @@ func (i *Interface) Delete(key string) error { return ErrReadOnly } + r.Lock() i.options.Apply(r) r.Meta().Delete() + r.Unlock() + + // Remove the record from the read cache and drop any pending delayed write + // of it, so that neither serves nor writes back the deleted record. + // The record may not be locked when updating the cache. + i.updateCache(r, true, true, 0) + + r.Lock() + defer r.Unlock() return db.Put(r) } diff --git a/base/database/interface_cache.go b/base/database/interface_cache.go index b860a2a31..de1a03a3d 100644 --- a/base/database/interface_cache.go +++ b/base/database/interface_cache.go @@ -5,6 +5,7 @@ import ( "time" "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/mgr" ) @@ -34,6 +35,10 @@ func (i *Interface) DelayedCacheWriter(wc *mgr.WorkerCtx) error { select { case <-wc.Done(): // The caller is shutting down, flush the cache to storage and exit. + // An aborted flush keeps its records in the write cache, so retry + // it once, as they would be lost otherwise. This is a no-op if the + // first flush emptied the write cache. + i.flushWriteCache(0) i.flushWriteCache(0) return nil @@ -74,7 +79,7 @@ func (i *Interface) ClearCache() { // FlushCache writes (and thus clears) the write cache. func (i *Interface) FlushCache() { // Check if write cache is in use. - if i.options.DelayCachedWrites != "" { + if i.options.DelayCachedWrites == "" { return } @@ -96,18 +101,31 @@ func (i *Interface) flushWriteCache(percentThreshold int) { } // Write the full cache in a batch operation. + // A batch that was aborted (storage.ErrBatchAborted) was not stored and a + // batch that timed out (errPutManyTimeout) was not stored completely. Keep + // the write cache then, so that the next flush retries all of its records. + // Writing a record again is idempotent. Other errors are logged and the + // write cache is cleared as before, as they may be caused by the records + // themselves and would then fail every following flush, too. + var retry bool batchPut := i.PutMany(i.options.DelayCachedWrites) for _, r := range i.writeCache { err := batchPut(r) if err != nil { + retry = retry || isRetryableBatchError(err) log.Warningf("database: failed to write write-cached entry to %q database: %s", i.options.DelayCachedWrites, err) } } // Finish batch. err := batchPut(nil) if err != nil { + retry = retry || isRetryableBatchError(err) log.Warningf("database: failed to finish flushing write cache to %q database: %s", i.options.DelayCachedWrites, err) } + if retry { + log.Warningf("database: keeping %d write-cached entries of %q database to retry writing them with the next flush", len(i.writeCache), i.options.DelayCachedWrites) + return + } // Optimized map clearing following the Go1.11 recommendation. for key := range i.writeCache { @@ -115,6 +133,12 @@ func (i *Interface) flushWriteCache(percentThreshold int) { } } +// isRetryableBatchError reports whether err says that a PutMany batch was +// aborted or timed out, so that some or all of its records were not stored. +func isRetryableBatchError(err error) bool { + return errors.Is(err, storage.ErrBatchAborted) || errors.Is(err, errPutManyTimeout) +} + // cacheEvictHandler is run by the cache for every entry that gets evicted // from the cache. func (i *Interface) cacheEvictHandler(keyData, _ interface{}) { @@ -192,6 +216,15 @@ func (i *Interface) updateCache(r record.Record, write bool, remove bool, ttl in // Check if record should be deleted if remove { + // Drop a pending delayed write of the same key: the removal wins over + // it and is written through to the database storage by the caller. + // Otherwise the evict handler would first write the stale pending + // record to storage. + if write && r.DatabaseName() == i.options.DelayCachedWrites { + i.writeCacheLock.Lock() + delete(i.writeCache, r.Key()) + i.writeCacheLock.Unlock() + } // Remove entry from cache. i.cache.Remove(r.Key()) // Let write through to database storage. diff --git a/base/database/interface_cache_abort_test.go b/base/database/interface_cache_abort_test.go new file mode 100644 index 000000000..87f6e4856 --- /dev/null +++ b/base/database/interface_cache_abort_test.go @@ -0,0 +1,245 @@ +package database + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" + "github.com/safing/portmaster/base/database/storage/hashmap" + "github.com/safing/portmaster/service/mgr" +) + +// abortingStorage is a test storage that implements storage.AbortableBatcher +// on top of a hashmap. It discards the next abortBatches batches that contain +// records and reports them as aborted, like sqlite and bbolt do with a batch +// that was aborted. Other batches are stored completely. +type abortingStorage struct { + storage.Interface + + abortBatches atomic.Int32 + aborted atomic.Int32 +} + +func (s *abortingStorage) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { + return s.PutManyAbortable(context.Background(), shadowDelete) +} + +func (s *abortingStorage) PutManyAbortable(_ context.Context, _ bool) (chan<- record.Record, <-chan error) { + batch := make(chan record.Record, 100) + errs := make(chan error, 1) + go func() { + var records []record.Record + for r := range batch { + records = append(records, r) + } + if len(records) > 0 && s.abortBatches.Add(-1) >= 0 { + s.aborted.Add(1) + errs <- fmt.Errorf("%w: test abort of %d records", storage.ErrBatchAborted, len(records)) + return + } + for _, r := range records { + _, err := s.Put(r) + if err != nil { + errs <- err + return + } + } + errs <- nil + }() + return batch, errs +} + +var ( + abortingStoragesLock sync.Mutex + abortingStorages = make(map[string]*abortingStorage) +) + +func init() { + _ = storage.Register("test-aborting", func(name, location string) (storage.Interface, error) { + hm, err := hashmap.NewHashMap(name, location) + if err != nil { + return nil, err + } + s := &abortingStorage{Interface: hm} + abortingStoragesLock.Lock() + defer abortingStoragesLock.Unlock() + abortingStorages[name] = s + return s, nil + }) +} + +// setupAbortingCacheDB registers a database on an abortingStorage and returns +// it together with an interface that delays writes to it and one without a +// cache to check the storage. +func setupAbortingCacheDB(t *testing.T, dbName string) (s *abortingStorage, cachingDB, plainDB *Interface) { + t.Helper() + + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for aborted write cache flushes", + StorageType: "test-aborting", + }) + if err != nil { + t.Fatal(err) + } + cachingDB = NewInterface(&Options{ + Local: true, + Internal: true, + CacheSize: 1000, + DelayCachedWrites: dbName, + }) + plainDB = NewInterface(&Options{ + Local: true, + Internal: true, + }) + // Get the controller so that the storage is started. + _, err = getController(dbName) + if err != nil { + t.Fatal(err) + } + abortingStoragesLock.Lock() + s = abortingStorages[dbName] + abortingStoragesLock.Unlock() + if s == nil { + t.Fatal("aborting storage was not created") + } + return s, cachingDB, plainDB +} + +// countStored returns how many of the records 0 to n-1 are stored with the +// given score. +func countStored(t *testing.T, plainDB *Interface, dbName string, n, score int) int { + t.Helper() + + var stored int + for i := range n { + r, err := plainDB.Get(fmt.Sprintf("%s:%d", dbName, i)) + switch { + case errors.Is(err, ErrNotFound): + continue + case err != nil: + t.Fatal(err) + } + example, ok := r.(*Example) + if !ok { + example = &Example{} + err = record.Unwrap(r, example) + if err != nil { + t.Fatal(err) + } + } + if example.Score == score { + stored++ + } + } + return stored +} + +func pendingWrites(i *Interface) int { + i.writeCacheLock.Lock() + defer i.writeCacheLock.Unlock() + return len(i.writeCache) +} + +// TestFlushWriteCacheKeepsAbortedRecords checks that a write cache flush +// whose batch is aborted keeps the records in the write cache and that the +// next flush stores all of them, in their latest version. +func TestFlushWriteCacheKeepsAbortedRecords(t *testing.T) { //nolint:paralleltest // Must finish before TestDatabaseSystem shuts down the database system. + dbName := "test-flush-write-cache-abort" + s, cachingDB, plainDB := setupAbortingCacheDB(t, dbName) + + const records = 50 + for i := range records { + err := cachingDB.Put(NewExample(fmt.Sprintf("%s:%d", dbName, i), "A", 1)) + if err != nil { + t.Fatal(err) + } + } + + // The batch of the first flush is aborted: nothing is stored and all + // records stay in the write cache. + s.abortBatches.Store(1) + cachingDB.FlushCache() + if aborted := s.aborted.Load(); aborted != 1 { + t.Fatalf("%d batches were aborted, expected 1", aborted) + } + stored := countStored(t, plainDB, dbName, records, 1) + if stored != 0 { + t.Errorf("%d records of the aborted flush are stored, expected 0", stored) + } + if pending := pendingWrites(cachingDB); pending != records { + t.Fatalf("%d records are left in the write cache after the aborted flush, expected %d", pending, records) + } + + // A newer version written in between replaces the kept one. + err := cachingDB.Put(NewExample(dbName+":0", "A", 2)) + if err != nil { + t.Fatal(err) + } + + // The next flush stores all records. + cachingDB.FlushCache() + stored = countStored(t, plainDB, dbName, records, 1) + if stored != records-1 { + t.Errorf("%d records are stored after the retry, expected %d", stored, records-1) + } + stored = countStored(t, plainDB, dbName, 1, 2) + if stored != 1 { + t.Error("the newer version of record 0 is not stored after the retry") + } + if pending := pendingWrites(cachingDB); pending != 0 { + t.Errorf("%d records are left in the write cache after the retry, expected 0", pending) + } +} + +// TestDelayedCacheWriterRetriesAbortedFlushOnShutdown checks that the final +// flush on shutdown is retried once if its batch is aborted. +func TestDelayedCacheWriterRetriesAbortedFlushOnShutdown(t *testing.T) { //nolint:paralleltest // Must finish before TestDatabaseSystem shuts down the database system. + dbName := "test-delayed-cache-writer-abort" + s, cachingDB, plainDB := setupAbortingCacheDB(t, dbName) + + m := mgr.New("delayed cache writer abort test") + writerErr := make(chan error, 1) + m.Go("delayed cache writer", func(wc *mgr.WorkerCtx) error { + writerErr <- cachingDB.DelayedCacheWriter(wc) + return nil + }) + + // Few records compared to the cache size, so that only the shutdown + // flushes them. + const records = 20 + for i := range records { + err := cachingDB.Put(NewExample(fmt.Sprintf("%s:%d", dbName, i), "A", 1)) + if err != nil { + t.Fatal(err) + } + } + + s.abortBatches.Store(1) + m.Cancel() + select { + case err := <-writerErr: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("delayed cache writer did not stop") + } + + if aborted := s.aborted.Load(); aborted != 1 { + t.Errorf("%d batches were aborted, expected 1", aborted) + } + stored := countStored(t, plainDB, dbName, records, 1) + if stored != records { + t.Errorf("%d records are stored after shutdown, expected %d", stored, records) + } + if pending := pendingWrites(cachingDB); pending != 0 { + t.Errorf("%d records are left in the write cache after shutdown, expected 0", pending) + } +} diff --git a/base/database/interface_delete_test.go b/base/database/interface_delete_test.go new file mode 100644 index 000000000..2c58e4ee6 --- /dev/null +++ b/base/database/interface_delete_test.go @@ -0,0 +1,74 @@ +package database + +import ( + "errors" + "fmt" + "testing" +) + +// TestDeleteWithPendingDelayedWrite checks that a Delete wins over an earlier, +// not yet flushed delayed write of the same key. +func TestDeleteWithPendingDelayedWrite(t *testing.T) { //nolint:paralleltest // Subtests register databases and share the registry. + for _, storageType := range []string{"hashmap", "bbolt", "sqlite"} { //nolint:goconst,paralleltest // Storage type names; subtests share the registry. + for _, shadowDelete := range []bool{false, true} { + t.Run(fmt.Sprintf("%s_%v", storageType, shadowDelete), func(t *testing.T) { + dbName := fmt.Sprintf("test-delete-pending-%s-%v", storageType, shadowDelete) + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for Delete with delayed writes", + StorageType: storageType, + ShadowDelete: shadowDelete, + }) + if err != nil { + t.Fatal(err) + } + + cachingDB := NewInterface(&Options{ + Local: true, + Internal: true, + CacheSize: 100, + DelayCachedWrites: dbName, + }) + plainDB := NewInterface(&Options{ + Local: true, + Internal: true, + }) + + key := dbName + ":deleted" + err = cachingDB.Put(NewExample(key, "A", 1)) + if err != nil { + t.Fatal(err) + } + err = cachingDB.Delete(key) + if err != nil { + t.Fatal(err) + } + + // The deleted record must not be served from the cache. + _, err = cachingDB.Get(key) + if !errors.Is(err, ErrNotFound) { + t.Fatalf("deleted record still served by caching interface (err=%v)", err) + } + + // The pending write must have been dropped. + cachingDB.writeCacheLock.Lock() + _, pending := cachingDB.writeCache[key] + cachingDB.writeCacheLock.Unlock() + if pending { + t.Fatal("deleted record still pending in write cache") + } + + // Flushing the write cache must not resurrect the record. + cachingDB.flushWriteCache(0) + _, err = plainDB.Get(key) + if !errors.Is(err, ErrNotFound) { + t.Fatalf("deleted record present in storage after flush (err=%v)", err) + } + _, err = cachingDB.Get(key) + if !errors.Is(err, ErrNotFound) { + t.Fatalf("deleted record served by caching interface after flush (err=%v)", err) + } + }) + } + } +} diff --git a/base/database/interface_flush_test.go b/base/database/interface_flush_test.go new file mode 100644 index 000000000..fdc6a2be5 --- /dev/null +++ b/base/database/interface_flush_test.go @@ -0,0 +1,57 @@ +package database + +import "testing" + +func TestFlushCache(t *testing.T) { + t.Parallel() + + dbName := "test-flush-cache" + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for FlushCache", + StorageType: "hashmap", //nolint:goconst // Storage type name. + }) + if err != nil { + t.Fatal(err) + } + + cachingDB := NewInterface(&Options{ + Local: true, + Internal: true, + CacheSize: 100, + DelayCachedWrites: dbName, + }) + plainDB := NewInterface(&Options{ + Local: true, + Internal: true, + }) + + key := dbName + ":flushed" + err = cachingDB.Put(NewExample(key, "A", 1)) + if err != nil { + t.Fatal(err) + } + + // The write must still be pending in the write cache. + _, err = plainDB.Get(key) + if err == nil { + t.Fatal("record was written to storage before flush") + } + + cachingDB.FlushCache() + + _, err = plainDB.Get(key) + if err != nil { + t.Fatalf("record not in storage after FlushCache: %s", err) + } + cachingDB.writeCacheLock.Lock() + pending := len(cachingDB.writeCache) + cachingDB.writeCacheLock.Unlock() + if pending != 0 { + t.Fatalf("write cache not empty after FlushCache: %d entries", pending) + } + + // FlushCache must be a safe no-op without a cache or delayed writes. + plainDB.FlushCache() + NewInterface(&Options{Local: true, Internal: true, CacheSize: 10}).FlushCache() +} diff --git a/base/database/interface_putmany_abort_test.go b/base/database/interface_putmany_abort_test.go new file mode 100644 index 000000000..ec471cb16 --- /dev/null +++ b/base/database/interface_putmany_abort_test.go @@ -0,0 +1,282 @@ +package database + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" +) + +// TestPutManyTimeoutAbortsBatch checks that a batch that is closed by the +// idle timeout is discarded by the storages that can abort a batch (sqlite, +// bbolt): none of its records are stored, records stored before are left +// untouched and the result says so. The hashmap cannot abort a batch and +// keeps the records passed on before the timeout. +func TestPutManyTimeoutAbortsBatch(t *testing.T) { //nolint:paralleltest,tparallel // Must finish before TestDatabaseSystem shuts down the database system. + for _, tc := range []struct { + storageType string + abortable bool + }{ + {storageType: "sqlite", abortable: true}, + {storageType: "bbolt", abortable: true}, //nolint:goconst // Storage type name. + {storageType: "hashmap", abortable: false}, //nolint:goconst // Storage type name. + } { + t.Run(tc.storageType, func(t *testing.T) { + t.Parallel() + testPutManyTimeoutAbortsBatch(t, tc.storageType, tc.abortable) + }) + } +} + +func testPutManyTimeoutAbortsBatch(t *testing.T, storageType string, abortable bool) { + t.Helper() + + dbName := "test-putmany-abort-" + storageType + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for aborted PutMany batches", + StorageType: storageType, + }) + if err != nil { + t.Fatal(err) + } + + db := NewInterface(&Options{ + Local: true, + Internal: true, + }) + batchKey := func(i int) string { + return fmt.Sprintf("%s:batch/%d", dbName, i) + } + getScore := func(key string) int { + r, err := db.Get(dbName + ":" + key) + if err != nil { + t.Fatalf("record %q: %s", key, err) + } + example, ok := r.(*Example) + if !ok { + example = &Example{} + err = record.Unwrap(r, example) + if err != nil { + t.Fatalf("record %q: %s", key, err) + } + } + return example.Score + } + // putBatch submits a batch that also changes a stored record. It + // submits more records than sqlite writes with one statement. + const records = 120 + putBatch := func(score int) (put func(record.Record) error) { + put = db.PutMany(dbName) + for i := range records - 1 { + err := put(NewExample(batchKey(i), "batch", score)) + if err != nil { + t.Fatal(err) + } + } + err := put(NewExample(dbName+":changed", "batch", score)) + if err != nil { + t.Fatal(err) + } + return put + } + + // Records stored before the batch. + for _, key := range []string{"kept", "changed"} { + err = db.Put(NewExample(dbName+":"+key, "before", 1)) + if err != nil { + t.Fatal(err) + } + } + + // Submit a part of a batch and leave it idle until it times out. + put := putBatch(2) + time.Sleep(3 * time.Second) + + // Exactly one result is delivered, also when asked again. + finished := make(chan [2]error, 1) + go func() { + finished <- [2]error{put(nil), put(nil)} + }() + var results [2]error + select { + case results = <-finished: + case <-time.After(10 * time.Second): + t.Fatal("finishing the timed out batch blocked") + } + err = results[0] + if !errors.Is(err, errPutManyTimeout) { + t.Fatalf("finishing returned %v, expected %v", err, errPutManyTimeout) + } + if results[1] == nil || results[1].Error() != err.Error() { + t.Errorf("finishing again returned %v, expected %v", results[1], err) + } + + wantStored, wantScore, wantMsg := 0, 1, "were not stored" + if !abortable { + wantStored, wantScore, wantMsg = records-1, 2, "were stored" + } + wantMsg = fmt.Sprintf("%d records submitted before %s", records, wantMsg) + if !strings.Contains(err.Error(), wantMsg) { + t.Errorf("finishing returned %q, expected it to report: %s", err, wantMsg) + } + if errors.Is(err, storage.ErrBatchAborted) != abortable { + t.Errorf("finishing returned %q, expected an aborted batch: %v", err, abortable) + } + + // The batch is stored not at all, or completely by the hashmap. + var stored int + for i := range records - 1 { + _, err = db.Get(batchKey(i)) + switch { + case err == nil: + stored++ + case !errors.Is(err, ErrNotFound): + t.Fatal(err) + } + } + if stored != wantStored { + t.Errorf("%d new records of the timed out batch are stored, expected %d", stored, wantStored) + } + // Records stored before are untouched by an aborted batch. + if score := getScore("kept"); score != 1 { + t.Errorf("record stored before the batch has score %d, expected 1", score) + } + if score := getScore("changed"); score != wantScore { + t.Errorf("record changed by the timed out batch has score %d, expected %d", score, wantScore) + } + + // The storage is not blocked by the aborted batch and a finished batch + // still stores everything. + err = putBatch(3)(nil) + if err != nil { + t.Fatalf("finishing returned %v", err) + } + for i := range records - 1 { + _, err = db.Get(batchKey(i)) + if err != nil { + t.Fatalf("record %d of the finished batch: %s", i, err) + } + } + if score := getScore("kept"); score != 1 { + t.Errorf("record stored before the batch has score %d, expected 1", score) + } + if score := getScore("changed"); score != 3 { + t.Errorf("record changed by the finished batch has score %d, expected 3", score) + } +} + +// abortObservingStorage is a test storage that implements both batch APIs +// and records which one was used and whether the batch was aborted at the +// time its channel was closed. +type abortObservingStorage struct { + nonBatchingStorage + + plainCalls chan struct{} + aborted chan bool +} + +func (s *abortObservingStorage) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { + s.plainCalls <- struct{}{} + return s.PutManyAbortable(context.Background(), shadowDelete) +} + +func (s *abortObservingStorage) PutManyAbortable(ctx context.Context, shadowDelete bool) (chan<- record.Record, <-chan error) { + batch := make(chan record.Record, 100) + errs := make(chan error, 1) + go func() { + for range batch { //nolint:revive // Drain the batch. + } + // The abort must be visible as soon as the channel is closed. + aborted := ctx.Err() != nil + s.aborted <- aborted + if aborted { + errs <- fmt.Errorf("%w: %w", storage.ErrBatchAborted, context.Cause(ctx)) + return + } + errs <- nil + }() + return batch, errs +} + +var putManyAbortObserver = &abortObservingStorage{ + plainCalls: make(chan struct{}, 10), + aborted: make(chan bool, 10), +} + +func init() { + _ = storage.Register("test-putmany-abort-observer", func(name, location string) (storage.Interface, error) { + return putManyAbortObserver, nil + }) +} + +// TestPutManyAbortSignal checks when Interface.PutMany aborts a batch of a +// storage that implements storage.AbortableBatcher: never when the caller +// finishes the batch, always when the batch times out, and always before the +// batch channel is closed. +func TestPutManyAbortSignal(t *testing.T) { //nolint:paralleltest // Must finish before TestDatabaseSystem shuts down the database system. + dbName := "test-putmany-abort-observer-db" + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for the PutMany abort signal", + StorageType: "test-putmany-abort-observer", + }) + if err != nil { + t.Fatal(err) + } + db := NewInterface(&Options{ + Local: true, + Internal: true, + }) + s := putManyAbortObserver + startBatch := func(records int) (put func(record.Record) error) { + put = db.PutMany(dbName) + for i := range records { + err := put(NewExample(fmt.Sprintf("%s:%d", dbName, i), "A", i)) + if err != nil { + t.Fatal(err) + } + } + return put + } + + // Finished batches are not aborted, with or without records. + for _, records := range []int{0, 300} { + err = startBatch(records)(nil) + if err != nil { + t.Fatalf("finishing a batch of %d records returned %v", records, err) + } + if <-s.aborted { + t.Fatalf("finished batch of %d records was aborted", records) + } + } + + // A batch that times out is aborted, also without records. + for _, records := range []int{0, 5} { + put := startBatch(records) + select { + case aborted := <-s.aborted: + if !aborted { + t.Fatalf("timed out batch of %d records was not aborted before it was closed", records) + } + case <-time.After(10 * time.Second): + t.Fatal("PutMany did not time out") + } + err = put(nil) + if !errors.Is(err, errPutManyTimeout) { + t.Errorf("finishing returned %v, expected %v", err, errPutManyTimeout) + } + if records > 0 && !errors.Is(err, storage.ErrBatchAborted) { + t.Errorf("finishing returned %v, expected %v", err, storage.ErrBatchAborted) + } + } + + if len(s.plainCalls) != 0 { + t.Errorf("PutMany was used %d times instead of PutManyAbortable", len(s.plainCalls)) + } +} diff --git a/base/database/interface_putmany_test.go b/base/database/interface_putmany_test.go new file mode 100644 index 000000000..eee17b65f --- /dev/null +++ b/base/database/interface_putmany_test.go @@ -0,0 +1,306 @@ +package database + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" +) + +var errStoppedPutMany = errors.New("test storage failed to write record") + +// nonBatchingStorage is a writable test storage without PutMany support. +type nonBatchingStorage struct { + storage.InjectBase +} + +func (s *nonBatchingStorage) ReadOnly() bool { return false } +func (s *nonBatchingStorage) Injected() bool { return false } + +// stoppingBatchStorage is a test storage whose PutMany handler fails on the +// first record and stops reading the batch channel, like the SQLite storage +// does on a write error. +type stoppingBatchStorage struct { + nonBatchingStorage +} + +func (s *stoppingBatchStorage) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { + batch := make(chan record.Record, 100) + errs := make(chan error, 1) + go func() { + <-batch + errs <- errStoppedPutMany + }() + return batch, errs +} + +func init() { + _ = storage.Register("test-putmany-stopping", func(name, location string) (storage.Interface, error) { + return &stoppingBatchStorage{}, nil + }) + _ = storage.Register("test-putmany-unsupported", func(name, location string) (storage.Interface, error) { + return &nonBatchingStorage{}, nil + }) +} + +// TestPutManyStoppedBackend checks that Interface.PutMany neither blocks nor +// leaks its proxy goroutine when the storage stops reading the batch, and +// that the caller receives the storage's error. +func TestPutManyStoppedBackend(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + storageType string + wantErr error + }{ + {storageType: "test-putmany-stopping", wantErr: errStoppedPutMany}, + {storageType: "test-putmany-unsupported", wantErr: ErrNotImplemented}, + } { + t.Run(tc.storageType, func(t *testing.T) { + t.Parallel() + + dbName := tc.storageType + "-db" + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for PutMany with a stopped backend", + StorageType: tc.storageType, + }) + if err != nil { + t.Fatal(err) + } + + db := NewInterface(&Options{ + Local: true, + Internal: true, + }) + + // putErr, finishErr, finishAgainErr + results := make(chan [3]error, 1) + go func() { + var res [3]error + put := db.PutMany(dbName) + // Write more records than the channel buffers can hold. + for i := range 300 { + res[0] = put(NewExample(fmt.Sprintf("%s:%d", dbName, i), "A", i)) + if res[0] != nil { + break + } + } + // Finishing the batch must return the storage error, too, + // also when called again. + res[1] = put(nil) + res[2] = put(nil) + results <- res + }() + + select { + case res := <-results: + for i, step := range []string{"put", "finish", "finish again"} { + if !errors.Is(res[i], tc.wantErr) { + t.Errorf("%s returned %v, expected %v", step, res[i], tc.wantErr) + } + } + case <-time.After(10 * time.Second): + t.Fatal("PutMany blocked after the storage stopped reading the batch") + } + }) + } +} + +// TestPutManyFinish checks the result of a successful batch. +func TestPutManyFinish(t *testing.T) { + t.Parallel() + + dbName := "test-putmany-finish" + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for PutMany", + StorageType: "hashmap", //nolint:goconst // Storage type name. + }) + if err != nil { + t.Fatal(err) + } + + db := NewInterface(&Options{ + Local: true, + Internal: true, + }) + + put := db.PutMany(dbName) + for i := range 300 { + err = put(NewExample(fmt.Sprintf("%s:%d", dbName, i), "A", i)) + if err != nil { + t.Fatal(err) + } + } + err = put(nil) + if err != nil { + t.Fatalf("finishing returned %v", err) + } + err = put(nil) + if err != nil { + t.Fatalf("finishing again returned %v", err) + } + err = put(NewExample(dbName+":late", "A", 1)) + if !errors.Is(err, errBatchClosed) { + t.Fatalf("put after finishing returned %v, expected %v", err, errBatchClosed) + } + + for i := range 300 { + _, err = db.Get(fmt.Sprintf("%s:%d", dbName, i)) + if err != nil { + t.Fatal(err) + } + } +} + +var errCommitPutMany = errors.New("test storage failed to commit batch") + +// committingBatchStorage is a test storage that, like the SQLite and BBolt +// storages, collects the batch until the batch channel is closed and then +// commits it. The commit only completes once release is closed. +type committingBatchStorage struct { + nonBatchingStorage + + commitErr error + closed chan struct{} // Closed when the batch channel was closed. + release chan struct{} // Close to let the commit complete. + committed chan int // Receives the number of committed records. +} + +func newCommittingBatchStorage(commitErr error) *committingBatchStorage { + return &committingBatchStorage{ + commitErr: commitErr, + closed: make(chan struct{}), + release: make(chan struct{}), + committed: make(chan int, 1), + } +} + +func (s *committingBatchStorage) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { + batch := make(chan record.Record, 100) + errs := make(chan error, 1) + go func() { + var n int + for range batch { + n++ + } + close(s.closed) + <-s.release + if s.commitErr == nil { + s.committed <- n + } + errs <- s.commitErr + }() + return batch, errs +} + +var ( + putManyCommitOK = newCommittingBatchStorage(nil) + putManyCommitFailed = newCommittingBatchStorage(errCommitPutMany) +) + +func init() { + _ = storage.Register("test-putmany-commit-ok", func(name, location string) (storage.Interface, error) { + return putManyCommitOK, nil + }) + _ = storage.Register("test-putmany-commit-failed", func(name, location string) (storage.Interface, error) { + return putManyCommitFailed, nil + }) +} + +// TestPutManyTimeoutReportsCommit checks what the caller learns when the +// PutMany batch times out: the storage commits the records that were passed +// on before the timeout, as the batch channel is closed normally. The caller +// must only get the final result once the storage finished the batch, and the +// result must say whether these records were stored. +func TestPutManyTimeoutReportsCommit(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + storageType string + storage *committingBatchStorage + }{ + {storageType: "test-putmany-commit-ok", storage: putManyCommitOK}, + {storageType: "test-putmany-commit-failed", storage: putManyCommitFailed}, + } { + t.Run(tc.storageType, func(t *testing.T) { + t.Parallel() + + dbName := tc.storageType + "-db" + _, err := Register(&Database{ + Name: dbName, + Description: "Unit Test Database for PutMany timeouts", + StorageType: tc.storageType, + }) + if err != nil { + t.Fatal(err) + } + + db := NewInterface(&Options{ + Local: true, + Internal: true, + }) + + const records = 5 + put := db.PutMany(dbName) + for i := range records { + err = put(NewExample(fmt.Sprintf("%s:%d", dbName, i), "A", i)) + if err != nil { + t.Fatal(err) + } + } + + // Wait for the idle timeout to close the batch. + select { + case <-tc.storage.closed: + case <-time.After(10 * time.Second): + t.Fatal("PutMany did not time out") + } + + finished := make(chan error, 1) + go func() { + finished <- put(nil) + }() + + // The result is not known before the storage finished the batch. + select { + case err = <-finished: + t.Fatalf("finishing returned %v before the storage finished the batch", err) + case <-time.After(200 * time.Millisecond): + } + close(tc.storage.release) + + select { + case err = <-finished: + case <-time.After(10 * time.Second): + t.Fatal("finishing the batch blocked") + } + if !errors.Is(err, errPutManyTimeout) { + t.Errorf("finishing returned %v, expected %v", err, errPutManyTimeout) + } + if tc.storage.commitErr != nil { + if !errors.Is(err, tc.storage.commitErr) { + t.Errorf("finishing returned %v, expected it to include %v", err, tc.storage.commitErr) + } + return + } + + if n := <-tc.storage.committed; n != records { + t.Fatalf("storage committed %d records, expected %d", n, records) + } + if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("%d records submitted before were stored", records)) { + t.Errorf("finishing returned %v, expected it to report that %d records were stored", err, records) + } + // Further puts are rejected with the same result. + againErr := put(NewExample(dbName+":late", "A", 1)) + if againErr == nil || againErr.Error() != err.Error() { + t.Errorf("put after the timeout returned %v, expected %v", againErr, err) + } + }) + } +} diff --git a/base/database/storage/badger/badger_test.go b/base/database/storage/badger/badger_test.go index 7814f95a5..59eaf5570 100644 --- a/base/database/storage/badger/badger_test.go +++ b/base/database/storage/badger/badger_test.go @@ -18,7 +18,7 @@ var ( _ storage.Maintainer = &Badger{} ) -type TestRecord struct { //nolint:maligned +type TestRecord struct { record.Base sync.Mutex S string diff --git a/base/database/storage/bbolt/bbolt.go b/base/database/storage/bbolt/bbolt.go index 3c93309f5..817438b88 100644 --- a/base/database/storage/bbolt/bbolt.go +++ b/base/database/storage/bbolt/bbolt.go @@ -18,6 +18,12 @@ import ( var bucketName = []byte{0} +// queryPageSize is the maximum number of matching records a query collects +// within one read transaction before handing them to the consumer. +const queryPageSize = 100 + +var errQueryTimeout = errors.New("query timeout") + // BBolt database made pluggable for portbase. type BBolt struct { name string @@ -55,6 +61,9 @@ func NewBBolt(name, location string) (storage.Interface, error) { return nil }) if err != nil { + // Close the database in order to release its file lock, which would + // otherwise block every later attempt to open it. + _ = db.Close() return nil, err } @@ -126,46 +135,29 @@ func (b *BBolt) Put(r record.Record) (record.Record, error) { } // PutMany stores many records in the database. +// The records are received and marshaled outside of any transaction and are +// written in a single transaction once the batch channel is closed, so that +// either all or none of them are stored and a slow producer does not block +// other writers. Exactly one value is sent on the error channel. func (b *BBolt) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { + return b.PutManyAbortable(context.Background(), shadowDelete) +} + +// PutManyAbortable stores many records in the database like PutMany, unless +// abort is done before the batch channel is closed: the collected records are +// then discarded without opening a transaction and the result wraps +// storage.ErrBatchAborted. +func (b *BBolt) PutManyAbortable(abort context.Context, shadowDelete bool) (chan<- record.Record, <-chan error) { batch := make(chan record.Record, 100) errs := make(chan error, 1) go func() { - err := b.db.Batch(func(tx *bbolt.Tx) error { - bucket := tx.Bucket(bucketName) - for r := range batch { - txErr := b.batchPutOrDelete(bucket, shadowDelete, r) - if txErr != nil { - return txErr - } - } - return nil - }) - errs <- err + errs <- b.putMany(abort, batch, shadowDelete) }() return batch, errs } -func (b *BBolt) batchPutOrDelete(bucket *bbolt.Bucket, shadowDelete bool, r record.Record) (err error) { - r.Lock() - defer r.Unlock() - - if !shadowDelete && r.Meta().IsDeleted() { - // Immediate delete. - err = bucket.Delete([]byte(r.DatabaseKey())) - } else { - // Put or shadow delete. - var data []byte - data, err = r.MarshalRecord(r) - if err == nil { - err = bucket.Put([]byte(r.DatabaseKey()), data) - } - } - - return err -} - // Delete deletes a record from the database. func (b *BBolt) Delete(key string) error { err := b.db.Update(func(tx *bbolt.Tx) error { @@ -195,64 +187,29 @@ func (b *BBolt) Query(q *query.Query, local, internal bool) (*iterator.Iterator, } func (b *BBolt) queryExecutor(queryIter *iterator.Iterator, q *query.Query, local, internal bool) { - prefix := []byte(q.DatabaseKeyPrefix()) - err := b.db.View(func(tx *bbolt.Tx) error { - // Create a cursor for iteration. - c := tx.Bucket(bucketName).Cursor() - - // Iterate over items in sorted key order. This starts from the - // first key/value pair and updates the k/v variables to the - // next key/value on each iteration. - // - // The loop finishes at the end of the cursor when a nil key is returned. - for key, value := c.Seek(prefix); key != nil; key, value = c.Next() { - - // if we don't match the prefix anymore, exit - if !bytes.HasPrefix(key, prefix) { - return nil - } - - // wrap value - iterWrapper, err := record.NewRawWrapper(b.name, string(key), value) - if err != nil { - return err - } - - // check validity / access - if !iterWrapper.Meta().CheckValidity() { - continue - } - if !iterWrapper.Meta().CheckPermission(local, internal) { - continue - } - - // check if matches & send - if q.MatchesRecord(iterWrapper) { - // copy data - duplicate := make([]byte, len(value)) - copy(duplicate, value) - - newWrapper, err := record.NewRawWrapper(b.name, iterWrapper.DatabaseKey(), duplicate) - if err != nil { - return err - } - select { - case <-queryIter.Done: - return nil - case queryIter.Next <- newWrapper: - default: - select { - case <-queryIter.Done: - return nil - case queryIter.Next <- newWrapper: - case <-time.After(1 * time.Second): - return errors.New("query timeout") - } - } - } + // Collect the matching records page by page within a read transaction, + // but feed them to the consumer only after the transaction is closed. + // An open read transaction blocks bbolt from growing its mmap, so a slow + // consumer would otherwise stall the writer that needs to grow it and, + // through it, all other writers and new transactions. + var ( + err error + startKey = []byte(q.DatabaseKeyPrefix()) + ) + for { + var page []record.Record + page, startKey, err = b.queryPage(q, startKey, local, internal) + + // Feed the records collected before a possible error, as before. + done, feedErr := feedQueryPage(queryIter, page) + if done { + err = feedErr + break } - return nil - }) + if err != nil || startKey == nil { + break + } + } queryIter.Finish(err) } @@ -267,66 +224,34 @@ func (b *BBolt) Injected() bool { } // MaintainRecordStates maintains records states in the database. -func (b *BBolt) MaintainRecordStates(ctx context.Context, purgeDeletedBefore time.Time, shadowDelete bool) error { //nolint:gocognit +// The records are processed in chunks of maintenanceChunkSize records, each +// in its own write transaction, so that other writers are not blocked for the +// whole walk. If the context is cancelled, the already processed chunks stay +// committed and the context error is returned. +func (b *BBolt) MaintainRecordStates(ctx context.Context, purgeDeletedBefore time.Time, shadowDelete bool) error { now := time.Now().Unix() purgeThreshold := purgeDeletedBefore.Unix() - return b.db.Update(func(tx *bbolt.Tx) error { - bucket := tx.Bucket(bucketName) - // Create a cursor for iteration. - c := bucket.Cursor() - for key, value := c.First(); key != nil; key, value = c.Next() { - // check if context is cancelled - select { - case <-ctx.Done(): - return nil - default: - } - - // wrap value - wrapper, err := record.NewRawWrapper(b.name, string(key), value) - if err != nil { - return err - } - - // check if we need to do maintenance - meta := wrapper.Meta() - switch { - case meta.Deleted == 0 && meta.Expires > 0 && meta.Expires < now: - if shadowDelete { - // mark as deleted - meta.Deleted = meta.Expires - deleted, err := wrapper.MarshalRecord(wrapper) - if err != nil { - return err - } - err = bucket.Put(key, deleted) - if err != nil { - return err - } - - // Cursor repositioning is required after modifying data. - // While the documentation states that this is also required after a - // delete, this actually makes the cursor skip a record with the - // following c.Next() call of the loop. - // Docs/Issue: https://github.com/boltdb/bolt/issues/426#issuecomment-141982984 - c.Seek(key) - - continue - } + var startKey []byte + for { + // Check if the context is cancelled. + err := ctx.Err() + if err != nil { + return err + } - // Immediately delete expired entries if shadowDelete is disabled. - fallthrough - case meta.Deleted > 0 && (!shadowDelete || meta.Deleted < purgeThreshold): - // delete from storage - err = c.Delete() - if err != nil { - return err - } - } + err = b.db.Update(func(tx *bbolt.Tx) error { + var txErr error + startKey, txErr = b.maintainRecordStatesChunk(tx.Bucket(bucketName), startKey, now, purgeThreshold, shadowDelete) + return txErr + }) + if err != nil && !errors.Is(err, errNothingToMaintain) { + return err } - return nil - }) + if startKey == nil { + return nil + } + } } // Purge deletes all records that match the given query. It returns the number of successful deletes and an error. @@ -335,16 +260,24 @@ func (b *BBolt) Purge(ctx context.Context, q *query.Query, local, internal, shad var cnt int var done bool + var cancelErr error + // Each chunk continues after the last record handled by the previous one, + // instead of rescanning the records already handled, which stay in the + // bucket when shadow deleting or skipped. + startKey := prefix for !done { err := b.db.Update(func(tx *bbolt.Tx) error { // Create a cursor for iteration. bucket := tx.Bucket(bucketName) c := bucket.Cursor() - for key, value := c.Seek(prefix); key != nil; key, value = c.Next() { + for key, value := c.Seek(startKey); key != nil; key, value = c.Next() { // Check if context has been cancelled. select { case <-ctx.Done(): + // Commit what was purged so far, but report that the + // purge is incomplete. done = true + cancelErr = ctx.Err() return nil default: } @@ -405,8 +338,11 @@ func (b *BBolt) Purge(ctx context.Context, q *query.Query, local, internal, shad } // Work in batches of 1000 changes in order to enable other operations in between. + // The next chunk starts at the smallest key after the current one. cnt++ if cnt%1000 == 0 { + startKey = make([]byte, len(key)+1) + copy(startKey, key) return nil } } @@ -418,10 +354,252 @@ func (b *BBolt) Purge(ctx context.Context, q *query.Query, local, internal, shad } } - return cnt, nil + return cnt, cancelErr } // Shutdown shuts down the database. func (b *BBolt) Shutdown() error { return b.db.Close() } + +// maintenanceChunkSize is the maximum number of records MaintainRecordStates +// processes within one write transaction. Each commit costs a sync to disk, so +// the chunks must not be too small. A variable for tests. +var maintenanceChunkSize = 10000 + +// errNothingToMaintain rolls back the transaction of a chunk without changes, +// which saves the commit and its sync to disk. +var errNothingToMaintain = errors.New("nothing to maintain") + +// maintenanceChange is a change of a record found during maintenance. +type maintenanceChange struct { + key []byte + data []byte // nil means delete +} + +// maintainRecordStatesChunk maintains up to maintenanceChunkSize records, +// starting at the given key. It returns the key to continue at, or nil if +// there are no more records. If no record needs to be changed, it returns +// errNothingToMaintain, together with the key to continue at. +func (b *BBolt) maintainRecordStatesChunk(bucket *bbolt.Bucket, startKey []byte, now, purgeThreshold int64, shadowDelete bool) (nextKey []byte, err error) { + // Collect the changes first and apply them after the iteration, as + // modifying the bucket during cursor iteration (other than with a lone + // Cursor.Delete) makes the cursor skip records. + var changes []maintenanceChange + c := bucket.Cursor() + processed := 0 + for key, value := c.Seek(startKey); key != nil; key, value = c.Next() { + // Continue in a new transaction once the chunk is full. + if processed >= maintenanceChunkSize { + nextKey = bytes.Clone(key) + break + } + processed++ + + // wrap value + wrapper, err := record.NewRawWrapper(b.name, string(key), value) + if err != nil { + return nil, err + } + + // check if we need to do maintenance + meta := wrapper.Meta() + switch { + case meta.Deleted == 0 && meta.Expires > 0 && meta.Expires < now: + if shadowDelete { + // mark as deleted + meta.Deleted = meta.Expires + deleted, err := wrapper.MarshalRecord(wrapper) + if err != nil { + return nil, err + } + changes = append(changes, maintenanceChange{key: bytes.Clone(key), data: deleted}) + continue + } + + // Immediately delete expired entries if shadowDelete is disabled. + fallthrough + case meta.Deleted > 0 && (!shadowDelete || meta.Deleted < purgeThreshold): + // delete from storage + changes = append(changes, maintenanceChange{key: bytes.Clone(key)}) + } + } + + if len(changes) == 0 { + return nextKey, errNothingToMaintain + } + + // Apply the changes. + for _, change := range changes { + if change.data == nil { + err = bucket.Delete(change.key) + } else { + err = bucket.Put(change.key, change.data) + } + if err != nil { + return nil, err + } + } + + return nextKey, nil +} + +// queryPage collects up to queryPageSize matching records, starting at the +// given key, within one read transaction. It returns the key to continue at, +// or nil if there are no more records. The returned records own their data, +// as the data returned by bbolt is only valid during the transaction. +func (b *BBolt) queryPage(q *query.Query, startKey []byte, local, internal bool) (page []record.Record, nextKey []byte, err error) { + prefix := []byte(q.DatabaseKeyPrefix()) + err = b.db.View(func(tx *bbolt.Tx) error { + // Create a cursor for iteration. + c := tx.Bucket(bucketName).Cursor() + + // Iterate over items in sorted key order. This starts from the + // first key/value pair and updates the k/v variables to the + // next key/value on each iteration. + // + // The loop finishes at the end of the cursor when a nil key is returned. + for key, value := c.Seek(startKey); key != nil; key, value = c.Next() { + // if we don't match the prefix anymore, exit + if !bytes.HasPrefix(key, prefix) { + return nil + } + + // wrap value + iterWrapper, err := record.NewRawWrapper(b.name, string(key), value) + if err != nil { + return err + } + + // check validity / access + if !iterWrapper.Meta().CheckValidity() { + continue + } + if !iterWrapper.Meta().CheckPermission(local, internal) { + continue + } + + // check if matches & collect + if !q.MatchesRecord(iterWrapper) { + continue + } + + // copy data + duplicate := make([]byte, len(value)) + copy(duplicate, value) + + newWrapper, err := record.NewRawWrapper(b.name, iterWrapper.DatabaseKey(), duplicate) + if err != nil { + return err + } + page = append(page, newWrapper) + + // Continue in a new transaction once the page is full. The next + // page starts at the smallest key after the current one. + if len(page) >= queryPageSize { + nextKey = make([]byte, len(key)+1) + copy(nextKey, key) + return nil + } + } + return nil + }) + return page, nextKey, err +} + +// feedQueryPage sends the given records to the query iterator. It returns +// whether the query is done, either because it was cancelled or because the +// consumer did not accept a record in time. +func feedQueryPage(queryIter *iterator.Iterator, page []record.Record) (done bool, err error) { + for _, r := range page { + select { + case <-queryIter.Done: + return true, nil + case queryIter.Next <- r: + default: + select { + case <-queryIter.Done: + return true, nil + case queryIter.Next <- r: + case <-time.After(1 * time.Second): + return true, errQueryTimeout + } + } + } + + return false, nil +} + +// batchEntry is a prepared write of a PutMany batch. +type batchEntry struct { + key []byte + data []byte + delete bool +} + +// putMany collects all records of the batch and writes them in one +// transaction. It must not use DB.Batch: bbolt may run a Batch function more +// than once (when it is combined with a failing one, or when it fails itself), +// and the records of the channel can only be consumed once. +// If abort is done before the batch channel is closed, nothing is written. +func (b *BBolt) putMany(abort context.Context, batch <-chan record.Record, shadowDelete bool) error { + var entries []batchEntry +collect: + for { + select { + case r, ok := <-batch: + if !ok { + break collect + } + entry, err := prepareBatchEntry(r, shadowDelete) + if err != nil { + return err + } + entries = append(entries, entry) + case <-abort.Done(): + break collect + } + } + // Also check for an abort when the batch channel was closed, as it is + // closed right after the abort. + if abort.Err() != nil { + return fmt.Errorf("%w: %w", storage.ErrBatchAborted, context.Cause(abort)) + } + if len(entries) == 0 { + return nil + } + + return b.db.Update(func(tx *bbolt.Tx) error { + bucket := tx.Bucket(bucketName) + for _, entry := range entries { + var err error + if entry.delete { + err = bucket.Delete(entry.key) + } else { + err = bucket.Put(entry.key, entry.data) + } + if err != nil { + return err + } + } + return nil + }) +} + +func prepareBatchEntry(r record.Record, shadowDelete bool) (batchEntry, error) { + r.Lock() + defer r.Unlock() + + key := []byte(r.DatabaseKey()) + if !shadowDelete && r.Meta() != nil && r.Meta().IsDeleted() { + // Immediate delete. + return batchEntry{key: key, delete: true}, nil + } + + // Put or shadow delete. + data, err := r.MarshalRecord(r) + if err != nil { + return batchEntry{}, err + } + return batchEntry{key: key, data: data}, nil +} diff --git a/base/database/storage/bbolt/bbolt_test.go b/base/database/storage/bbolt/bbolt_test.go index c2fb22b95..5e57ac63e 100644 --- a/base/database/storage/bbolt/bbolt_test.go +++ b/base/database/storage/bbolt/bbolt_test.go @@ -20,7 +20,7 @@ var ( _ storage.Purger = &BBolt{} ) -type TestRecord struct { //nolint:maligned +type TestRecord struct { record.Base sync.Mutex S string diff --git a/base/database/storage/bbolt/maintenance_test.go b/base/database/storage/bbolt/maintenance_test.go new file mode 100644 index 000000000..4ea1c05c8 --- /dev/null +++ b/base/database/storage/bbolt/maintenance_test.go @@ -0,0 +1,430 @@ +package bbolt + +import ( + "context" + "errors" + "fmt" + "math/rand" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "go.etcd.io/bbolt" + + "github.com/safing/portmaster/base/database/record" +) + +// Record kinds used by the maintenance tests. +const ( + kindLive = iota + kindLiveExpiring + kindExpired + kindDeletedRecently + kindDeletedLongAgo + numKinds +) + +// maintenanceTestMeta returns the meta data for a record of the given kind. +func maintenanceTestMeta(kind int, now int64) *record.Meta { + m := &record.Meta{Created: now - 86400, Modified: now - 86400} + switch kind { + case kindLive: + case kindLiveExpiring: + m.Expires = now + 3600 + case kindExpired: + // Expired after the purge threshold (now-60), so that the shadow deleted + // record is not purged by a later run and maintenance is idempotent. + m.Expires = now - 30 + case kindDeletedRecently: + m.Deleted = now - 10 + case kindDeletedLongAgo: + m.Deleted = now - 7200 + } + return m +} + +// putRawRecords writes records with the given meta data directly into the +// bucket, bypassing Put, so that meta data is stored as given. +func putRawRecords(tb testing.TB, b *BBolt, metas map[string]*record.Meta) { + tb.Helper() + + err := b.db.Update(func(tx *bbolt.Tx) error { + bucket := tx.Bucket(bucketName) + for key, meta := range metas { + r := &TestRecord{S: key} + r.SetKey("test:" + key) + r.SetMeta(meta) + data, err := r.MarshalRecord(r) + if err != nil { + return err + } + err = bucket.Put([]byte(key), data) + if err != nil { + return err + } + } + return nil + }) + if err != nil { + tb.Fatal(err) + } +} + +// readAllMetas returns the meta data of all records in the bucket. +func readAllMetas(tb testing.TB, b *BBolt) map[string]record.Meta { + tb.Helper() + + metas := make(map[string]record.Meta) + err := b.db.View(func(tx *bbolt.Tx) error { + return tx.Bucket(bucketName).ForEach(func(k, v []byte) error { + w, err := record.NewRawWrapper(b.name, string(k), v) + if err != nil { + return err + } + metas[string(k)] = *w.Meta() + return nil + }) + }) + if err != nil { + tb.Fatal(err) + } + return metas +} + +// expectedAfterMaintenance returns the expected meta data of a record after +// MaintainRecordStates, and whether the record is expected to still exist. +func expectedAfterMaintenance(m record.Meta, now, purgeThreshold int64, shadowDelete bool) (record.Meta, bool) { + switch { + case m.Deleted == 0 && m.Expires > 0 && m.Expires < now: + if shadowDelete { + m.Deleted = m.Expires + return m, true + } + return m, false + case m.Deleted > 0 && (!shadowDelete || m.Deleted < purgeThreshold): + return m, false + default: + return m, true + } +} + +// newMixedRecords creates n records of randomly interleaved kinds. +func newMixedRecords(n int, now int64, seed int64) map[string]*record.Meta { + rng := rand.New(rand.NewSource(seed)) //nolint:gosec // Deterministic test data. + metas := make(map[string]*record.Meta, n) + for i := range n { + metas[fmt.Sprintf("rec/%06d", i)] = maintenanceTestMeta(rng.Intn(numKinds), now) + } + return metas +} + +// checkMaintained compares the database content with the expected outcome of +// maintaining the given original records. If allowUnprocessed is set, records +// may also still be in their original state (incomplete maintenance). It +// returns the number of records in maintained and in original state that +// differ between the two (ie. needed maintenance). +func checkMaintained(t *testing.T, b *BBolt, original map[string]*record.Meta, now, purgeThreshold int64, shadowDelete, allowUnprocessed bool) (processed, unprocessed int) { + t.Helper() + + got := readAllMetas(t, b) + var mismatches int + for key, orig := range original { + want, wantExists := expectedAfterMaintenance(*orig, now, purgeThreshold, shadowDelete) + gotMeta, gotExists := got[key] + maintained := gotExists == wantExists && (!wantExists || gotMeta == want) + untouched := gotExists && gotMeta == *orig + needsMaintenance := !wantExists || want != *orig + + switch { + case maintained: + if needsMaintenance { + processed++ + } + case allowUnprocessed && untouched: + unprocessed++ + default: + mismatches++ + if mismatches > 5 { + continue + } + t.Errorf("record %s: got exists=%v meta=%+v, want exists=%v meta=%+v (original %+v)", + key, gotExists, gotMeta, wantExists, want, *orig) + } + } + if mismatches > 0 { + t.Errorf("%d of %d records are not maintained correctly", mismatches, len(original)) + } + for key := range got { + if _, ok := original[key]; !ok && !strings.HasPrefix(key, "writer/") { + t.Errorf("database contains unexpected record %s", key) + } + } + return processed, unprocessed +} + +// TestMaintainRecordStatesCorrectness runs maintenance over a few thousand +// records with randomly interleaved expired, deleted and live records and +// compares the result with the expected per-record outcome. This catches +// records skipped because the bucket was modified during cursor iteration. +func TestMaintainRecordStatesCorrectness(t *testing.T) { + t.Parallel() + + for _, shadowDelete := range []bool{true, false} { + t.Run(fmt.Sprintf("shadowDelete=%v", shadowDelete), func(t *testing.T) { + t.Parallel() + + b := newPutManyTestDB(t) + now := time.Now().Unix() + purgeDeletedBefore := time.Unix(now-60, 0) + original := newMixedRecords(5000, now, 1) + putRawRecords(t, b, original) + + err := b.MaintainRecordStates(t.Context(), purgeDeletedBefore, shadowDelete) + if err != nil { + t.Fatal(err) + } + checkMaintained(t, b, original, now, purgeDeletedBefore.Unix(), shadowDelete, false) + + // Maintenance is idempotent: a second run must not change anything. + err = b.MaintainRecordStates(t.Context(), purgeDeletedBefore, shadowDelete) + if err != nil { + t.Fatal(err) + } + checkMaintained(t, b, original, now, purgeDeletedBefore.Unix(), shadowDelete, false) + }) + } +} + +// TestMaintainRecordStatesShadowDeleteThenPurge is the minimal case of a +// record being skipped: with shadow delete, an expired record is rewritten +// (Put + Seek, which leaves the cursor on a materialized node), the next record +// is purged with Cursor.Delete, which shifts the node's elements so that the +// following Cursor.Next skipped the record after it. +func TestMaintainRecordStatesShadowDeleteThenPurge(t *testing.T) { + t.Parallel() + + b := newPutManyTestDB(t) + now := time.Now().Unix() + purgeDeletedBefore := time.Unix(now-60, 0) + original := map[string]*record.Meta{ + "a": maintenanceTestMeta(kindExpired, now), + "b": maintenanceTestMeta(kindDeletedLongAgo, now), + "c": maintenanceTestMeta(kindDeletedLongAgo, now), + "d": maintenanceTestMeta(kindLive, now), + } + putRawRecords(t, b, original) + + err := b.MaintainRecordStates(t.Context(), purgeDeletedBefore, true) + if err != nil { + t.Fatal(err) + } + checkMaintained(t, b, original, now, purgeDeletedBefore.Unix(), true, false) +} + +// cancelAfterContext is a context that cancels itself on the n-th time its +// cancellation state is checked (via Done or Err), so that maintenance is +// cancelled in the middle of its walk independent of timing. +type cancelAfterContext struct { + context.Context //nolint:containedctx // Wrapped for the test. + + cancel context.CancelFunc + checks atomic.Int64 + n int64 +} + +func newCancelAfterContext(tb testing.TB, n int64) *cancelAfterContext { + tb.Helper() + + ctx, cancel := context.WithCancel(tb.Context()) + tb.Cleanup(cancel) + return &cancelAfterContext{Context: ctx, cancel: cancel, n: n} +} + +func (c *cancelAfterContext) Done() <-chan struct{} { + c.check() + return c.Context.Done() +} + +func (c *cancelAfterContext) Err() error { + c.check() + return c.Context.Err() +} + +func (c *cancelAfterContext) check() { + if c.checks.Add(1) >= c.n { + c.cancel() + } +} + +// TestMaintainRecordStatesCancel checks that a cancelled maintenance reports +// the cancellation, that the already processed records are consistently +// maintained, and that a later run completes the maintenance. +// This test changes the chunk size and must not run in parallel. +func TestMaintainRecordStatesCancel(t *testing.T) { //nolint:paralleltest // Changes the chunk size. + // Use small chunks in order to keep the test fast. + defer func(size int) { + maintenanceChunkSize = size + }(maintenanceChunkSize) + maintenanceChunkSize = 1000 + + b := newPutManyTestDB(t) + now := time.Now().Unix() + purgeDeletedBefore := time.Unix(now-60, 0) + original := newMixedRecords(10000, now, 2) + putRawRecords(t, b, original) + + // Already cancelled: nothing may be done and the caller must be told. + ctx, cancel := context.WithCancel(t.Context()) + cancel() + err := b.MaintainRecordStates(ctx, purgeDeletedBefore, true) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled for cancelled context, got %v", err) + } + processed, _ := checkMaintained(t, b, original, now, purgeDeletedBefore.Unix(), true, true) + if processed != 0 { + t.Fatalf("%d records were maintained with a cancelled context", processed) + } + + // Cancelled in the middle of the walk. + err = b.MaintainRecordStates(newCancelAfterContext(t, 3), purgeDeletedBefore, true) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled for maintenance cancelled mid-walk, got %v", err) + } + processed, unprocessed := checkMaintained(t, b, original, now, purgeDeletedBefore.Unix(), true, true) + t.Logf("cancelled mid-walk: %d records maintained, %d left for later", processed, unprocessed) + if unprocessed == 0 { + t.Fatal("maintenance was not cancelled mid-walk") + } + + // A later run completes the maintenance. + err = b.MaintainRecordStates(t.Context(), purgeDeletedBefore, true) + if err != nil { + t.Fatal(err) + } + checkMaintained(t, b, original, now, purgeDeletedBefore.Unix(), true, false) +} + +// TestMaintainRecordStatesDoesNotBlockWriters checks that other writers of the +// database can write while the maintenance walks a large bucket, instead of +// being blocked for the whole walk. +// This test changes the chunk size and must not run in parallel. +func TestMaintainRecordStatesDoesNotBlockWriters(t *testing.T) { //nolint:paralleltest // Changes the chunk size. + // Use small chunks in order to keep the test fast. + defer func(size int) { + maintenanceChunkSize = size + }(maintenanceChunkSize) + maintenanceChunkSize = 1000 + + b := newPutManyTestDB(t) + now := time.Now().Unix() + n := 20 * maintenanceChunkSize + original := make(map[string]*record.Meta, n) + for i := range n { + // Every record needs to be rewritten, making the walk long. + original[fmt.Sprintf("rec/%06d", i)] = maintenanceTestMeta(kindExpired, now) + } + putRawRecords(t, b, original) + + type write struct{ start, end time.Time } + var ( + wg sync.WaitGroup + stop = make(chan struct{}) + writes []write + ) + wg.Go(func() { + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + start := time.Now() + _, err := b.Put(newPutManyTestRecord(fmt.Sprintf("writer/%d", i))) + if err != nil { + t.Error(err) + return + } + writes = append(writes, write{start: start, end: time.Now()}) + time.Sleep(100 * time.Microsecond) + } + }) + + maintStart := time.Now() + err := b.MaintainRecordStates(t.Context(), time.Unix(now-60, 0), true) + maintEnd := time.Now() + close(stop) + wg.Wait() + if err != nil { + t.Fatal(err) + } + + // Only count writes that were done entirely while the maintenance was + // running, after it had time to take the write lock. + var ( + putsDuring int + maxLatency time.Duration + ) + for _, w := range writes { + maxLatency = max(maxLatency, w.end.Sub(w.start)) + if w.start.After(maintStart.Add(time.Millisecond)) && w.end.Before(maintEnd) { + putsDuring++ + } + } + + t.Logf("maintenance took %s, max writer latency %s, %d writes completed during maintenance", + maintEnd.Sub(maintStart), maxLatency, putsDuring) + // Without chunking, no write could be done during the walk and the + // latency of a write was the duration of the whole walk. A single slow + // write, eg. a sync on a slow CI disk, may take a good part of a short + // walk, so only a latency close to the whole walk counts as blocked. + if putsDuring < 3 || maxLatency > maintEnd.Sub(maintStart)*9/10 { + t.Fatalf("writers were blocked during maintenance: only %d writes completed during the walk of %s (max writer latency %s)", + putsDuring, maintEnd.Sub(maintStart), maxLatency) + } + checkMaintained(t, b, original, now, now-60, true, false) +} + +// BenchmarkMaintainRecordStates measures the total time of maintaining 50k +// records, with a mix of records that need to be changed and with records +// that are all up to date. +func BenchmarkMaintainRecordStates(b *testing.B) { + now := time.Now().Unix() + purgeDeletedBefore := time.Unix(now-60, 0) + unchanged := make(map[string]*record.Meta, 50000) + for i := range 50000 { + unchanged[fmt.Sprintf("rec/%06d", i)] = maintenanceTestMeta(kindLiveExpiring, now) + } + + for _, bc := range []struct { + name string + records map[string]*record.Meta + }{ + {name: "mixed", records: newMixedRecords(50000, now, 3)}, + {name: "unchanged", records: unchanged}, + } { + b.Run(bc.name, func(b *testing.B) { + db, err := NewBBolt("test", b.TempDir()) + if err != nil { + b.Fatal(err) + } + defer func() { + _ = db.Shutdown() + }() + bb := db.(*BBolt) //nolint:forcetypeassert // Test. + + b.ResetTimer() + for range b.N { + b.StopTimer() + putRawRecords(b, bb, bc.records) + b.StartTimer() + + err = bb.MaintainRecordStates(context.Background(), purgeDeletedBefore, true) + if err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/base/database/storage/bbolt/open_linux_test.go b/base/database/storage/bbolt/open_linux_test.go new file mode 100644 index 000000000..30700552f --- /dev/null +++ b/base/database/storage/bbolt/open_linux_test.go @@ -0,0 +1,67 @@ +//go:build linux + +package bbolt + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "time" +) + +// TestNewBBoltClosesDBOnBucketCreationFailure checks that NewBBolt closes the +// opened database if creating the bucket fails. Otherwise the file lock of the +// leaked database blocks every later attempt to open the same database within +// this process. +// +// The bucket creation is made to fail by limiting the maximum file size of the +// process (RLIMIT_FSIZE) to the size of a freshly initialized database file: +// bbolt.Open succeeds, but committing the bucket needs to write beyond it and +// fails with EFBIG (Go ignores the accompanying SIGXFSZ). +// This test changes a process wide limit and must not run in parallel. +func TestNewBBoltClosesDBOnBucketCreationFailure(t *testing.T) { //nolint:paralleltest // Changes a process wide limit. + dir := t.TempDir() + pageSize := int64(os.Getpagesize()) + + var orig syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_FSIZE, &orig) + if err != nil { + t.Skipf("cannot get file size limit: %s", err) + } + limited := orig + // bbolt initializes a new database file with 4 pages. + limited.Cur = uint64(4 * pageSize) //nolint:gosec // The page size is positive. + if orig.Max != ^uint64(0) && orig.Max < limited.Cur { + t.Skip("file size limit is too low") + } + err = syscall.Setrlimit(syscall.RLIMIT_FSIZE, &limited) + if err != nil { + t.Skipf("cannot set file size limit: %s", err) + } + _, err = NewBBolt("test", dir) + rErr := syscall.Setrlimit(syscall.RLIMIT_FSIZE, &orig) + if rErr != nil { + t.Fatalf("failed to restore file size limit: %s", rErr) + } + if err == nil { + t.Skip("bucket creation did not fail with a limited file size") + } + t.Logf("bucket creation failed as intended: %s", err) + fi, statErr := os.Stat(filepath.Join(dir, "db.bbolt")) + if statErr != nil || fi.Size() == 0 { + t.Fatalf("database file was not created by bbolt.Open: %v", statErr) + } + + // Opening the database again must not be blocked by the lock of the + // failed attempt. Without the fix, this fails after six open timeouts. + start := time.Now() + db, err := NewBBolt("test", dir) + if err != nil { + t.Fatalf("reopening the database after a failed open failed after %s: %s", time.Since(start), err) + } + err = db.Shutdown() + if err != nil { + t.Fatal(err) + } +} diff --git a/base/database/storage/bbolt/purge_test.go b/base/database/storage/bbolt/purge_test.go new file mode 100644 index 000000000..23bf95419 --- /dev/null +++ b/base/database/storage/bbolt/purge_test.go @@ -0,0 +1,188 @@ +package bbolt + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/safing/portmaster/base/database/query" + "github.com/safing/portmaster/base/database/record" +) + +// TestPurgeReportsCancellation checks that a cancelled purge tells the caller +// that it did not complete, instead of reporting success. +func TestPurgeReportsCancellation(t *testing.T) { + t.Parallel() + + b := newPutManyTestDB(t) + for i := range 10 { + _, err := b.Put(newPutManyTestRecord(fmt.Sprintf("purge/%d", i))) + if err != nil { + t.Fatal(err) + } + } + + for _, shadowDelete := range []bool{true, false} { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + n, err := b.Purge(ctx, query.New("test:purge/").MustBeValid(), true, true, shadowDelete) + if !errors.Is(err, context.Canceled) { + t.Errorf("shadowDelete=%v: expected context.Canceled, got %d purged and error %v", shadowDelete, n, err) + } + if n != 0 { + t.Errorf("shadowDelete=%v: %d records purged with a cancelled context", shadowDelete, n) + } + } + + // Nothing was purged. + for i := range 10 { + _, err := b.Get(fmt.Sprintf("purge/%d", i)) + if err != nil { + t.Fatalf("record purge/%d: %s", i, err) + } + } +} + +// Record kinds used by TestPurgeAcrossChunks. +const ( + purgeKindLive = iota + purgeKindSecret + purgeKindDeleted + numPurgeKinds +) + +// TestPurgeAcrossChunks checks that a purge spanning several chunks purges +// every matching record exactly once and leaves all other records untouched, +// also when the chunks end next to records that are skipped. +func TestPurgeAcrossChunks(t *testing.T) { + t.Parallel() + + for _, shadowDelete := range []bool{true, false} { + t.Run(fmt.Sprintf("shadowDelete=%v", shadowDelete), func(t *testing.T) { + t.Parallel() + + b := newPutManyTestDB(t) + now := time.Now().Unix() + deletedAt := now - 3600 + + // More than three chunks (3334 records) of live records, interleaved with + // records that must be skipped, and records around the prefix. + const total = 10000 + metas := make(map[string]*record.Meta, total+4) + wantPurged := 0 + for i := range total { + m := &record.Meta{Created: now, Modified: now} + switch i % numPurgeKinds { + case purgeKindLive: + wantPurged++ + case purgeKindSecret: + m.MakeSecret() + case purgeKindDeleted: + m.Deleted = deletedAt + } + metas[fmt.Sprintf("purge/%05d", i)] = m + } + for _, key := range []string{"purga/0", "purge", "purgf/0", "zzz"} { + metas[key] = &record.Meta{Created: now, Modified: now} + } + putRawRecords(t, b, metas) + + n, err := b.Purge(t.Context(), query.New("test:purge/").MustBeValid(), true, false, shadowDelete) + if err != nil { + t.Fatal(err) + } + if n != wantPurged { + t.Errorf("purged %d records, expected %d", n, wantPurged) + } + + after := readAllMetas(t, b) + for key, before := range metas { + m, exists := after[key] + var i int + _, scanErr := fmt.Sscanf(key, "purge/%05d", &i) + switch { + case scanErr != nil || i%numPurgeKinds != purgeKindLive: + // Not to be purged: must be unchanged. + if !exists { + t.Fatalf("record %s was removed", key) + } + if m.Deleted != before.Deleted { + t.Fatalf("record %s: deleted changed from %d to %d", key, before.Deleted, m.Deleted) + } + case shadowDelete: + if !exists || !m.IsDeleted() { + t.Fatalf("record %s was not shadow deleted", key) + } + default: + if exists { + t.Fatalf("record %s was not deleted", key) + } + } + } + + // A second purge finds nothing left to purge. + n, err = b.Purge(t.Context(), query.New("test:purge/").MustBeValid(), true, false, shadowDelete) + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("second purge purged %d records", n) + } + }) + } +} + +// BenchmarkPurge measures purging n matching records. With shadowDelete, the +// purged records stay in the bucket, so a purge that rescans them from the +// prefix for every chunk does quadratic work. +func BenchmarkPurge(b *testing.B) { + for _, shadowDelete := range []bool{true, false} { + for _, n := range []int{2000, 8000, 32000} { + b.Run(fmt.Sprintf("shadowDelete=%v/n=%d", shadowDelete, n), func(b *testing.B) { + benchmarkPurge(b, n, shadowDelete) + }) + } + } +} + +func benchmarkPurge(b *testing.B, n int, shadowDelete bool) { + b.Helper() + + db, err := NewBBolt("test", b.TempDir()) + if err != nil { + b.Fatal(err) + } + bb, ok := db.(*BBolt) + if !ok { + b.Fatal("unexpected storage type") + } + defer func() { + _ = bb.Shutdown() + }() + + now := time.Now().Unix() + metas := make(map[string]*record.Meta, n) + for i := range n { + metas[fmt.Sprintf("purge/%08d", i)] = &record.Meta{Created: now, Modified: now} + } + q := query.New("test:purge/").MustBeValid() + + b.ReportAllocs() + b.ResetTimer() + for range b.N { + // Reset the records to live ones, as the purge changes them. + b.StopTimer() + putRawRecords(b, bb, metas) + b.StartTimer() + + purged, err := bb.Purge(b.Context(), q, true, true, shadowDelete) + if err != nil { + b.Fatal(err) + } + if purged != n { + b.Fatalf("purged %d of %d records", purged, n) + } + } +} diff --git a/base/database/storage/bbolt/putmany_abort_test.go b/base/database/storage/bbolt/putmany_abort_test.go new file mode 100644 index 000000000..aca4b790d --- /dev/null +++ b/base/database/storage/bbolt/putmany_abort_test.go @@ -0,0 +1,166 @@ +package bbolt + +import ( + "bytes" + "context" + "errors" + "fmt" + "runtime" + "testing" + "time" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" +) + +var errTestAbort = errors.New("test aborts the batch") + +const abortBatchSize = 120 + +// feedAbortTestBatch feeds a batch that adds abortBatchSize records and +// changes the stored record "changed". +func feedAbortTestBatch(batch chan<- record.Record, value string) { + for i := range abortBatchSize { + batch <- newPutManyTestRecord(fmt.Sprintf("batch/%d", i)) + } + r := newPutManyTestRecord("changed") + r.S = value + batch <- r +} + +// checkAbortTestState checks the records "kept" and "changed", which are +// stored before the batch, and how many records the batch added. +func checkAbortTestState(t *testing.T, db *BBolt, changedValue string, wantAdded int) { + t.Helper() + + for key, want := range map[string]string{"kept": "old", "changed": changedValue} { + r, err := db.Get(key) + if err != nil { + t.Fatalf("record %q stored before the batch: %s", key, err) + } + got := &TestRecord{} + err = record.Unwrap(r, got) + if err != nil { + t.Fatal(err) + } + if got.S != want { + t.Errorf("record %q stored before the batch has value %q, expected %q", key, got.S, want) + } + } + + var added int + for i := range abortBatchSize { + _, err := db.Get(fmt.Sprintf("batch/%d", i)) + switch { + case err == nil: + added++ + case !errors.Is(err, storage.ErrNotFound): + t.Fatal(err) + } + } + if added != wantAdded { + t.Errorf("the batch added %d records, expected %d", added, wantAdded) + } +} + +// checkSinglePutManyResult checks that no further result is sent and that +// the batch handler has finished. +func checkSinglePutManyResult(t *testing.T, errs <-chan error) { + t.Helper() + + select { + case err := <-errs: + t.Fatalf("received second result: %v", err) + case <-time.After(100 * time.Millisecond): + } + + buf := make([]byte, 1<<20) + for range 500 { + n := runtime.Stack(buf, true) + if !bytes.Contains(buf[:n], []byte("bbolt.(*BBolt).putMany")) { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Error("batch handler is still running") +} + +// TestPutManyAbort checks that an aborted batch is discarded: none of its +// records are stored, records stored before are untouched, exactly one +// result that is not a success is sent and the batch handler ends. +// A batch that is not aborted is still stored completely. +func TestPutManyAbort(t *testing.T) { //nolint:paralleltest // Checks for batch handlers of this test, of which other tests have their own. + var _ storage.AbortableBatcher = &BBolt{} + + for _, closeBatch := range []bool{true, false} { //nolint:paralleltest // See above. + t.Run(fmt.Sprintf("close=%v", closeBatch), func(t *testing.T) { + db := newPutManyTestDB(t) + for _, key := range []string{"kept", "changed"} { + r := newPutManyTestRecord(key) + r.S = "old" + _, err := db.Put(r) + if err != nil { + t.Fatal(err) + } + } + + // Abort a batch after feeding it. The batch channel is closed + // right after the abort, as Interface.PutMany does it, or is + // left open. + abort, cancel := context.WithCancelCause(context.Background()) + batch, errs := db.PutManyAbortable(abort, true) + feedAbortTestBatch(batch, "aborted") + cancel(errTestAbort) + if closeBatch { + close(batch) + } + err := waitForPutManyResult(t, errs) + if !errors.Is(err, storage.ErrBatchAborted) || !errors.Is(err, errTestAbort) { + t.Fatalf("aborted batch returned %v, expected %v with cause %v", err, storage.ErrBatchAborted, errTestAbort) + } + checkSinglePutManyResult(t, errs) + checkAbortTestState(t, db, "old", 0) + + // A batch that is not aborted is stored. Cancelling after the + // result was sent has no effect. + abort, cancel = context.WithCancelCause(context.Background()) + batch, errs = db.PutManyAbortable(abort, true) + feedAbortTestBatch(batch, "finished") + close(batch) + err = waitForPutManyResult(t, errs) + if err != nil { + t.Fatalf("finished batch returned %v", err) + } + cancel(errTestAbort) + checkSinglePutManyResult(t, errs) + checkAbortTestState(t, db, "finished", abortBatchSize) + }) + } +} + +// TestPutManyAbortBeforeClose checks that a batch is always aborted when the +// abort is signalled before the batch channel is closed, also if the handler +// only gets to look at them afterwards. +func TestPutManyAbortBeforeClose(t *testing.T) { + t.Parallel() + + db := newPutManyTestDB(t) + + // Repeat, as the handler chooses randomly between a closed batch channel + // and the abort signal when it sees both at once. + for i := range 200 { + abort, cancel := context.WithCancelCause(context.Background()) + batch, errs := db.PutManyAbortable(abort, true) + batch <- newPutManyTestRecord("aborted") + cancel(errTestAbort) + close(batch) + err := waitForPutManyResult(t, errs) + if !errors.Is(err, storage.ErrBatchAborted) { + t.Fatalf("aborted batch %d returned %v, expected %v", i, err, storage.ErrBatchAborted) + } + } + _, err := db.Get("aborted") + if !errors.Is(err, storage.ErrNotFound) { + t.Errorf("aborted batches must not be stored, got %v", err) + } +} diff --git a/base/database/storage/bbolt/putmany_test.go b/base/database/storage/bbolt/putmany_test.go new file mode 100644 index 000000000..02562e4b3 --- /dev/null +++ b/base/database/storage/bbolt/putmany_test.go @@ -0,0 +1,186 @@ +package bbolt + +import ( + "errors" + "fmt" + "testing" + "time" + + "github.com/safing/portmaster/base/database/storage" +) + +func newPutManyTestDB(t *testing.T) *BBolt { + t.Helper() + + db, err := NewBBolt("test", t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = db.Shutdown() + }) + bb, ok := db.(*BBolt) + if !ok { + t.Fatal("unexpected storage type") + } + return bb +} + +func newPutManyTestRecord(key string) *TestRecord { + r := &TestRecord{S: key} + r.SetKey("test:" + key) + r.CreateMeta() + return r +} + +// newUnmarshalableRecord returns a record without meta data, which fails to +// marshal with "missing meta". +func newUnmarshalableRecord(key string) *TestRecord { + r := &TestRecord{S: key} + r.SetKey("test:" + key) + return r +} + +func waitForPutManyResult(t *testing.T, errs <-chan error) error { + t.Helper() + + select { + case err := <-errs: + return err + case <-time.After(10 * time.Second): + t.Fatal("PutMany did not report a result") + return nil + } +} + +// TestPutManyReportsErrorAtomically checks that a PutMany batch containing a +// record that cannot be stored reports the error and stores nothing. +// bbolt's DB.Batch re-runs a failing function solo, which used to continue +// with the remaining records of the channel and commit them with a nil error. +func TestPutManyReportsErrorAtomically(t *testing.T) { + t.Parallel() + + db := newPutManyTestDB(t) + + batch, errs := db.PutMany(true) + batch <- newPutManyTestRecord("before") + batch <- newUnmarshalableRecord("bad") + batch <- newPutManyTestRecord("after") + close(batch) + + err := waitForPutManyResult(t, errs) + if err == nil { + t.Error("PutMany with an unmarshalable record reported success") + } + for _, key := range []string{"before", "bad", "after"} { + _, err := db.Get(key) + if !errors.Is(err, storage.ErrNotFound) { + t.Errorf("record %q: expected not found after failed PutMany, got %v", key, err) + } + } +} + +// TestPutManyConcurrentFailureDoesNotLoseRecords runs a healthy and a failing +// PutMany at the same time. With DB.Batch, both were combined into one +// transaction; the failure rolled it back and the healthy function was re-run +// on its already drained channel, committing nothing while reporting success. +// Depending on the order in which bbolt combined them, either the healthy +// records were lost or the error of the failing batch was swallowed. +func TestPutManyConcurrentFailureDoesNotLoseRecords(t *testing.T) { + t.Parallel() + + db := newPutManyTestDB(t) + // Make bbolt combine exactly the two PutMany calls below, independent of + // timing: the batch only starts when both calls have joined it. + db.db.MaxBatchSize = 2 + db.db.MaxBatchDelay = time.Minute + + const healthyCount = 50 + + healthy, healthyErrs := db.PutMany(true) + failing, failingErrs := db.PutMany(true) + + for i := range healthyCount { + healthy <- newPutManyTestRecord(fmt.Sprintf("healthy/%02d", i)) + } + close(healthy) + failing <- newUnmarshalableRecord("failing") + close(failing) + + healthyErr := waitForPutManyResult(t, healthyErrs) + failingErr := waitForPutManyResult(t, failingErrs) + + if failingErr == nil { + t.Error("failing PutMany reported success") + } + if healthyErr != nil { + t.Fatalf("healthy PutMany failed: %s", healthyErr) + } + var missing int + for i := range healthyCount { + _, err := db.Get(fmt.Sprintf("healthy/%02d", i)) + if err != nil { + missing++ + } + } + if missing > 0 { + t.Errorf("healthy PutMany reported success, but %d of %d records are missing", missing, healthyCount) + } +} + +// TestPutManyIdleProducerDoesNotBlockWriters checks that a PutMany whose +// producer is idle mid-stream does not hold the bbolt write transaction, which +// would block all other writers until the producer finishes. +func TestPutManyIdleProducerDoesNotBlockWriters(t *testing.T) { + t.Parallel() + + db := newPutManyTestDB(t) + + batch, errs := db.PutMany(true) + batch <- newPutManyTestRecord("streamed/1") + // Producer idles. Give PutMany time to pick up the record (and to pass + // bbolt's batch delay of 10ms, if it is used). + time.Sleep(100 * time.Millisecond) + + putDone := make(chan error, 1) + start := time.Now() + go func() { + _, err := db.Put(newPutManyTestRecord("other")) + putDone <- err + }() + + putFinished := false + select { + case err := <-putDone: + putFinished = true + if err != nil { + t.Errorf("Put failed: %s", err) + } + t.Logf("Put during idle PutMany took %s", time.Since(start)) + case <-time.After(time.Second): + t.Errorf("Put blocked for more than %s by an idle PutMany producer", time.Since(start)) + } + + // Finish the producer, which also releases a blocked Put. + batch <- newPutManyTestRecord("streamed/2") + close(batch) + err := waitForPutManyResult(t, errs) + if err != nil { + t.Fatalf("PutMany failed: %s", err) + } + if !putFinished { + select { + case <-putDone: + t.Logf("blocked Put finished %s after it started", time.Since(start)) + case <-time.After(10 * time.Second): + t.Fatal("Put did not finish after PutMany finished") + } + } + + for _, key := range []string{"streamed/1", "streamed/2", "other"} { + _, err := db.Get(key) + if err != nil { + t.Errorf("record %q: %s", key, err) + } + } +} diff --git a/base/database/storage/bbolt/query_test.go b/base/database/storage/bbolt/query_test.go new file mode 100644 index 000000000..a43ab164c --- /dev/null +++ b/base/database/storage/bbolt/query_test.go @@ -0,0 +1,103 @@ +package bbolt + +import ( + "fmt" + "testing" + "time" + + "github.com/safing/portmaster/base/database/query" + "github.com/safing/portmaster/base/database/record" +) + +// TestQueryDoesNotBlockWriters checks that a query whose consumer is stalled +// does not keep its bbolt read transaction open. A write that has to grow the +// mmap waits for all read transactions to finish, so an open read transaction +// would block it (and with it all other writers and new readers). +func TestQueryDoesNotBlockWriters(t *testing.T) { + t.Parallel() + + db, err := NewBBolt("test", t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = db.Shutdown() + }() + + // More records than the iterator buffer holds, so the query executor + // has to wait for the consumer, and more than one query page. + const ( + total = queryPageSize*2 + 50 + testValue = "queried" + ) + for i := range total { + r := &TestRecord{S: testValue} + r.SetKey(fmt.Sprintf("test:q/%04d", i)) + r.CreateMeta() + _, err := db.Put(r) + if err != nil { + t.Fatal(err) + } + } + + it, err := db.Query(query.New("test:q/").MustBeValid(), true, true) + if err != nil { + t.Fatal(err) + } + + // Consumer stalls: wait until the iterator buffer is full. + deadline := time.Now().Add(time.Second) + for len(it.Next) < cap(it.Next) && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + + // Write a record that is larger than the current mmap (32KiB initially), + // so that bbolt has to remap the database file. The remap waits for all + // read transactions to finish. The query executor gives up a send after + // 1s, so stay well below it. + done := make(chan error, 1) + go func() { + w := &TestRecord{S: string(make([]byte, 256<<10))} + w.SetKey("test:big") + w.CreateMeta() + _, err := db.Put(w) + if err == nil { + _, err = db.Get("big") + } + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(500 * time.Millisecond): + t.Fatal("writer blocked by a query with a stalled consumer") + } + + // Resume consuming: all matching records must still be delivered, in + // key order. + cnt := 0 + for r := range it.Next { + if want := fmt.Sprintf("q/%04d", cnt); r.DatabaseKey() != want { + t.Fatalf("unexpected record %q, want %q", r.DatabaseKey(), want) + } + // The records must own their data, as the read transaction (and with + // it the mmapped data) is gone by now. + got := &TestRecord{} + err := record.Unwrap(r, got) + if err != nil { + t.Fatal(err) + } + if got.S != testValue { + t.Fatalf("unexpected record data: %q", got.S) + } + cnt++ + } + if it.Err() != nil { + t.Fatal(it.Err()) + } + if cnt != total { + t.Fatalf("unexpected query result count: %d", cnt) + } +} diff --git a/base/database/storage/errors.go b/base/database/storage/errors.go index f85340460..a38f8a18b 100644 --- a/base/database/storage/errors.go +++ b/base/database/storage/errors.go @@ -6,4 +6,7 @@ import "errors" var ( ErrNotFound = errors.New("storage entry not found") ErrRecordMalformed = errors.New("record is malformed") + // ErrBatchAborted is reported by an AbortableBatcher for a batch that was + // aborted and thus not stored. + ErrBatchAborted = errors.New("batch aborted") ) diff --git a/base/database/storage/hashmap/map.go b/base/database/storage/hashmap/map.go index 7114781f4..ccd540780 100644 --- a/base/database/storage/hashmap/map.go +++ b/base/database/storage/hashmap/map.go @@ -66,6 +66,11 @@ func (hm *HashMap) Put(r record.Record) (record.Record, error) { } // PutMany stores many records in the database. +// Every record is stored as soon as it is received, so a batch is not atomic +// and cannot be rolled back. The hashmap therefore does not implement +// storage.AbortableBatcher on purpose: when a batch is aborted (see +// database.Interface.PutMany), the records passed on before stay stored, and +// the batch result says so. func (hm *HashMap) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { hm.dbLock.Lock() defer hm.dbLock.Unlock() @@ -123,24 +128,16 @@ func (hm *HashMap) Query(q *query.Query, local, internal bool) (*iterator.Iterat } func (hm *HashMap) queryExecutor(queryIter *iterator.Iterator, q *query.Query, local, internal bool) { - hm.dbLock.RLock() - defer hm.dbLock.RUnlock() + // Collect the matching records under the lock, but feed them to the + // consumer only after releasing it, so that a slow consumer does not + // block writers (and, through a waiting writer, all other readers). + // Only the record pointers are held, the records are not copied. + matches := hm.queryMatches(q, local, internal) var err error mapLoop: - for key, record := range hm.db { - record.Lock() - if !q.MatchesKey(key) || - !q.MatchesRecord(record) || - !record.Meta().CheckValidity() || - !record.Meta().CheckPermission(local, internal) { - - record.Unlock() - continue - } - record.Unlock() - + for _, record := range matches { select { case <-queryIter.Done: break mapLoop @@ -214,3 +211,25 @@ func (hm *HashMap) MaintainRecordStates(ctx context.Context, purgeDeletedBefore func (hm *HashMap) Shutdown() error { return nil } + +func (hm *HashMap) queryMatches(q *query.Query, local, internal bool) []record.Record { + hm.dbLock.RLock() + defer hm.dbLock.RUnlock() + + var matches []record.Record + for key, r := range hm.db { + if !q.MatchesKey(key) { + continue + } + + r.Lock() + if q.MatchesRecord(r) && + r.Meta().CheckValidity() && + r.Meta().CheckPermission(local, internal) { + matches = append(matches, r) + } + r.Unlock() + } + + return matches +} diff --git a/base/database/storage/hashmap/map_test.go b/base/database/storage/hashmap/map_test.go index ff310c2d0..8ed95dba5 100644 --- a/base/database/storage/hashmap/map_test.go +++ b/base/database/storage/hashmap/map_test.go @@ -16,7 +16,7 @@ var ( _ storage.Batcher = &HashMap{} ) -type TestRecord struct { //nolint:maligned +type TestRecord struct { record.Base sync.Mutex S string diff --git a/base/database/storage/hashmap/query_test.go b/base/database/storage/hashmap/query_test.go new file mode 100644 index 000000000..6b1b4db7d --- /dev/null +++ b/base/database/storage/hashmap/query_test.go @@ -0,0 +1,79 @@ +package hashmap + +import ( + "fmt" + "testing" + "time" + + "github.com/safing/portmaster/base/database/query" +) + +// TestQueryDoesNotBlockWriters checks that a query whose consumer is stalled +// does not hold the storage lock and thereby block writers (and, through +// the waiting writer, all other readers). +func TestQueryDoesNotBlockWriters(t *testing.T) { + t.Parallel() + + db, err := NewHashMap("test", "") + if err != nil { + t.Fatal(err) + } + + // More records than the iterator buffer holds, so the query executor + // has to wait for the consumer. + const total = 50 + for i := range total { + r := &TestRecord{} + r.SetKey(fmt.Sprintf("test:q/%d", i)) + r.CreateMeta() + _, err := db.Put(r) + if err != nil { + t.Fatal(err) + } + } + + it, err := db.Query(query.New("test:q/").MustBeValid(), true, true) + if err != nil { + t.Fatal(err) + } + + // Consumer stalls: wait until the iterator buffer is full. + deadline := time.Now().Add(time.Second) + for len(it.Next) < cap(it.Next) && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + + // A writer and a reader must not be blocked by the stalled query. + // The query executor gives up a send after 1s, so stay well below it. + done := make(chan error, 1) + go func() { + w := &TestRecord{} + w.SetKey("test:other") + w.CreateMeta() + _, err := db.Put(w) + if err == nil { + _, err = db.Get("other") + } + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(300 * time.Millisecond): + t.Fatal("writer blocked by a query with a stalled consumer") + } + + // Resume consuming: all matching records must still be delivered. + cnt := 0 + for range it.Next { + cnt++ + } + if it.Err() != nil { + t.Fatal(it.Err()) + } + if cnt != total { + t.Fatalf("unexpected query result count: %d", cnt) + } +} diff --git a/base/database/storage/interface.go b/base/database/storage/interface.go index 7bdd84f80..c2fb1a371 100644 --- a/base/database/storage/interface.go +++ b/base/database/storage/interface.go @@ -42,6 +42,27 @@ type Batcher interface { PutMany(shadowDelete bool) (batch chan<- record.Record, errs <-chan error) } +// AbortableBatcher defines the database storage API for backends that can +// discard a batch instead of storing it. +// +// PutManyAbortable works like Batcher.PutMany: the batch is fed through the +// batch channel and ends when that channel is closed, and exactly one value +// is sent on the error channel. In addition, the batch is aborted when ctx is +// done before the batch channel is closed: none of its records are stored, +// records stored before are left untouched and the result is an error that +// wraps ErrBatchAborted. An aborted batch is never reported as success. +// +// To abort, cancel ctx first and then close the batch channel as usual. The +// storage must check ctx when it sees the closed batch channel, so that this +// order always aborts. Cancelling ctx after the batch channel was closed +// does not reliably abort the batch anymore, and has no effect once the +// result was sent. Without a cancellation, PutManyAbortable must behave +// exactly like PutMany. +type AbortableBatcher interface { + Batcher + PutManyAbortable(ctx context.Context, shadowDelete bool) (batch chan<- record.Record, errs <-chan error) +} + // Purger defines the database storage API for backends that support the purge operation. type Purger interface { Purge(ctx context.Context, q *query.Query, local, internal, shadowDelete bool) (int, error) diff --git a/base/database/storage/sqlite/prepared.go b/base/database/storage/sqlite/prepared.go index c2ab33745..e0ca2aac2 100644 --- a/base/database/storage/sqlite/prepared.go +++ b/base/database/storage/sqlite/prepared.go @@ -1,15 +1,19 @@ package sqlite import ( + "context" + "errors" "fmt" + "strconv" + "strings" "github.com/stephenafamo/bob" + "github.com/stephenafamo/bob/dialect/sqlite" "github.com/stephenafamo/bob/dialect/sqlite/im" "github.com/stephenafamo/bob/expr" "github.com/safing/portmaster/base/database/record" "github.com/safing/portmaster/base/database/storage" - "github.com/safing/portmaster/base/database/storage/sqlite/models" "github.com/safing/structures/dsd" ) @@ -26,6 +30,11 @@ var recordColumns = []string{"key", "format", "value", "created", "modified", "e // buildUpsert builds an INSERT for the given number of rows that replaces // existing records with the same key. +// +// The statement is built with the plain SQLite dialect, not with the +// generated table model: the model adds a RETURNING clause with every +// column, so SQLite would produce a result row with the full record value +// for each write, only for the driver to discard it. func (db *SQLite) buildUpsert(rows int) (string, error) { valueRows := make([][]bob.Expression, rows) for i := range valueRows { @@ -37,7 +46,7 @@ func (db *SQLite) buildUpsert(rows int) (string, error) { } // Simulate upsert with custom selection on conflict. - rawQuery, _, err := models.Records.Insert( + rawQuery, _, err := sqlite.Insert( im.Into("records", recordColumns...), im.Rows(valueRows...), im.OnConflict("key").DoUpdate( @@ -47,11 +56,54 @@ func (db *SQLite) buildUpsert(rows int) (string, error) { if err != nil { return "", fmt.Errorf("build upsert for %d rows: %w", rows, err) } - return rawQuery, nil + return anonymizePlaceholders(rawQuery, rows*len(recordColumns)) } -// PutMany stores many records in the database. -func (db *SQLite) putManyWithPreparedStmts(shadowDelete bool) (chan<- record.Record, <-chan error) { +var errUnexpectedPlaceholders = errors.New("unexpected placeholders in upsert") + +// anonymizePlaceholders replaces the numbered placeholders ?1, ?2, ... ?n in +// query with anonymous ? placeholders. SQLite numbers anonymous placeholders +// in the order they appear, so this is only done if the numbered placeholders +// appear exactly in the order 1..n; otherwise an error is returned. +// +// The modernc.org/sqlite driver matches every numbered placeholder against +// all arguments by formatting each argument's ordinal as a string, which +// makes binding the arguments of a multi-row insert quadratic and allocate +// for every comparison. Anonymous placeholders are matched by ordinal. +func anonymizePlaceholders(query string, n int) (string, error) { + var b strings.Builder + b.Grow(len(query)) + + next := 1 + for i := 0; i < len(query); i++ { + c := query[i] + b.WriteByte(c) + if c != '?' { + continue + } + + // Read the placeholder number. + end := i + 1 + for end < len(query) && query[end] >= '0' && query[end] <= '9' { + end++ + } + num, err := strconv.Atoi(query[i+1 : end]) + if err != nil || num != next { + return "", fmt.Errorf("%w: found %q, expected ?%d", errUnexpectedPlaceholders, query[i:end], next) + } + next++ + i = end - 1 + } + + if next-1 != n { + return "", fmt.Errorf("%w: found %d, expected %d", errUnexpectedPlaceholders, next-1, n) + } + return b.String(), nil +} + +// putManyWithPreparedStmts stores many records in the database. The batch is +// rolled back if abort is done before the batch channel is closed. +func (db *SQLite) putManyWithPreparedStmts(abort context.Context) (chan<- record.Record, <-chan error) { batch := make(chan record.Record, 100) errs := make(chan error, 1) @@ -77,10 +129,13 @@ func (db *SQLite) putManyWithPreparedStmts(shadowDelete bool) (chan<- record.Rec } // start handler + db.batchWg.Add(1) go func() { + defer db.batchWg.Done() // Arguments of the records collected for the next statement. args := make([]any, 0, upsertRowsPerStatement*len(recordColumns)) pending := 0 + var err error // Read all put records. writeBatch: @@ -89,9 +144,9 @@ func (db *SQLite) putManyWithPreparedStmts(shadowDelete bool) (chan<- record.Rec case r := <-batch: if r != nil { // Collect record and write when a full statement is reached. - recordArgs, err := upsertArgs(r) + var recordArgs []any + recordArgs, err = upsertArgs(r) if err != nil { - errs <- err break writeBatch } args = append(args, recordArgs...) @@ -102,22 +157,27 @@ func (db *SQLite) putManyWithPreparedStmts(shadowDelete bool) (chan<- record.Rec _, err = preparedStmt.ExecContext(db.ctx, args...) if err != nil { - errs <- err break writeBatch } args = args[:0] pending = 0 } else { + // Also check for an abort when the batch channel was + // closed, as it is closed right after the abort. + if abort.Err() != nil { + err = batchAbortedErr(abort) + break writeBatch + } + // Write the remaining records with a statement of matching size. if pending > 0 { - remainderUpsert, err := db.buildUpsert(pending) + var remainderUpsert string + remainderUpsert, err = db.buildUpsert(pending) if err != nil { - errs <- err break writeBatch } _, err = tx.ExecContext(db.ctx, remainderUpsert, args...) if err != nil { - errs <- err break writeBatch } } @@ -127,13 +187,20 @@ func (db *SQLite) putManyWithPreparedStmts(shadowDelete bool) (chan<- record.Rec return } + case <-abort.Done(): + err = batchAbortedErr(abort) + break writeBatch + case <-db.ctx.Done(): + err = db.shuttingDownErr() break writeBatch } } - // Rollback transaction. - errs <- tx.Rollback(db.ctx) + // Rollback transaction and report why the batch was aborted. + // Exactly one value must be sent on errs. + db.rollbackBatch(tx) + errs <- err }() return batch, errs @@ -144,6 +211,12 @@ func upsertArgs(r record.Record) ([]any, error) { r.Lock() defer r.Unlock() + return recordArgs(r) +} + +// recordArgs returns the statement arguments of r in recordColumns order. +// The caller must hold the lock of r. +func recordArgs(r record.Record) ([]any, error) { // default serialization format - JSON format := uint8(dsd.JSON) diff --git a/base/database/storage/sqlite/prepared_test.go b/base/database/storage/sqlite/prepared_test.go index 8a90bcb94..3814aa451 100644 --- a/base/database/storage/sqlite/prepared_test.go +++ b/base/database/storage/sqlite/prepared_test.go @@ -2,9 +2,47 @@ package sqlite import ( "strconv" + "strings" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +func TestAnonymizePlaceholders(t *testing.T) { + t.Parallel() + + q, err := anonymizePlaceholders("INSERT INTO t(a, b) VALUES (?1, ?2), (?3, ?4) RETURNING a", 4) + require.NoError(t, err) + assert.Equal(t, "INSERT INTO t(a, b) VALUES (?, ?), (?, ?) RETURNING a", q) + + // Placeholders out of order, missing or of an unexpected count are rejected. + for _, query := range []string{ + "VALUES (?2, ?1, ?3, ?4)", + "VALUES (?1, ?2, ?4, ?5)", + "VALUES (?1, ?2, ?3)", + "VALUES (?1, ?2, ?3, ?4, ?5)", + "VALUES (?1, ?2, ?, ?)", + "VALUES (?1, ?2, ?3, :a)", + } { + _, err := anonymizePlaceholders(query, 4) + assert.Error(t, err, query) + } +} + +func TestBuildUpsertPlaceholders(t *testing.T) { + t.Parallel() + + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + defer func() { _ = db.Shutdown() }() + + q, err := db.buildUpsert(upsertRowsPerStatement) + require.NoError(t, err) + assert.NotContains(t, q, "?1") + assert.Contains(t, q, "(?, ?, ?, ?, ?, ?, ?, ?, ?)") +} + func BenchmarkPutMany(b *testing.B) { // Configure prepared statement usage. origSetting := UsePreparedStatements @@ -84,3 +122,15 @@ func benchPutMany(b *testing.B) { //nolint:thelper b.Fatal(err) } } + +func TestUpsertHasNoReturning(t *testing.T) { + t.Parallel() + + db := &SQLite{ctx: t.Context()} + for _, rows := range []int{1, upsertRowsPerStatement} { + q, err := db.buildUpsert(rows) + require.NoError(t, err) + assert.NotContains(t, strings.ToUpper(q), "RETURNING") + assert.Contains(t, q, "ON CONFLICT") + } +} diff --git a/base/database/storage/sqlite/putmany_abort_test.go b/base/database/storage/sqlite/putmany_abort_test.go new file mode 100644 index 000000000..da2d2badb --- /dev/null +++ b/base/database/storage/sqlite/putmany_abort_test.go @@ -0,0 +1,169 @@ +package sqlite + +import ( + "context" + "errors" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" +) + +var errTestAbort = errors.New("test aborts the batch") + +// abortBatchSize is more than one statement of the prepared variant writes, +// so that an aborted batch has already written records in its transaction. +const abortBatchSize = 2*upsertRowsPerStatement + 20 + +// feedAbortTestBatch feeds a batch that adds abortBatchSize records and +// changes the stored record "changed". +func feedAbortTestBatch(batch chan<- record.Record, value string) { + for i := range abortBatchSize { + r := newPutManyTestRecord("batch/" + strconv.Itoa(i)) + r.S = value + batch <- r + } + r := newPutManyTestRecord("changed") + r.S = value + batch <- r +} + +// requireAbortTestState checks the records "kept" and "changed", which are +// stored before the batch, and how many records the batch added. +func requireAbortTestState(t *testing.T, db *SQLite, changedValue string, wantAdded int) { + t.Helper() + + for key, want := range map[string]string{"kept": "before", "changed": changedValue} { + r, err := db.Get(key) + require.NoError(t, err, "record %q stored before the batch", key) + got := &TestRecord{} + require.NoError(t, record.Unwrap(r, got)) + assert.Equal(t, want, got.S, "record %q stored before the batch", key) + } + + var added int + for i := range abortBatchSize { + _, err := db.Get("batch/" + strconv.Itoa(i)) + if err == nil { + added++ + } else { + require.ErrorIs(t, err, storage.ErrNotFound) + } + } + assert.Equal(t, wantAdded, added, "records added by the batch") +} + +// requireNoSecondPutManyResult checks that no further result is sent. +func requireNoSecondPutManyResult(t *testing.T, errs <-chan error) { + t.Helper() + + select { + case err := <-errs: + t.Fatalf("received second result: %v", err) + case <-time.After(100 * time.Millisecond): + } +} + +// TestPutManyAbort checks that an aborted batch is rolled back: none of its +// records are stored, records stored before are untouched, exactly one +// result that is not a success is sent and the database is released. +// A batch that is not aborted is still committed completely. +func TestPutManyAbort(t *testing.T) { //nolint:paralleltest // Switches package-wide setting. + runPutManyVariants(t, testPutManyAbort) +} + +func testPutManyAbort(t *testing.T) { + t.Helper() + + var _ storage.AbortableBatcher = &SQLite{} + + for _, closeBatch := range []bool{true, false} { + t.Run("close="+strconv.FormatBool(closeBatch), func(t *testing.T) { + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + for _, key := range []string{"kept", "changed"} { + r := newPutManyTestRecord(key) + r.S = "before" + _, err = db.Put(r) + require.NoError(t, err) + } + + // Abort a batch after feeding it. The batch channel is closed + // right after the abort, as Interface.PutMany does it, or is + // left open. + abort, cancel := context.WithCancelCause(context.Background()) + batch, errs := db.PutManyAbortable(abort, false) + feedAbortTestBatch(batch, "aborted") + cancel(errTestAbort) + if closeBatch { + close(batch) + } + err = readPutManyResult(t, errs) + require.ErrorIs(t, err, storage.ErrBatchAborted) + require.ErrorIs(t, err, errTestAbort) + requireNoSecondPutManyResult(t, errs) + + // The transaction is rolled back, which also releases the + // (single) database connection for the checks. + requireAbortTestState(t, db, "before", 0) + + // A batch that is not aborted is committed. Cancelling after + // the result was sent has no effect. + abort, cancel = context.WithCancelCause(context.Background()) + batch, errs = db.PutManyAbortable(abort, false) + feedAbortTestBatch(batch, "finished") + close(batch) + require.NoError(t, readPutManyResult(t, errs)) + cancel(errTestAbort) + requireNoSecondPutManyResult(t, errs) + requireAbortTestState(t, db, "finished", abortBatchSize) + + // Shutdown waits for the batch handlers, so none is left behind. + shutdownDone := make(chan error, 1) + go func() { + shutdownDone <- db.Shutdown() + }() + select { + case err := <-shutdownDone: + require.NoError(t, err) + case <-time.After(10 * time.Second): + t.Fatal("a batch handler is still running") + } + }) + } +} + +// TestPutManyAbortBeforeClose checks that a batch is always aborted when the +// abort is signalled before the batch channel is closed, also if the handler +// only gets to look at them afterwards. +func TestPutManyAbortBeforeClose(t *testing.T) { //nolint:paralleltest // Switches package-wide setting. + runPutManyVariants(t, testPutManyAbortBeforeClose) +} + +func testPutManyAbortBeforeClose(t *testing.T) { + t.Helper() + + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + + // Repeat, as the handler chooses randomly between a closed batch channel + // and the abort signal when it sees both at once. + for i := range 200 { + abort, cancel := context.WithCancelCause(context.Background()) + batch, errs := db.PutManyAbortable(abort, false) + batch <- newPutManyTestRecord("aborted") + cancel(errTestAbort) + close(batch) + err = readPutManyResult(t, errs) + require.ErrorIs(t, err, storage.ErrBatchAborted, "batch %d", i) + } + _, err = db.Get("aborted") + require.ErrorIs(t, err, storage.ErrNotFound, "aborted batches must not be committed") + + require.NoError(t, db.Shutdown()) +} diff --git a/base/database/storage/sqlite/putmany_test.go b/base/database/storage/sqlite/putmany_test.go new file mode 100644 index 000000000..3a5b7275d --- /dev/null +++ b/base/database/storage/sqlite/putmany_test.go @@ -0,0 +1,201 @@ +package sqlite + +import ( + "bytes" + "errors" + "runtime" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/database/storage" + "github.com/safing/structures/dsd" +) + +// runPutManyVariants runs the test with and without prepared statements. +// Callers must not be parallel, as this switches the package-wide +// UsePreparedStatements setting. +func runPutManyVariants(t *testing.T, test func(t *testing.T)) { + t.Helper() + + origSetting := UsePreparedStatements + t.Cleanup(func() { UsePreparedStatements = origSetting }) + + for _, usePrepared := range []bool{true, false} { + t.Run("prepared="+strconv.FormatBool(usePrepared), func(t *testing.T) { + UsePreparedStatements = usePrepared + test(t) + }) + } +} + +func newPutManyTestRecord(key string) *TestRecord { + r := &TestRecord{S: "batch"} + r.SetKey("test:" + key) + r.UpdateMeta() + return r +} + +// readPutManyResult reads the result of a PutMany batch with a timeout. +func readPutManyResult(t *testing.T, errs <-chan error) error { + t.Helper() + + select { + case err := <-errs: + return err + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for the PutMany result") + return nil + } +} + +// TestPutManyWriteError checks that a failed write is reported, rolls back +// the batch and releases the database. +func TestPutManyWriteError(t *testing.T) { //nolint:paralleltest // Switches package-wide setting. + runPutManyVariants(t, testPutManyWriteError) +} + +func testPutManyWriteError(t *testing.T) { + t.Helper() + + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + + // Write a valid record and one that cannot be serialized. + badRecord, err := record.NewWrapper("test:bad", &record.Meta{}, 255, []byte("bad")) + require.NoError(t, err) + batch, errs := db.PutMany(false) + batch <- newPutManyTestRecord("good") + batch <- badRecord + + // Wait for the result without reading it. + require.Eventually(t, func() bool { return len(errs) > 0 }, 10*time.Second, time.Millisecond) + + // The transaction must have been rolled back already, releasing the + // (single) database connection, even if the caller has not read the + // result yet. + getDone := make(chan error, 1) + go func() { + _, err := db.Get("good") + getDone <- err + }() + var result error + select { + case err := <-getDone: + require.ErrorIs(t, err, storage.ErrNotFound, "batch must not be committed") + result = readPutManyResult(t, errs) + case <-time.After(5 * time.Second): + t.Error("database is blocked by the failed batch until its result is read") + // Read the result to unblock the database and finish the test. + result = readPutManyResult(t, errs) + <-getDone + } + require.ErrorIs(t, result, dsd.ErrIncompatibleFormat) + + // Exactly one result must be sent. + select { + case err := <-errs: + t.Fatalf("received second result: %v", err) + case <-time.After(100 * time.Millisecond): + } + + require.NoError(t, db.Shutdown()) +} + +// TestPutManyShutdown checks that a batch aborted by a shutdown of the +// database does not report success. +func TestPutManyShutdown(t *testing.T) { //nolint:paralleltest // Switches package-wide setting. + runPutManyVariants(t, testPutManyShutdown) +} + +func testPutManyShutdown(t *testing.T) { + t.Helper() + + // Repeat, as the outcome before the fix depended on timing. + for i := range 20 { + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + + batch, errs := db.PutMany(false) + batch <- newPutManyTestRecord("aborted") + db.cancelCtx() + err = readPutManyResult(t, errs) + assert.Error(t, err, "aborted batch %d must not report success", i) + assert.False(t, errors.Is(err, dsd.ErrIncompatibleFormat)) + + // Closing the database afterwards synchronizes with the watchers. + waitForTxWatchers(t) + require.NoError(t, db.Shutdown()) + } +} + +// waitForTxWatchers waits until database/sql has finished rolling back the +// transactions of canceled contexts. It does so in background goroutines +// that may outlive the database and read the global time.Local, which +// TestMigrationTimezoneRoundTrip changes. +func waitForTxWatchers(t *testing.T) { + t.Helper() + + buf := make([]byte, 1<<20) + for range 500 { + n := runtime.Stack(buf, true) + if !bytes.Contains(buf[:n], []byte("database/sql.(*Tx).awaitDone")) { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Log("database/sql transaction watchers did not finish") +} + +// TestPutManyShutdownWhileWriting checks that shutting down the database while +// a batch is being written neither misuses the WaitGroup that Shutdown waits +// on nor leaves the batch handler running. +func TestPutManyShutdownWhileWriting(t *testing.T) { //nolint:paralleltest // Switches package-wide setting. + runPutManyVariants(t, testPutManyShutdownWhileWriting) +} + +func testPutManyShutdownWhileWriting(t *testing.T) { + t.Helper() + + for i := range 50 { + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + + batch, errs := db.PutMany(false) + + // Feed the batch until it is aborted. + fed := make(chan struct{}) + feederDone := make(chan struct{}) + go func() { + defer close(feederDone) + for n := 0; ; n++ { + select { + case batch <- newPutManyTestRecord(strconv.Itoa(n)): + if n == 20 { + close(fed) + } + case <-db.ctx.Done(): + return + } + } + }() + <-fed + + // Shut down while the handler writes records. + require.NoError(t, db.Shutdown()) + <-feederDone + + // The handler must have finished and reported the abort. + select { + case err := <-errs: + assert.Error(t, err, "aborted batch %d must not report success", i) + default: + t.Fatalf("batch handler %d is still running after Shutdown returned", i) + } + waitForTxWatchers(t) + } +} diff --git a/base/database/storage/sqlite/sqlite.go b/base/database/storage/sqlite/sqlite.go index 5d9ba5181..3334cd766 100644 --- a/base/database/storage/sqlite/sqlite.go +++ b/base/database/storage/sqlite/sqlite.go @@ -9,13 +9,11 @@ import ( "sync" "time" - "github.com/aarondl/opt/omit" - "github.com/aarondl/opt/omitnull" migrate "github.com/rubenv/sql-migrate" sqldblogger "github.com/simukti/sqldb-logger" "github.com/stephenafamo/bob" - "github.com/stephenafamo/bob/dialect/sqlite" - "github.com/stephenafamo/bob/dialect/sqlite/im" + "github.com/stephenafamo/bob/dialect/sqlite/dialect" + "github.com/stephenafamo/bob/dialect/sqlite/sm" "github.com/stephenafamo/bob/dialect/sqlite/um" _ "modernc.org/sqlite" @@ -26,14 +24,18 @@ import ( "github.com/safing/portmaster/base/database/storage" "github.com/safing/portmaster/base/database/storage/sqlite/models" "github.com/safing/portmaster/base/log" - "github.com/safing/structures/dsd" ) // Errors. var ( ErrQueryTimeout = errors.New("query timeout") + + errShuttingDown = errors.New("database is shutting down") ) +// queryPageSize is the number of rows a query loads from the database at once. +const queryPageSize = 100 + // SQLite storage. type SQLite struct { name string @@ -41,6 +43,13 @@ type SQLite struct { db *sql.DB bob bob.DB wg sync.WaitGroup + // batchWg tracks the handlers of PutMany batches, which keep running + // after PutMany returned. They must not use wg, as Shutdown may already + // wait on it. + batchWg sync.WaitGroup + + // singleUpsert writes one record, see buildUpsert. + singleUpsert string ctx context.Context cancelCtx context.CancelFunc @@ -109,13 +118,20 @@ func openSQLite(name, location string, printStmts bool) (*SQLite, error) { // Return as bob database. ctx, cancelCtx := context.WithCancel(context.Background()) - return &SQLite{ + sqliteDB := &SQLite{ name: name, db: db, bob: bob.NewDB(db), ctx: ctx, cancelCtx: cancelCtx, - }, nil + } + sqliteDB.singleUpsert, err = sqliteDB.buildUpsert(1) + if err != nil { + cancelCtx() + _ = db.Close() + return nil, err + } + return sqliteDB, nil } // Get returns a database record. @@ -151,74 +167,31 @@ func (db *SQLite) GetMeta(key string) (*record.Meta, error) { // Put stores a record in the database. func (db *SQLite) Put(r record.Record) (record.Record, error) { + db.wg.Add(1) + defer db.wg.Done() + return db.putRecord(r, nil) } +// putRecord writes the record. It does not register as a database operation +// that Shutdown waits for, as it is also used by the batch handlers. func (db *SQLite) putRecord(r record.Record, tx *bob.Tx) (record.Record, error) { - db.wg.Add(1) - defer db.wg.Done() - // Lock record if in a transaction. if tx != nil { r.Lock() defer r.Unlock() } - // default serialization format - JSON - format := uint8(dsd.JSON) - - // For wrapped records, check the required format - if r.IsWrapped() { - wrapper, ok := r.(*record.Wrapper) - if !ok { - return nil, fmt.Errorf("%w: reports to be wrapped but is not of type *record.Wrapper", storage.ErrRecordMalformed) - } - format, ok = dsd.ValidateSerializationFormat(wrapper.Format) - if !ok { - return nil, dsd.ErrIncompatibleFormat - } - } - - // Serialize. - data, err := r.MarshalDataOnly(r, format) + args, err := recordArgs(r) if err != nil { return nil, err } - // Prepare for setter. - setFormat := omitnull.From(int64(format)) - setData := omitnull.From(data) - if len(data) == 0 { - setFormat.Null() - setData.Null() - } - - // Create structure for insert. - m := r.Meta() - setter := models.RecordSetter{ - Key: omit.From(r.DatabaseKey()), - Format: setFormat, - Value: setData, - Created: omit.From(m.Created), - Modified: omit.From(m.Modified), - Expires: omit.From(m.Expires), - Deleted: omit.From(m.Deleted), - Secret: omit.From(m.IsSecret()), - Crownjewel: omit.From(m.IsCrownJewel()), - } - - // Simulate upsert with custom selection on conflict. - dbQuery := models.Records.Insert( - &setter, - im.OnConflict("key").DoUpdate( - im.SetExcluded("format", "value", "created", "modified", "expires", "deleted", "secret", "crownjewel"), - ), - ) // Execute in transaction or directly. if tx != nil { - _, err = dbQuery.Exec(db.ctx, tx) + _, err = tx.ExecContext(db.ctx, db.singleUpsert, args...) } else { - _, err = dbQuery.Exec(db.ctx, db.bob) + _, err = db.bob.ExecContext(db.ctx, db.singleUpsert, args...) } if err != nil { return nil, err @@ -229,12 +202,19 @@ func (db *SQLite) putRecord(r record.Record, tx *bob.Tx) (record.Record, error) // PutMany stores many records in the database. func (db *SQLite) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error) { + return db.PutManyAbortable(context.Background(), shadowDelete) +} + +// PutManyAbortable stores many records in the database like PutMany, unless +// abort is done before the batch channel is closed: the transaction of the +// batch is then rolled back and the result wraps storage.ErrBatchAborted. +func (db *SQLite) PutManyAbortable(abort context.Context, shadowDelete bool) (chan<- record.Record, <-chan error) { db.wg.Add(1) defer db.wg.Done() // Check if we should use prepared statement optimized inserting. if UsePreparedStatements { - return db.putManyWithPreparedStmts(shadowDelete) + return db.putManyWithPreparedStmts(abort) } batch := make(chan record.Record, 100) @@ -247,7 +227,11 @@ func (db *SQLite) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error } // start handler + db.batchWg.Add(1) go func() { + defer db.batchWg.Done() + var err error + // Read all put records. writeBatch: for { @@ -255,24 +239,37 @@ func (db *SQLite) PutMany(shadowDelete bool) (chan<- record.Record, <-chan error case r := <-batch: if r != nil { // Write record. - _, err := db.putRecord(r, &tx) + _, err = db.putRecord(r, &tx) if err != nil { - errs <- err break writeBatch } } else { + // Also check for an abort when the batch channel was + // closed, as it is closed right after the abort. + if abort.Err() != nil { + err = batchAbortedErr(abort) + break writeBatch + } + // Finalize transcation. errs <- tx.Commit(db.ctx) return } + case <-abort.Done(): + err = batchAbortedErr(abort) + break writeBatch + case <-db.ctx.Done(): + err = db.shuttingDownErr() break writeBatch } } - // Rollback transaction. - errs <- tx.Rollback(db.ctx) + // Rollback transaction and report why the batch was aborted. + // Exactly one value must be sent on errs. + db.rollbackBatch(tx) + errs <- err }() return batch, errs @@ -307,84 +304,46 @@ func (db *SQLite) queryExecutor(queryIter *iterator.Iterator, q *query.Query, lo db.wg.Add(1) defer db.wg.Done() - // Build query. - var recordQuery *sqlite.ViewQuery[*models.Record, models.RecordSlice] - if q.DatabaseKeyPrefix() != "" { - recordQuery = models.Records.View.Query( - models.SelectWhere.Records.Key.Like(q.DatabaseKeyPrefix() + "%"), - ) - } else { - recordQuery = models.Records.View.Query() - } - - // Get cursor to go over all records in the query. - cursor, err := models.RecordsQuery.Cursor(recordQuery, db.ctx, db.bob) - if err != nil { - queryIter.Finish(err) - return - } - defer func() { - _ = cursor.Close() - }() + var ( + err error + lastKey string + firstPage = true + page models.RecordSlice + ) -recordsLoop: - for cursor.Next() { - // Get next record - r, cErr := cursor.Get() - if cErr != nil { - err = fmt.Errorf("cursor error: %w", cErr) - break recordsLoop + // Load the records page by page (keyset pagination over the primary key). + // Each page is fully loaded before it is handed to the consumer, so that + // the single database connection is not held while waiting for the + // consumer. Otherwise, all other database operations - including any the + // consumer itself does while iterating - would block until the query ends. +pagesLoop: + for { + mods := []bob.Mod[*dialect.SelectQuery]{ + sm.OrderBy(models.Records.Columns.Key).Asc(), + sm.Limit(queryPageSize), } - - // Check if key matches. - if !q.MatchesKey(r.Key) { - continue recordsLoop + if q.DatabaseKeyPrefix() != "" { + mods = append(mods, models.SelectWhere.Records.Key.Like(q.DatabaseKeyPrefix()+"%")) } - - // Check Meta. - m := getMeta(r) - if !m.CheckValidity() || - !m.CheckPermission(local, internal) { - continue recordsLoop + if !firstPage { + mods = append(mods, models.SelectWhere.Records.Key.GT(lastKey)) } - - // Check Data. - if q.HasWhereCondition() { - if r.Format.IsNull() || r.Value.IsNull() { - continue recordsLoop - } - - jsonData := string(r.Value.GetOrZero()) - jsonAccess := accessor.NewJSONAccessor(&jsonData) - if !q.MatchesAccessor(jsonAccess) { - continue recordsLoop - } + firstPage = false + page, err = models.Records.View.Query(mods...).All(db.ctx, db.bob) + if err != nil { + err = fmt.Errorf("failed to load records: %w", err) + break pagesLoop } - - // Build database record. - matched, _ := record.NewWrapperFromDatabase( - db.name, - r.Key, - m, - uint8(r.Format.GetOrZero()), //nolint:gosec // Values are within uint8. - r.Value.GetOrZero(), - ) - - select { - case <-queryIter.Done: - break recordsLoop - case queryIter.Next <- matched: - default: - select { - case <-queryIter.Done: - break recordsLoop - case queryIter.Next <- matched: - case <-time.After(1 * time.Second): - err = ErrQueryTimeout - break recordsLoop - } + if len(page) == 0 { + break pagesLoop } + lastKey = page[len(page)-1].Key + var done bool + done, err = db.feedQueryPage(queryIter, q, page, local, internal) + if done || err != nil || len(page) < queryPageSize { + break pagesLoop + } } queryIter.Finish(err) @@ -581,10 +540,90 @@ func (db *SQLite) MaintainThorough(ctx context.Context) error { func (db *SQLite) Shutdown() error { db.wg.Wait() db.cancelCtx() + // Wait for the batch handlers, which abort their batch when the context + // is canceled, before closing the database they use. + db.batchWg.Wait() return db.bob.Close() } +// shuttingDownErr returns the error for a batch that was aborted because the +// database is shutting down. +func (db *SQLite) shuttingDownErr() error { + return fmt.Errorf("%w: %w", errShuttingDown, db.ctx.Err()) +} + +// batchAbortedErr returns the error for a batch that was aborted by its +// caller. +func batchAbortedErr(abort context.Context) error { + return fmt.Errorf("%w: %w", storage.ErrBatchAborted, context.Cause(abort)) +} + +// rollbackBatch rolls back the transaction of an aborted batch. +func (db *SQLite) rollbackBatch(tx bob.Tx) { + // The transaction is already rolled back when the context was canceled. + err := tx.Rollback(db.ctx) + if err != nil && !errors.Is(err, sql.ErrTxDone) { + log.Warningf("database/sqlite: failed to roll back aborted batch of %s database: %s", db.name, err) + } +} + +// feedQueryPage sends the matching records of the given page to the query +// iterator. It returns whether the consumer is done or an error. +func (db *SQLite) feedQueryPage(queryIter *iterator.Iterator, q *query.Query, page models.RecordSlice, local, internal bool) (done bool, err error) { + for _, r := range page { + // Check if key matches. + if !q.MatchesKey(r.Key) { + continue + } + + // Check Meta. + m := getMeta(r) + if !m.CheckValidity() || + !m.CheckPermission(local, internal) { + continue + } + + // Check Data. + if q.HasWhereCondition() { + if r.Format.IsNull() || r.Value.IsNull() { + continue + } + + jsonData := string(r.Value.GetOrZero()) + jsonAccess := accessor.NewJSONAccessor(&jsonData) + if !q.MatchesAccessor(jsonAccess) { + continue + } + } + + // Build database record. + matched, _ := record.NewWrapperFromDatabase( + db.name, + r.Key, + m, + uint8(r.Format.GetOrZero()), //nolint:gosec // Values are within uint8. + r.Value.GetOrZero(), + ) + + select { + case <-queryIter.Done: + return true, nil + case queryIter.Next <- matched: + default: + select { + case <-queryIter.Done: + return true, nil + case queryIter.Next <- matched: + case <-time.After(1 * time.Second): + return true, ErrQueryTimeout + } + } + } + + return false, nil +} + type statementLogger struct{} func (sl statementLogger) Log(ctx context.Context, level sqldblogger.Level, msg string, data map[string]interface{}) { diff --git a/base/database/storage/sqlite/sqlite_test.go b/base/database/storage/sqlite/sqlite_test.go index f3ac24d13..30ba137fe 100644 --- a/base/database/storage/sqlite/sqlite_test.go +++ b/base/database/storage/sqlite/sqlite_test.go @@ -21,7 +21,7 @@ var ( _ storage.Purger = &SQLite{} ) -type TestRecord struct { //nolint:maligned +type TestRecord struct { record.Base sync.Mutex S string @@ -293,3 +293,66 @@ func testPutManyBatches(t *testing.T) { assert.Equal(t, i, got.I) } } + +// TestQueryConsumerUsesSameDB checks that a query consumer can read from and +// write to the same database while ranging over the query iterator, as the +// profile migrations do. A running query must not hold the (single) SQLite +// connection while it waits for the consumer. +func TestQueryConsumerUsesSameDB(t *testing.T) { + t.Parallel() + + db, err := openSQLite("test", t.TempDir(), false) + require.NoError(t, err) + defer func() { + require.NoError(t, db.Shutdown()) + }() + + // More records than fit into the iterator buffer and more than one query page. + const count = queryPageSize*2 + 50 + for i := range count { + r := &TestRecord{S: "orig", I: i} + r.SetKey("test:consumer/" + strconv.Itoa(i)) + r.UpdateMeta() + _, err := db.Put(r) + require.NoError(t, err) + } + + it, err := db.Query(query.New("test:consumer/").MustBeValid(), true, true) + require.NoError(t, err) + + var ( + start = time.Now() + seen = make(map[string]struct{}, count) + slowestOp time.Duration + nestedErrs int + ) + for r := range it.Next { + seen[r.DatabaseKey()] = struct{}{} + + opStart := time.Now() + _, err := db.Get(r.DatabaseKey()) + if err != nil { + nestedErrs++ + } + updated := &TestRecord{S: "updated"} + updated.SetKey(r.Key()) + updated.UpdateMeta() + _, err = db.Put(updated) + if err != nil { + nestedErrs++ + } + slowestOp = max(slowestOp, time.Since(opStart)) + } + require.NoError(t, it.Err()) + assert.Len(t, seen, count, "all records must be delivered") + assert.Zero(t, nestedErrs, "nested Get/Put must succeed") + assert.Less(t, slowestOp, 250*time.Millisecond, "nested Get/Put blocked by running query") + assert.Less(t, time.Since(start), 5*time.Second) + + // Writes from the consumer must have been applied. + r, err := db.Get("consumer/0") + require.NoError(t, err) + got := &TestRecord{} + require.NoError(t, record.Unwrap(r, got)) + assert.Equal(t, "updated", got.S) +} diff --git a/base/info/version.go b/base/info/version.go index be241e7e0..4572184db 100644 --- a/base/info/version.go +++ b/base/info/version.go @@ -50,7 +50,7 @@ func init() { } // Info holds the programs meta information. -type Info struct { //nolint:maligned +type Info struct { Name string Version string VersionNumber string diff --git a/base/log/output.go b/base/log/output.go index 9049f8033..7ea386b69 100644 --- a/base/log/output.go +++ b/base/log/output.go @@ -1,9 +1,11 @@ package log import ( + "errors" "fmt" "runtime/debug" "sync" + "sync/atomic" "time" "github.com/safing/portmaster/base/info" @@ -110,21 +112,26 @@ func writerManager() { for { err := writer() - if err != nil { - Errorf("log: writer failed: %s", err) - } else { + if err == nil { return } + // The error report was already written to GlobalWriter. Do not log + // via the log buffer here, as this goroutine is the only consumer of + // it and would deadlock if the buffer is full. + atomic.AddUint64(errLogLines, 1) } } -func writer() error { - var err error +// errWriterPanic is returned by writer when it recovered from a panic. +var errWriterPanic = errors.New("log writer panicked") + +func writer() (err error) { defer func() { // recover from panic panicVal := recover() if panicVal != nil { - _, err = fmt.Fprintf(GlobalWriter, "%s", panicVal) + // Always return an error, so that the writer is restarted. + err = fmt.Errorf("%w: %v", errWriterPanic, panicVal) // write stack to stderr fmt.Fprintf( @@ -157,7 +164,7 @@ StackTrace: case <-forceEmptyingOfBuffer: // log buffer is full! case <-shutdownSignal: // shutting down finalizeWriting() - return err + return nil } // wait for timeslot to log @@ -166,7 +173,7 @@ StackTrace: case <-forceEmptyingOfBuffer: // log buffer is full! case <-shutdownSignal: // shutting down finalizeWriting() - return err + return nil } // write all the logs! @@ -213,7 +220,7 @@ StackTrace: case <-time.After(10 * time.Millisecond): case <-shutdownSignal: finalizeWriting() - return err + return nil } } diff --git a/base/log/trace.go b/base/log/trace.go index 2226339cb..0601000f4 100644 --- a/base/log/trace.go +++ b/base/log/trace.go @@ -66,18 +66,26 @@ func (tracer *ContextTracer) Submit() { return } - if len(tracer.logs) == 0 { + // Detach the collected lines under the lock, so that concurrent or later + // log calls on this tracer cannot touch the lines handed to the writer and + // a repeated Submit does not emit them again. + tracer.Lock() + lines := tracer.logs + tracer.logs = nil + tracer.Unlock() + + if len(lines) == 0 { return } // extract last line as main line - mainLine := tracer.logs[len(tracer.logs)-1] - tracer.logs = tracer.logs[:len(tracer.logs)-1] + mainLine := lines[len(lines)-1] // create log object log := &logLine{ - msg: mainLine.msg, - tracer: tracer, + msg: mainLine.msg, + // Give the writer a private snapshot of the trace lines. + tracer: &ContextTracer{logs: lines[:len(lines)-1]}, level: mainLine.level, timestamp: mainLine.timestamp, file: mainLine.file, diff --git a/base/log/trace_test.go b/base/log/trace_test.go index 999e0f301..8161c3988 100644 --- a/base/log/trace_test.go +++ b/base/log/trace_test.go @@ -2,6 +2,7 @@ package log import ( "context" + "sync" "testing" "time" ) @@ -33,3 +34,47 @@ func TestContextTracer(t *testing.T) { tracer.Submit() time.Sleep(100 * time.Millisecond) } + +// TestContextTracerSubmitDetachesLines checks that Submit hands the collected +// lines over and leaves the tracer empty, so a second Submit does not emit +// the remaining lines again. +func TestContextTracerSubmitDetachesLines(t *testing.T) { + t.Parallel() + + tracer := &ContextTracer{} + tracer.Trace("first") + tracer.Trace("second") + tracer.Trace("third") + tracer.Submit() + + tracer.Lock() + remaining := len(tracer.logs) + tracer.Unlock() + if remaining != 0 { + t.Fatalf("expected tracer to be empty after Submit, still holds %d lines", remaining) + } +} + +// TestContextTracerConcurrentSubmit uses one tracer from multiple goroutines, +// tracing and submitting concurrently, while the log writer formats the +// submitted lines. Run with -race. +func TestContextTracerConcurrentSubmit(t *testing.T) { + t.Parallel() + + tracer := &ContextTracer{} + + var wg sync.WaitGroup + for range 4 { + wg.Go(func() { + for range 200 { + tracer.Trace("step") + tracer.Warning("something") + tracer.Submit() + } + }) + } + wg.Wait() + + // Give the writer time to process the submitted lines. + time.Sleep(50 * time.Millisecond) +} diff --git a/base/log/writer.go b/base/log/writer.go index 6c10716f7..221878ecf 100644 --- a/base/log/writer.go +++ b/base/log/writer.go @@ -15,6 +15,8 @@ type LogWriter struct { writeLock sync.Mutex isStdout bool file *os.File + // closed is set when the file is closed. Guarded by writeLock. + closed bool } // NewStdoutWriter creates a new log writer thet will write to the stdout. @@ -32,10 +34,14 @@ func NewFileWriter(dir string) (*LogWriter, error) { // Open new log file. logFile := time.Now().UTC().Format("2006-01-02_15-04-05") + ".log" - file, err := os.Create(filepath.Join(dir, logFile)) + // Create the file itself with strict permissions too: the directory may + // already exist with broader permissions (e.g. created by a package). + file, err := os.OpenFile(filepath.Join(dir, logFile), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return nil, err } + // The file may already exist (the name changes only every second). + _ = file.Chmod(0o600) return &LogWriter{ file: file, @@ -53,6 +59,10 @@ func (l *LogWriter) Write(buf []byte) (int, error) { if !l.isStdout { l.writeLock.Lock() defer l.writeLock.Unlock() + + if l.closed { + return 0, os.ErrClosed + } } return l.file.Write(buf) @@ -68,6 +78,10 @@ func (l *LogWriter) WriteMessage(msg Message, duplicates uint64) { if !l.isStdout { l.writeLock.Lock() defer l.writeLock.Unlock() + + if l.closed { + return + } } fmt.Fprintln(l.file, formatLine(msg.(*logLine), duplicates, l.isStdout)) @@ -79,10 +93,24 @@ func (l *LogWriter) IsStdout() bool { } // Close closes the writer. +// It takes the write lock, so that the file is never closed while it is +// written to: on Windows, closing a file during a concurrent write can block +// forever (Go 1.26, golang/go#77404), which would keep the process from +// exiting. Writes after Close are dropped. func (l *LogWriter) Close() { - if l != nil && !l.isStdout { - _ = l.file.Close() + if l == nil || l.isStdout { + return + } + + l.writeLock.Lock() + defer l.writeLock.Unlock() + + if l.closed { + return } + l.closed = true + _ = l.file.Sync() + _ = l.file.Close() } // CleanOldLogs deletes all log files in given directory that are older than the given threshold. diff --git a/base/log/writer_panic_test.go b/base/log/writer_panic_test.go new file mode 100644 index 000000000..4870924d3 --- /dev/null +++ b/base/log/writer_panic_test.go @@ -0,0 +1,44 @@ +package log + +import ( + "fmt" + "strings" + "testing" + "time" +) + +// TestWriterSurvivesPanic checks that the log writer keeps processing log +// lines after a panic occurred while writing a line. +func TestWriterSurvivesPanic(t *testing.T) { + t.Parallel() + + // Submit a trace whose remaining trace lines contain a nil entry. Formatting + // this line panics inside the writer goroutine. + poisoned := &ContextTracer{ + logs: []*logLine{ + nil, + { + msg: "poisoned trace", + level: InfoLevel, + timestamp: time.Now(), + }, + }, + } + poisoned.Submit() + + // Keep logging a warning until the writer processed one of them. Lines + // that are processed together with the poisoned line are lost, so a single + // warning is not enough. + marker := fmt.Sprintf("writer-survives-panic-%d", time.Now().UnixNano()) + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + Warning(marker) + time.Sleep(10 * time.Millisecond) + for _, line := range GetLastUnexpectedLogs() { + if strings.Contains(line, marker) { + return + } + } + } + t.Fatal("log writer stopped processing log lines after a panic") +} diff --git a/base/log/writer_perm_test.go b/base/log/writer_perm_test.go new file mode 100644 index 000000000..ab1669349 --- /dev/null +++ b/base/log/writer_perm_test.go @@ -0,0 +1,32 @@ +//go:build !windows + +package log + +import ( + "os" + "testing" +) + +func TestNewFileWriterPermissions(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + // The directory exists with broad permissions, e.g. created by a package. + err := os.Chmod(dir, 0o755) //nolint:gosec // test setup + if err != nil { + t.Fatal(err) + } + w, err := NewFileWriter(dir) + if err != nil { + t.Fatal(err) + } + defer w.Close() + + info, err := w.file.Stat() + if err != nil { + t.Fatal(err) + } + if perm := info.Mode().Perm(); perm != 0o600 { + t.Errorf("log file permissions are %o, want 600", perm) + } +} diff --git a/base/log/writer_test.go b/base/log/writer_test.go new file mode 100644 index 000000000..e14d81ebe --- /dev/null +++ b/base/log/writer_test.go @@ -0,0 +1,62 @@ +package log + +import ( + "errors" + "os" + "sync" + "testing" + "time" +) + +// TestLogWriterCloseWhileWriting checks that closing the log file does not run +// concurrently with writes, which can block forever on Windows, and that +// writes after closing are dropped. +func TestLogWriterCloseWhileWriting(t *testing.T) { + t.Parallel() + + for range 50 { + w, err := NewFileWriter(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + var wg sync.WaitGroup + stop := make(chan struct{}) + for range 4 { + wg.Go(func() { + for { + select { + case <-stop: + return + default: + } + // Like slog, which writes to the file directly from any + // goroutine. WriteMessage is only used by the log writer + // goroutine. + _, _ = w.Write([]byte("concurrent log line\n")) + } + }) + } + + time.Sleep(time.Millisecond) + closed := make(chan struct{}) + go func() { + w.Close() + close(closed) + }() + select { + case <-closed: + case <-time.After(10 * time.Second): + t.Fatal("closing the log writer blocked while writing") + } + close(stop) + wg.Wait() + + _, err = w.Write([]byte("after close\n")) + if !errors.Is(err, os.ErrClosed) { + t.Errorf("write after close: got %v, want %v", err, os.ErrClosed) + } + w.WriteMessage(&logLine{msg: "after close", level: InfoLevel, timestamp: time.Now()}, 0) + w.Close() // Closing twice is fine. + } +} diff --git a/base/metrics/api.go b/base/metrics/api.go index ccc3bfe90..7e832217c 100644 --- a/base/metrics/api.go +++ b/base/metrics/api.go @@ -3,6 +3,7 @@ package metrics import ( "bytes" "context" + "errors" "fmt" "io" "net/http" @@ -97,6 +98,16 @@ func WriteMetrics(w io.Writer, permission api.Permission, expertiseLevel config. } } +// maxPushErrorBodySize is the maximum amount of bytes read from an error +// response when pushing metrics. +const maxPushErrorBodySize = 4096 + +// pushTimeout bounds a single metrics push request. +// It is a variable so that tests can shorten it. +var pushTimeout = 30 * time.Second + +var errPushTimeout = errors.New("push timed out") + func writeMetricsTo(ctx context.Context, url string) error { // First, collect metrics into buffer. buf := &bytes.Buffer{} @@ -109,7 +120,9 @@ func writeMetricsTo(ctx context.Context, url string) error { } // Create request - req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf) + reqCtx, cancel := context.WithTimeout(ctx, pushTimeout) + defer cancel() + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, url, buf) if err != nil { return fmt.Errorf("failed to create request: %w", err) } @@ -117,6 +130,13 @@ func writeMetricsTo(ctx context.Context, url string) error { // Send. resp, err := http.DefaultClient.Do(req) if err != nil { + // A per-request timeout must not look like a deadline/cancel of the + // worker itself, as the worker manager would treat that as a clean + // stop and never restart the pusher. Only pass through errors that + // stem from the worker context ending. + if ctx.Err() == nil && errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("%w after %s while writing metrics to %s", errPushTimeout, pushTimeout, url) + } return err } defer func() { @@ -129,7 +149,8 @@ func writeMetricsTo(ctx context.Context, url string) error { } // Get and return error. - body, _ := io.ReadAll(resp.Body) + // Limit the read, as the body is only used for the error message. + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxPushErrorBodySize)) return fmt.Errorf( "got %s while writing metrics to %s: %s", resp.Status, diff --git a/base/metrics/api_test.go b/base/metrics/api_test.go new file mode 100644 index 000000000..c05cd058b --- /dev/null +++ b/base/metrics/api_test.go @@ -0,0 +1,123 @@ +package metrics + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + vm "github.com/VictoriaMetrics/metrics" +) + +func TestWriteMetricsToErrorWithEndlessBody(t *testing.T) { //nolint:paralleltest // Modifies package globals. + registerPushTestMetric(t) + + // Server that responds with an error and a body that never ends. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + chunk := []byte(strings.Repeat("x", 4096)) + for r.Context().Err() == nil { + _, err := w.Write(chunk) + if err != nil { + return + } + } + })) + t.Cleanup(srv.Close) + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + errs := make(chan error, 1) + go func() { + errs <- writeMetricsTo(ctx, srv.URL) + }() + + select { + case err := <-errs: + if err == nil { + t.Fatal("expected an error") + } + if !strings.Contains(err.Error(), "500") { + t.Fatalf("unexpected error: %.200s", err) + } + case <-time.After(5 * time.Second): + cancel() + t.Fatal("writeMetricsTo did not return: error response body is read without limit") + } +} + +// registerPushTestMetric replaces the registry with a single test metric, so +// that there is something to push. +func registerPushTestMetric(t *testing.T) { + t.Helper() + + set := vm.NewSet() + set.NewCounter("push_test_total").Inc() + registryLock.Lock() + prevRegistry := registry + registry = []Metric{&metricBase{ + Identifier: "push_test_total", + LabeledIdentifier: "push_test_total", + Options: &Options{}, + set: set, + }} + registryLock.Unlock() + t.Cleanup(func() { + registryLock.Lock() + registry = prevRegistry + registryLock.Unlock() + }) +} + +func TestWriteMetricsToTimeout(t *testing.T) { //nolint:paralleltest // Modifies package globals. + registerPushTestMetric(t) + + prevTimeout := pushTimeout + pushTimeout = 200 * time.Millisecond + t.Cleanup(func() { pushTimeout = prevTimeout }) + + // Server that accepts the request, but never answers. + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + select { + case <-release: + case <-r.Context().Done(): + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) // Runs before srv.Close. + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + errs := make(chan error, 1) + go func() { + errs <- writeMetricsTo(ctx, srv.URL) + }() + + select { + case err := <-errs: + if err == nil { + t.Fatal("expected an error") + } + // The worker manager treats these as a clean stop and would not + // restart the pusher. + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + t.Fatalf("timeout error must not wrap context errors, got: %v", err) + } + case <-time.After(5 * time.Second): + cancel() + t.Fatal("writeMetricsTo did not return: push request has no timeout") + } + + // Cancellation of the worker context must still be passed through. + cancel() + err := writeMetricsTo(ctx, srv.URL) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got: %v", err) + } +} diff --git a/base/metrics/metrics_runtime.go b/base/metrics/metrics_runtime.go index 88bff9d53..7906509a8 100644 --- a/base/metrics/metrics_runtime.go +++ b/base/metrics/metrics_runtime.go @@ -88,6 +88,8 @@ func (r *runtimeMetrics) WritePrometheus(w io.Writer) { fmt.Fprint(w, "}") } fmt.Fprintln(w, line[insertAt:]) + } else { + _, _ = fmt.Fprintln(w, line) } } diff --git a/base/metrics/metrics_runtime_test.go b/base/metrics/metrics_runtime_test.go new file mode 100644 index 000000000..f74c84f32 --- /dev/null +++ b/base/metrics/metrics_runtime_test.go @@ -0,0 +1,32 @@ +package metrics + +import ( + "bytes" + "strings" + "testing" +) + +func TestRuntimeMetricsWithNamespaceOnly(t *testing.T) { //nolint:paralleltest // Modifies package globals. + registryLock.Lock() + prevNamespace, prevLabels := metricNamespace, globalLabels + metricNamespace = "testns" + globalLabels = make(map[string]string) + registryLock.Unlock() + t.Cleanup(func() { + registryLock.Lock() + metricNamespace, globalLabels = prevNamespace, prevLabels + registryLock.Unlock() + }) + + buf := &bytes.Buffer{} + (&runtimeMetrics{}).WritePrometheus(buf) + + if buf.Len() == 0 { + t.Fatal("no runtime metrics written when only a namespace is set") + } + for line := range strings.Lines(buf.String()) { + if !strings.HasPrefix(line, "testns_") { + t.Fatalf("runtime metric line without namespace: %q", line) + } + } +} diff --git a/base/notifications/database.go b/base/notifications/database.go index 6cbbd86bf..9dd9884e5 100644 --- a/base/notifications/database.go +++ b/base/notifications/database.go @@ -143,9 +143,17 @@ func (s *StorageInterface) Put(r record.Record) (record.Record, error) { func applyUpdate(n *Notification, key string) (*Notification, error) { // separate goroutine in order to correctly lock notsLock existing, ok := getNotification(key) + if ok { + existing.Lock() + // Check under lock, as the notification may be deleted concurrently. + if existing.Meta().IsDeleted() { + existing.Unlock() + ok = false + } + } // ignore if already deleted - if !ok || existing.Meta().IsDeleted() { + if !ok { // this is a completely new notification // we pass pushUpdate==false because the storage // controller will push an update on put anyway. @@ -161,7 +169,7 @@ func applyUpdate(n *Notification, key string) (*Notification, error) { } }() - existing.Lock() + // existing is locked above. defer existing.Unlock() if existing.State == Executed { diff --git a/base/notifications/delete_test.go b/base/notifications/delete_test.go new file mode 100644 index 000000000..9d8e09ee1 --- /dev/null +++ b/base/notifications/delete_test.go @@ -0,0 +1,30 @@ +package notifications + +import "testing" + +// TestDeleteOldCopyKeepsReplacement checks that deleting an old notification +// object does not remove a newer notification with the same EventID from the +// notification storage. +// +//nolint:paralleltest // Uses the global notification storage. +func TestDeleteOldCopyKeepsReplacement(t *testing.T) { + setupTestModule(t) + + const id = "test:replaced-by-newer" + oldN := Notify(&Notification{EventID: id, Title: "Old", Message: "Old"}) + newN := Notify(&Notification{EventID: id, Title: "New", Message: "New"}) + defer Delete(id) + + if Get(id) != newN { + t.Fatal("newer notification was not stored") + } + + oldN.Delete() + + if got := Get(id); got != newN { + t.Fatalf("newer notification unreachable after deleting old copy: got %v", got) + } + if newN.Meta().IsDeleted() { + t.Fatal("newer notification must not be marked deleted") + } +} diff --git a/base/notifications/delete_unsaved_test.go b/base/notifications/delete_unsaved_test.go new file mode 100644 index 000000000..3af6b9317 --- /dev/null +++ b/base/notifications/delete_unsaved_test.go @@ -0,0 +1,25 @@ +package notifications + +import "testing" + +// TestDeleteNeverSaved checks that deleting a notification that was never +// saved does not panic. +// +//nolint:paralleltest // Uses the global notification storage. +func TestDeleteNeverSaved(t *testing.T) { + setupTestModule(t) + + n := &Notification{EventID: "test:never-saved", Title: "T", Message: "M"} + expired := n.Expired() + n.Delete() + n.Delete() // Must also be safe to repeat. + + select { + case <-expired: + default: + t.Error("expired channel was not closed") + } + if Get("test:never-saved") != nil { + t.Error("never-saved notification must not be in storage") + } +} diff --git a/base/notifications/notification.go b/base/notifications/notification.go index 9bc4787b3..8d508e28b 100644 --- a/base/notifications/notification.go +++ b/base/notifications/notification.go @@ -47,7 +47,7 @@ const ( ) // Notification represents a notification that is to be delivered to the user. -type Notification struct { //nolint:maligned +type Notification struct { record.Base // EventID is used to identify a specific notification. It consists of // the module name and a per-module unique event id. @@ -291,18 +291,6 @@ func (n *Notification) Save() { // save saves the notification to the internal storage. It locks the // notification, so it must not be locked when save is called. func (n *Notification) save(pushUpdate bool) { - var id string - - // Save notification after pre-save processing. - defer func() { - if id != "" { - // Lock and save to notification storage. - notsLock.Lock() - defer notsLock.Unlock() - nots[id] = n - } - }() - // We do not access EventData here, so it is enough to just lock the // notification itself. n.lock.Lock() @@ -314,6 +302,12 @@ func (n *Notification) save(pushUpdate bool) { return } + // Never resurrect a deleted notification, eg. when a pending save of a + // user response races with a deletion by the cleaner or an action function. + if meta := n.Meta(); meta != nil && meta.IsDeleted() { + return + } + // Derive EventID from Message if not given. if n.EventID == "" { n.EventID = fmt.Sprintf( @@ -322,9 +316,6 @@ func (n *Notification) save(pushUpdate bool) { ) } - // Save ID for deletion - id = n.EventID - // Generate random GUID if not set. if n.GUID == "" { n.GUID = utils.RandomUUID(n.EventID).String() @@ -349,6 +340,14 @@ func (n *Notification) save(pushUpdate bool) { // Update meta data. n.UpdateMeta() + // Save to notification storage while still holding the notification lock, + // so that a concurrent delete cannot be undone. + func() { + notsLock.Lock() + defer notsLock.Unlock() + nots[n.EventID] = n + }() + // Push update via the database system if needed. if pushUpdate { log.Tracef("notifications: pushing update for %s to subscribers", n.Key()) @@ -424,32 +423,44 @@ func (n *Notification) Delete() { // delete deletes the notification from the internal storage. It locks the // notification, so it must not be locked when delete is called. func (n *Notification) delete(pushUpdate bool) { - var id string - - // Delete notification after processing deletion. - defer func() { - // Lock and delete from notification storage. - notsLock.Lock() - defer notsLock.Unlock() - delete(nots, id) - }() - // We do not access EventData here, so it is enough to just lock the // notification itself. n.lock.Lock() defer n.lock.Unlock() + // A notification that was never saved has no meta data and is not in the + // notification storage: only release waiters and the connected state. + if n.Meta() == nil { + if n.expiredTrigger != nil { + close(n.expiredTrigger) + n.expiredTrigger = nil + } + if n.belongsTo != nil { + n.belongsTo.Remove(n.EventID) + } + return + } + // Check if notification is already deleted. if n.Meta().IsDeleted() { return } - // Save ID for deletion - id = n.EventID - // Mark notification as deleted. n.Meta().Delete() + // Delete from notification storage while still holding the notification + // lock, so that it is consistent with the deleted flag checked by save. + func() { + notsLock.Lock() + defer notsLock.Unlock() + // Only remove the entry if it is this very notification, as it might + // have been replaced by a newer one with the same EventID. + if nots[n.EventID] == n { + delete(nots, n.EventID) + } + }() + // Close expiry channel if available. if n.expiredTrigger != nil { close(n.expiredTrigger) diff --git a/base/notifications/notification_test.go b/base/notifications/notification_test.go new file mode 100644 index 000000000..ddeeddee6 --- /dev/null +++ b/base/notifications/notification_test.go @@ -0,0 +1,63 @@ +package notifications + +import ( + "fmt" + "sync" + "testing" +) + +var testModuleOnce sync.Once + +func setupTestModule(t *testing.T) { + t.Helper() + + testModuleOnce.Do(func() { + _, err := New(struct{}{}) + if err != nil { + t.Fatalf("failed to create notifications module: %s", err) + } + }) +} + +// TestApplyUpdateConcurrentDelete checks that a user response that is applied +// while the notification is deleted (e.g. by the expiry cleaner) does not +// access the notification without holding its lock and does not re-add the +// deleted notification to the notification storage. +// +//nolint:paralleltest // Uses the global notification storage. +func TestApplyUpdateConcurrentDelete(t *testing.T) { + setupTestModule(t) + + var zombies int + defer func() { + if zombies > 0 { + t.Errorf("%d deleted notifications were re-added to the notification storage", zombies) + } + }() + + for i := range 1000 { + id := fmt.Sprintf("test:concurrent-delete-%d", i) + n := Notify(&Notification{ + EventID: id, + Title: "Test", + Message: "Test", + }) + + var wg sync.WaitGroup + wg.Go(func() { + _, _ = applyUpdate(&Notification{EventID: id, SelectedActionID: "ack"}, id) + }) + wg.Go(func() { + n.delete(true) + }) + wg.Wait() + + // The deletion must be final, regardless of the order. + if zombie := Get(id); zombie != nil { + zombies++ + } + + // Clean up. + Delete(id) + } +} diff --git a/base/rng/rng_test.go b/base/rng/rng_test.go index 20cb6aaa5..45c5a025c 100644 --- a/base/rng/rng_test.go +++ b/base/rng/rng_test.go @@ -17,11 +17,11 @@ func init() { } } -func TestRNG(t *testing.T) { - t.Parallel() - +func TestRNG(t *testing.T) { //nolint:paralleltest // Modifies the global rngCipher. key := make([]byte, 16) + // Hold the rng lock, as the generator reads rngCipher when reseeding. + rngLock.Lock() rngCipher = "aes" _, err := newCipher(key) if err != nil { @@ -33,6 +33,8 @@ func TestRNG(t *testing.T) { if err != nil { t.Errorf("failed to create serpent cipher: %s", err) } + rngCipher = "aes" + rngLock.Unlock() b := make([]byte, 32) _, err = Read(b) diff --git a/base/runtime/registry.go b/base/runtime/registry.go index 373f3ffc7..324d17c70 100644 --- a/base/runtime/registry.go +++ b/base/runtime/registry.go @@ -73,6 +73,16 @@ func (r *Registry) DatabaseName() string { return r.dbName } +// HasSubscribers returns whether a record pushed with the given key (without +// the database name) could be received by a database subscriber. Records +// that are expensive to create do not need to be pushed otherwise. +func (r *Registry) HasSubscribers(key string) bool { + r.l.RLock() + defer r.l.RUnlock() + + return r.dbController.HasSubscribers(key) +} + // InjectAsDatabase injects the registry as the storage // database for name. func (r *Registry) InjectAsDatabase(name string) error { @@ -285,9 +295,11 @@ func (r *Registry) collectProviderByPrefix(prefix string) []*keyedValueProvider r.l.RLock() defer r.l.RUnlock() - // if there's a LongestPrefix provider that's the only one - // we need to ask - if _, p, ok := r.providers.LongestPrefix(prefix); ok { + // if there's a LongestPrefix provider that is registered for a + // prefix (not a single key) it covers the whole query and is the + // only one we need to ask. Providers for single keys only match + // that exact key and must not hide providers below the query prefix. + if key, p, ok := r.providers.LongestPrefix(prefix); ok && isPrefixKey(key) { return []*keyedValueProvider{p.(*keyedValueProvider)} //nolint:forcetypeassert } diff --git a/base/runtime/registry_test.go b/base/runtime/registry_test.go index 54084e23a..fe4ba627c 100644 --- a/base/runtime/registry_test.go +++ b/base/runtime/registry_test.go @@ -155,3 +155,33 @@ func TestRegistryRegister(t *testing.T) { } } } + +func TestRegistryCollectProviderByPrefix(t *testing.T) { + t.Parallel() + + const nested = "foo/bar/" + + reg := NewRegistry() + for _, k := range []string{"foo", nested, "foobar", "a/b/"} { + _, err := reg.Register(k, &testProvider{k: k}) + require.NoError(t, err, k) + } + + keys := func(prefix string) []string { + ps := reg.collectProviderByPrefix(prefix) + res := make([]string, 0, len(ps)) + for _, p := range ps { + res = append(res, p.key) + } + return res + } + + // An exact-key provider must not hide the providers below the prefix. + assert.ElementsMatch(t, []string{"foo", nested, "foobar"}, keys("foo")) + assert.ElementsMatch(t, []string{nested}, keys("foo/")) + // A prefix provider that contains the query prefix is the only one asked. + assert.Equal(t, []string{nested}, keys("foo/bar/baz")) + assert.Equal(t, []string{"a/b/"}, keys("a/b/c")) + // Nothing manages this. + assert.Empty(t, keys("fo0")) +} diff --git a/base/utils/call_limiter.go b/base/utils/call_limiter.go index eb669a2f5..1439c2d5b 100644 --- a/base/utils/call_limiter.go +++ b/base/utils/call_limiter.go @@ -67,7 +67,9 @@ func (l *CallLimiter) lead(f func()) { // Transition from out lock to in lock when done. defer func() { // Update last execution time. - l.lastExec = time.Now().UTC() + // Keep the monotonic clock reading: a wall-clock jump must not + // change how long the next call waits. + l.lastExec = time.Now() // Stop newcomers from waiting on previous execution. l.inLock.Lock() // Allow waiters to leave. @@ -75,13 +77,34 @@ func (l *CallLimiter) lead(f func()) { }() // Wait for the minimum duration between executions. - if l.pause > 0 { - sinceLastExec := time.Since(l.lastExec) - if sinceLastExec < l.pause { - time.Sleep(l.pause - sinceLastExec) - } + if wait := l.waitTime(); wait > 0 { + time.Sleep(wait) } // Execute. f() } + +// waitTime returns how long to wait before the next execution. +// It never exceeds the minimum pause, even if lastExec lies in the future. +func (l *CallLimiter) waitTime() time.Duration { + return limiterWait(l.pause, l.lastExec) +} + +// limiterWait returns how long to wait so that at least pause passes since +// lastExec. The result is capped at pause, so a lastExec in the future (after +// the system clock was set back) costs at most one pause instead of the jump. +func limiterWait(pause time.Duration, lastExec time.Time) time.Duration { + if pause <= 0 { + return 0 + } + since := time.Since(lastExec) + switch { + case since < 0: + return pause + case since < pause: + return pause - since + default: + return 0 + } +} diff --git a/base/utils/call_limiter2.go b/base/utils/call_limiter2.go index 30d1b1ef6..cd2d2693e 100644 --- a/base/utils/call_limiter2.go +++ b/base/utils/call_limiter2.go @@ -54,7 +54,9 @@ func (l *CallLimiter2) Do(f func()) { func (l *CallLimiter2) waitAndExec(f func()) { defer func() { // Update last exec time. - l.lastExec = time.Now().UTC() + // Keep the monotonic clock reading: a wall-clock jump must not + // change how long the next call waits. + l.lastExec = time.Now() // Enable next execution first. l.executing.Store(false) // Move to next slot aftewards to prevent wait loops. @@ -62,13 +64,16 @@ func (l *CallLimiter2) waitAndExec(f func()) { }() // Wait for the minimum duration between executions. - if l.pause > 0 { - sinceLastExec := time.Since(l.lastExec) - if sinceLastExec < l.pause { - time.Sleep(l.pause - sinceLastExec) - } + if wait := l.waitTime(); wait > 0 { + time.Sleep(wait) } // Execute. f() } + +// waitTime returns how long to wait before the next execution. +// It never exceeds the minimum pause, even if lastExec lies in the future. +func (l *CallLimiter2) waitTime() time.Duration { + return limiterWait(l.pause, l.lastExec) +} diff --git a/base/utils/call_limiter_clock_test.go b/base/utils/call_limiter_clock_test.go new file mode 100644 index 000000000..b775c0b96 --- /dev/null +++ b/base/utils/call_limiter_clock_test.go @@ -0,0 +1,55 @@ +package utils + +import ( + "testing" + "time" +) + +func TestLimiterWait(t *testing.T) { + t.Parallel() + + pause := 100 * time.Millisecond + tests := []struct { + name string + pause time.Duration + lastExec time.Time + min, max time.Duration + }{ + {"no pause", 0, time.Now(), 0, 0}, + {"never executed", pause, time.Time{}, 0, 0}, + {"long ago", pause, time.Now().Add(-time.Hour), 0, 0}, + {"just executed", pause, time.Now(), pause - 20*time.Millisecond, pause}, + // Wall-clock time in the future, as after the system clock was set back. + {"clock set back by days", pause, time.Now().Round(0).Add(96 * time.Hour), pause, pause}, + } + for _, tc := range tests { + got := limiterWait(tc.pause, tc.lastExec) + if got < tc.min || got > tc.max { + t.Errorf("%s: wait %v, want between %v and %v", tc.name, got, tc.min, tc.max) + } + } +} + +// TestCallLimiterClockSetBack checks that a lastExec in the future (clock set +// back, no monotonic reading) delays the next call by at most one pause. +func TestCallLimiterClockSetBack(t *testing.T) { + t.Parallel() + + pause := 20 * time.Millisecond + future := time.Now().Round(0).Add(48 * time.Hour) + + l1 := NewCallLimiter(pause) + l1.lastExec = future + l2 := NewCallLimiter2(pause) + l2.lastExec = future + + for name, do := range map[string]func(func()){"CallLimiter": l1.Do, "CallLimiter2": l2.Do} { + done := make(chan struct{}) + go do(func() { close(done) }) + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatalf("%s: call blocked after the clock was set back", name) + } + } +} diff --git a/base/utils/call_limiter_test.go b/base/utils/call_limiter_test.go index 2343673aa..6dbf9d082 100644 --- a/base/utils/call_limiter_test.go +++ b/base/utils/call_limiter_test.go @@ -16,6 +16,7 @@ func TestCallLimiter(t *testing.T) { oa := NewCallLimiter2(pause) executed := abool.New() var testWg sync.WaitGroup + var inFlight atomic.Int32 // One execution should gobble up the whole batch. // We are doing this without sleep in function, so dummy exec first to trigger first pause. @@ -26,9 +27,14 @@ func TestCallLimiter(t *testing.T) { for range 100 { go func() { oa.Do(func() { - if !executed.SetToIf(false, true) { + // Check for actual concurrent execution. Multiple sequential + // executions per batch are allowed, as goroutines might not + // all be started in time (eg. with the race detector). + if inFlight.Add(1) != 1 { t.Errorf("concurrent execution!") } + executed.Set() + inFlight.Add(-1) }) testWg.Done() }() diff --git a/base/utils/onceagain_test.go b/base/utils/onceagain_test.go index 15bd6d4f3..794d2dc95 100644 --- a/base/utils/onceagain_test.go +++ b/base/utils/onceagain_test.go @@ -15,6 +15,7 @@ func TestOnceAgain(t *testing.T) { oa := OnceAgain{} executed := abool.New() var testWg sync.WaitGroup + var inFlight atomic.Int32 // One execution should gobble up the whole batch. for range 10 { @@ -22,15 +23,23 @@ func TestOnceAgain(t *testing.T) { for range 100 { go func() { oa.Do(func() { - if !executed.SetToIf(false, true) { + // Check for actual concurrent execution. Multiple sequential + // executions per batch are allowed, as goroutines might not + // all be started in time (eg. with the race detector). + if inFlight.Add(1) != 1 { t.Errorf("concurrent execution!") } + executed.Set() time.Sleep(10 * time.Millisecond) + inFlight.Add(-1) }) testWg.Done() }() } testWg.Wait() + if executed.IsNotSet() { + t.Errorf("no execution!") + } executed.UnSet() // reset check } @@ -38,6 +47,7 @@ func TestOnceAgain(t *testing.T) { // Choose values so that about 10 executions are expected var execs uint32 testWg.Add(100) + started := time.Now() for range 100 { go func() { oa.Do(func() { @@ -50,11 +60,18 @@ func TestOnceAgain(t *testing.T) { time.Sleep(1 * time.Millisecond) } + spawned := time.Since(started) testWg.Wait() - if execs <= 8 { + // Executions take at least 10ms and do not overlap, so at most one + // execution fits into every 10ms of spawning, plus one running and one + // queued at the end. Sleeps may take longer than requested (eg. on + // Windows or on loaded machines), so derive the bound from the time + // spawning actually took. + maxExecs := uint32(spawned/(10*time.Millisecond)) + 2 //nolint:gosec // Spawning takes seconds at most. + if execs <= 5 { t.Errorf("unexpected low exec count: %d", execs) } - if execs >= 12 { - t.Errorf("unexpected high exec count: %d", execs) + if execs > maxExecs { + t.Errorf("unexpected high exec count: %d (max %d for %s of spawning)", execs, maxExecs, spawned) } } diff --git a/base/utils/renameio/writefile.go b/base/utils/renameio/writefile.go index 073a1e1b0..901ed9e4d 100644 --- a/base/utils/renameio/writefile.go +++ b/base/utils/renameio/writefile.go @@ -20,7 +20,9 @@ func WriteFile(filename string, data []byte, perm os.FileMode) error { // Set permissions before writing data, in case the data is sensitive. if runtime.GOOS == "windows" { - err = acl.Chmod(t.path, perm) + // The ACL must be set on the temporary file, not on the destination, + // which may not exist yet. + err = acl.Chmod(t.Name(), perm) } else { err = t.Chmod(perm) } diff --git a/base/utils/renameio/writefile_test.go b/base/utils/renameio/writefile_test.go index eaf302b56..5775ea63f 100644 --- a/base/utils/renameio/writefile_test.go +++ b/base/utils/renameio/writefile_test.go @@ -6,6 +6,7 @@ import ( "bytes" "os" "path/filepath" + "runtime" "testing" ) @@ -40,7 +41,9 @@ func TestWriteFile(t *testing.T) { if err != nil { t.Fatal(err) } - if gotPerm := fi.Mode() & os.ModePerm; gotPerm != wantPerm { + // On Windows, the permissions are set as an ACL, which the mode bits do + // not reflect. + if gotPerm := fi.Mode() & os.ModePerm; runtime.GOOS != "windows" && gotPerm != wantPerm { t.Errorf("got permissions 0%o, want permissions 0%o", gotPerm, wantPerm) } } diff --git a/cmds/portmaster-core/main.go b/cmds/portmaster-core/main.go index ee8501e92..a494b7cb8 100644 --- a/cmds/portmaster-core/main.go +++ b/cmds/portmaster-core/main.go @@ -16,7 +16,6 @@ import ( "github.com/safing/portmaster/service/configure" "github.com/safing/portmaster/service/firewall/interception" "github.com/safing/portmaster/service/updates" - "github.com/safing/portmaster/spn/conf" ) var ( @@ -86,10 +85,6 @@ func initializeGlobals(cmd *cobra.Command, args []string) { // Configure user agent. updates.UserAgent = fmt.Sprintf("Portmaster Core (%s %s)", runtime.GOOS, runtime.GOARCH) - // Enable SPN client mode - conf.EnableClient(true) - conf.EnableIntegration(true) - // Configure service. cmdbase.SvcFactory = func(svcCfg *service.ServiceConfig) (cmdbase.ServiceInstance, error) { svc, err := service.New(svcCfg) diff --git a/cmds/testsuite/login.go b/cmds/testsuite/login.go index bf1e5ef3b..405023d13 100644 --- a/cmds/testsuite/login.go +++ b/cmds/testsuite/login.go @@ -1,125 +1,7 @@ -package main - -import ( - "errors" - "fmt" - "log" - - "github.com/spf13/cobra" - - "github.com/safing/portmaster/spn/access" - "github.com/safing/portmaster/spn/access/account" -) - -var ( - loginCmd = &cobra.Command{ - Use: "login", - Short: "Test login and token issuing", - RunE: runTestCommand(testLogin), - } - - loginUsername string - loginPassword string - loginDeviceID string -) - -func init() { - rootCmd.AddCommand(loginCmd) - - // Add flags for login options. - flags := loginCmd.Flags() - flags.StringVar(&loginUsername, "username", "", "set username to use for the login test") - flags.StringVar(&loginPassword, "password", "", "set password to use for the login test") - flags.StringVar(&loginDeviceID, "device-id", "", "set device ID to use for the login test") - - // Mark all as required. - _ = loginCmd.MarkFlagRequired("username") - _ = loginCmd.MarkFlagRequired("password") - _ = loginCmd.MarkFlagRequired("device-id") -} - -func testLogin(cmd *cobra.Command, args []string) (err error) { - // Init token zones. - err = access.InitializeZones() - if err != nil { - return fmt.Errorf("failed to initialize token zones: %w", err) - } +//go:build ignore - // Set initial user object in order to set the device ID that should be used for login. - initialUser := &access.UserRecord{ - User: &account.User{ - Username: loginUsername, - Device: &account.Device{ - ID: loginDeviceID, - }, - }, - } - err = initialUser.Save() - if err != nil { - return fmt.Errorf("failed to save initial user with device ID: %w", err) - } - - // Login. - _, _, err = access.Login(loginUsername, loginPassword) - if err != nil { - return fmt.Errorf("login failed: %w", err) - } - - // Check user. - user, err := access.GetUser() - if err != nil { - return fmt.Errorf("failed to get user after login: %w", err) - } - if verbose { - log.Printf("user (from login): %+v", user.User) - log.Printf("device (from login): %+v", user.User.Device) - } - - // Check if the device ID is unchanged. - if user.Device.ID != loginDeviceID { - return errors.New("device ID changed") - } - - // Check Auth Token. - authToken, err := access.GetAuthToken() - if err != nil { - return fmt.Errorf("failed to get auth token after login: %w", err) - } - if verbose { - log.Printf("auth token (from login): %+v", authToken.Token) - } - firstAuthToken := authToken.Token.Token - - // Update User. - _, _, err = access.UpdateUser() - if err != nil { - return fmt.Errorf("failed to update user: %w", err) - } - - // Check if we received a new Auth Token. - authToken, err = access.GetAuthToken() - if err != nil { - return fmt.Errorf("failed to get auth token after user update: %w", err) - } - if verbose { - log.Printf("auth token (from update): %+v", authToken.Token) - } - if authToken.Token.Token == firstAuthToken { - return errors.New("auth token did not change after update") - } - - // Get Tokens. - err = access.UpdateTokens() - if err != nil { - return fmt.Errorf("failed to update tokens: %w", err) - } - regular, fallback := access.GetTokenAmount(access.ExpandAndConnectZones) - if verbose { - log.Printf("received tokens: %d regular, %d fallback", regular, fallback) - } - if regular == 0 || fallback == 0 { - return fmt.Errorf("not enough tokens after fetching: %d regular, %d fallback", regular, fallback) - } - - return nil -} +// The previous contents exercised the external Safing account-login API. +// Account authentication, token persistence, and related network calls have +// been removed from portmasterpro. Keeping this source excluded prevents the +// obsolete login test command from being compiled as part of `go build ./...`. +package main diff --git a/desktop/CHANGES.md b/desktop/CHANGES.md new file mode 100644 index 000000000..06f999e37 --- /dev/null +++ b/desktop/CHANGES.md @@ -0,0 +1,50 @@ +# Desktop UI changes in portmasterpro + +The production UI is the Angular app in `desktop/angular` (Angular 16, npm, +Karma). All account, subscription and SPN gating is handled centrally in the +`@safing/portmaster-api` library so that the ~90 components which read the +user profile did not have to be touched individually. + +## Central change: `projects/safing/portmaster-api/src/lib/spn.service.ts` + +| Member | Before | Now | +|---|---|---| +| `profile$` / `watchProfile()` / `userProfile()` | watched `core:spn/account/user`, fetched `/v1/spn/account/user/profile` | static `LOCAL_PROFILE` with `feature_ids = [history, bw-vis, vpn-compat]`; SPN not included | +| `status$` | watched `runtime:spn/status` | static `disabled` status | +| `watchPins()` | watched `map:main/` | always `[]` | +| `login()` / `logout()` | HTTP to `/v1/spn/account/...` | fail locally with `ERR_ACCOUNT_REMOVED`, no request | +| `loadFeaturePackages()` / `watchEnabledFeatures()` | HTTP to `/v1/account/features` | always `[]` | + +Effect: every `profile?.current_plan?.feature_ids?.includes(FeatureID.History)` +or `FeatureID.Bandwidth` check in the app (monitor, app-view, netquery, +dashboard, generic-setting upgrade lock) evaluates to `true`; every +`FeatureID.SPN` check evaluates to `false`. No outbound request to +`account.safing.io` or the ticket agent is issued by the UI. + +## Removed from the UI + +- Navigation: SPN map entry, "Re-Initialize SPN", "Logout Completely". +- Route `/spn` (the page component still compiles but is unreachable; + `**` redirects to the dashboard). +- Dashboard: "Features" (package upsell) widget, "Login / Subscribe" / + "Account Details" header, current-plan/billing text, "SPN Identities" + mini-stat, "Connections Tunneled through SPN" chart. +- Upsell copy: "Available in Portmaster Plus/Pro" and the pricing link in the + monitor page. + +## Left in place (dead but harmless) + +`spn-login`, `spn-account-details`, `spn-status`, `feature-scout`, `pages/spn` +still exist as components. They are either never rendered (`spnLoginRequired` +is `false`, SPN status is `disabled`, developer-expertise gated) or no longer +routed. Removing them entirely is optional clean-up. + +## Verify + +```bash +cd desktop/angular +npm ci +npm run build +grep -rn 'account.safing.io\|/v1/spn/account\|/v1/account/features' projects/safing/portmaster-api/src +# expected: no matches in spn.service.ts +``` diff --git a/desktop/angular/projects/safing/portmaster-api/src/lib/config.types.ts b/desktop/angular/projects/safing/portmaster-api/src/lib/config.types.ts index 99fe5d829..cef44e090 100644 --- a/desktop/angular/projects/safing/portmaster-api/src/lib/config.types.ts +++ b/desktop/angular/projects/safing/portmaster-api/src/lib/config.types.ts @@ -1,4 +1,3 @@ -import { FeatureID } from './features'; import { Record } from './portapi.types'; import { deepClone } from './utils'; @@ -145,7 +144,6 @@ export enum WellKnown { Requires = "safing/portbase:config:requires", RestartPending = "safing/portbase:options:restart-pending", EndpointListVerdictNames = "safing/portmaster:ui:endpoint-list:verdict-names", - RequiresFeatureID = "safing/portmaster:ui:config:requires-feature", RequiresUIReload = "safing/portmaster:ui:requires-reload", } @@ -164,7 +162,6 @@ export interface Annotations { [WellKnown.Stackable]?: true; [WellKnown.QuickSetting]?: QuickSetting | QuickSetting[] | CountrySelectionQuickSetting | CountrySelectionQuickSetting[]; [WellKnown.Requires]?: ValueRequirement | ValueRequirement[]; - [WellKnown.RequiresFeatureID]?: FeatureID | FeatureID[]; [WellKnown.RequiresUIReload]?: unknown, // Any thing else... [key: string]: any; diff --git a/desktop/angular/projects/safing/portmaster-api/src/lib/features.ts b/desktop/angular/projects/safing/portmaster-api/src/lib/features.ts deleted file mode 100644 index 658f1c1b9..000000000 --- a/desktop/angular/projects/safing/portmaster-api/src/lib/features.ts +++ /dev/null @@ -1,8 +0,0 @@ -export enum FeatureID { - None = "", - SPN = "spn", - PrioritySupport = "support", - History = "history", - Bandwidth = "bw-vis", - VPNCompat = "vpn-compat", -} diff --git a/desktop/angular/projects/safing/portmaster-api/src/lib/module.ts b/desktop/angular/projects/safing/portmaster-api/src/lib/module.ts index 13d5e048f..60ef72b52 100644 --- a/desktop/angular/projects/safing/portmaster-api/src/lib/module.ts +++ b/desktop/angular/projects/safing/portmaster-api/src/lib/module.ts @@ -5,7 +5,6 @@ import { DebugAPI } from "./debug-api.service"; import { MetaAPI } from "./meta-api.service"; import { Netquery } from "./netquery.service"; import { PortapiService, PORTMASTER_HTTP_API_ENDPOINT, PORTMASTER_WS_API_ENDPOINT } from "./portapi.service"; -import { SPNService } from "./spn.service"; import { WebsocketService } from "./websocket.service"; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { TauriHttpInterceptor } from "./platform-specific/tauri/tauri-http-interceptor"; @@ -67,7 +66,6 @@ export class PortmasterAPIModule { AppProfileService, DebugAPI, Netquery, - SPNService, { provide: PORTMASTER_HTTP_API_ENDPOINT, useValue: cfg.httpAPI, diff --git a/desktop/angular/projects/safing/portmaster-api/src/lib/portapi.service.ts b/desktop/angular/projects/safing/portmaster-api/src/lib/portapi.service.ts index 8c195e4fe..cee203e78 100644 --- a/desktop/angular/projects/safing/portmaster-api/src/lib/portapi.service.ts +++ b/desktop/angular/projects/safing/portmaster-api/src/lib/portapi.service.ts @@ -167,17 +167,16 @@ export class PortapiService { }); } - /** Triggers a pause of the portmaster or SPN service + /** Triggers a pause of the portmaster service * @param duration The duration of the pause in seconds - * @param onlySPN Whether or not only the SPN should be paused */ - pause(duration: number, onlySPN: boolean): Observable { - return this.http.post(`${this.httpEndpoint}/v1/control/pause`, { duration, onlySPN }, { + pause(duration: number): Observable { + return this.http.post(`${this.httpEndpoint}/v1/control/pause`, { duration }, { observe: 'response', responseType: 'arraybuffer', }); } - /** Triggers a resume of the portmaster (and SPN) service */ + /** Triggers a resume of the portmaster service */ resume(): Observable { return this.http.post(`${this.httpEndpoint}/v1/control/resume`, undefined, { observe: 'response', @@ -218,14 +217,6 @@ export class PortapiService { ); } - /** Re-initialize the SPN */ - reinitSPN(): Observable { - return this.http.post(`${this.httpEndpoint}/v1/spn/reinit`, undefined, { - observe: 'response', - responseType: 'arraybuffer', - }); - } - /** Cleans up the history database by applying history retention settings */ cleanupHistory(): Observable { return this.http.post( diff --git a/desktop/angular/projects/safing/portmaster-api/src/lib/spn.service.ts b/desktop/angular/projects/safing/portmaster-api/src/lib/spn.service.ts deleted file mode 100644 index eb4c5deaf..000000000 --- a/desktop/angular/projects/safing/portmaster-api/src/lib/spn.service.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { HttpClient, HttpParams, HttpResponse } from "@angular/common/http"; -import { Inject, Injectable } from "@angular/core"; -import { BehaviorSubject, Observable, of } from "rxjs"; -import { filter, map, share, switchMap } from "rxjs/operators"; -import { FeatureID } from "./features"; -import { PORTMASTER_HTTP_API_ENDPOINT, PortapiService } from './portapi.service'; -import { Feature, Pin, SPNStatus, UserProfile } from "./spn.types"; - -@Injectable() -export class SPNService { - - /** Emits the SPN status whenever it changes */ - status$: Observable; - - profile$ = this.watchProfile() - .pipe( - share({ connector: () => new BehaviorSubject(undefined) }), - filter(val => val !== undefined) - ) as Observable; - - private pins$: Observable; - - constructor( - private portapi: PortapiService, - private http: HttpClient, - @Inject(PORTMASTER_HTTP_API_ENDPOINT) private httpAPI: string, - ) { - this.status$ = this.portapi.watch('runtime:spn/status', { ignoreDelete: true }) - .pipe( - share({ connector: () => new BehaviorSubject(null) }), - filter(val => val !== null), - ) - - this.pins$ = this.status$ - .pipe( - switchMap(status => { - if (status.Status !== "disabled") { - return this.portapi.watchAll("map:main/", { retryDelay: 50000 }) - } - - return of([] as Pin[]); - }), - share({ connector: () => new BehaviorSubject(undefined) }), - filter(val => val !== undefined) - ) as Observable; - } - - /** - * Watches all pins of the "main" SPN map. - */ - watchPins(): Observable { - return this.pins$; - } - - /** - * Encodes a unicode string to base64. - * See https://developer.mozilla.org/en-US/docs/Web/API/btoa - * and https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings - */ - b64EncodeUnicode(str: string): string { - return window.btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { - return String.fromCharCode(parseInt(p1, 16)) - })) - } - - /** - * Logs into the SPN user account - */ - login({ username, password }: { username: string, password: string }): Observable> { - return this.http.post(`${this.httpAPI}/v1/spn/account/login`, undefined, { - headers: { - Authorization: `Basic ${this.b64EncodeUnicode(username + ':' + password)}` - }, - responseType: 'text', - observe: 'response' - }); - } - - /** - * Log out of the SPN user account - * - * @param purge Whether or not the portmaster should keep user/device information for the next login - */ - logout(purge = false): Observable> { - let params = new HttpParams(); - if (!!purge) { - params = params.set("purge", "true") - } - return this.http.delete(`${this.httpAPI}/v1/spn/account/logout`, { - params, - responseType: 'text', - observe: 'response' - }) - } - - watchEnabledFeatures(): Observable<(Feature & { enabled: boolean })[]> { - return this.profile$ - .pipe( - switchMap(profile => { - return this.loadFeaturePackages() - .pipe( - map(features => { - return features.map(feature => { - // console.log(feature, profile?.current_plan?.feature_ids) - return { - ...feature, - enabled: feature.RequiredFeatureID === FeatureID.None || profile?.current_plan?.feature_ids?.includes(feature.RequiredFeatureID) || false, - } - }) - }) - ) - }) - ); - } - - /** Returns a list of all feature packages */ - loadFeaturePackages(): Observable { - return this.http.get<{ Features: Feature[] }>(`${this.httpAPI}/v1/account/features`) - .pipe( - map(response => response.Features.map(feature => { - return { - ...feature, - IconURL: `${this.httpAPI}/v1/account/features/${feature.ID}/icon`, - } - })) - ); - } - - /** - * Returns the current SPN user profile. - * - * @param refresh Whether or not the user profile should be refreshed from the ticket agent - * @returns - */ - userProfile(refresh = false): Observable { - let params = new HttpParams(); - if (!!refresh) { - params = params.set("refresh", true) - } - return this.http.get(`${this.httpAPI}/v1/spn/account/user/profile`, { - params - }); - } - - /** - * Watches the user profile. It will emit null if there is no profile available yet. - */ - watchProfile(): Observable { - let hasSent = false; - return this.portapi.watch('core:spn/account/user', { ignoreDelete: true }, { forwardDone: true }) - .pipe( - filter(result => { - if ('type' in result && result.type === 'done') { - if (hasSent) { - return false; - } - } - - return true - }), - map(result => { - hasSent = true; - if ('type' in result) { - return null; - } - - return result; - }) - ); - } -} diff --git a/desktop/angular/projects/safing/portmaster-api/src/lib/spn.types.ts b/desktop/angular/projects/safing/portmaster-api/src/lib/spn.types.ts deleted file mode 100644 index b2e7caaf4..000000000 --- a/desktop/angular/projects/safing/portmaster-api/src/lib/spn.types.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { FeatureID } from './features'; -import { CountryInfo, GeoCoordinates, IntelEntity } from './network.types'; -import { Record } from './portapi.types'; - -export interface SPNStatus extends Record { - Status: 'failed' | 'disabled' | 'connecting' | 'connected'; - HomeHubID: string; - HomeHubName: string; - ConnectedIP: string; - ConnectedTransport: string; - ConnectedCountry: CountryInfo | null; - ConnectedSince: string | null; -} - -export interface Pin extends Record { - ID: string; - Name: string; - FirstSeen: string; - EntityV4?: IntelEntity | null; - EntityV6?: IntelEntity | null; - States: string[]; - SessionActive: boolean; - HopDistance: number; - ConnectedTo: { - [key: string]: Lane, - }; - Route: string[] | null; - VerifiedOwner: string; -} - -export interface Lane { - HubID: string; - Capacity: number; - Latency: number; -} - -export function getPinCoords(p: Pin): GeoCoordinates | null { - if (p.EntityV4 && p.EntityV4.Coordinates) { - return p.EntityV4.Coordinates; - } - return p.EntityV6?.Coordinates || null; -} - -export interface Device { - name: string; - id: string; -} - -export interface Subscription { - ends_at: string; - state: 'manual' | 'active' | 'cancelled'; - next_billing_date: string; - payment_provider: string; -} - -export interface Plan { - name: string; - amount: number; - months: number; - renewable: boolean; - feature_ids: FeatureID[]; -} - -export interface View { - Message: string; - ShowAccountData: boolean; - ShowAccountButton: boolean; - ShowLoginButton: boolean; - ShowRefreshButton: boolean; - ShowLogoutButton: boolean; -} - -export interface UserProfile extends Record { - username: string; - state: string; - balance: number; - device: Device | null; - subscription: Subscription | null; - current_plan: Plan | null; - next_plan: Plan | null; - view: View | null; - LastNotifiedOfEnd?: string; - LoggedInAt?: string; -} - -export interface Package { - Name: string; - HexColor: string; -} - -export interface Feature { - ID: string; - Name: string; - ConfigKey: string; - ConfigScope: string; - RequiredFeatureID: FeatureID; - InPackage: Package | null; - Comment: string; - Beta?: boolean; - ComingSoon?: boolean; - - // does not come from the PM API but is set by SPNService - IconURL: string; -} diff --git a/desktop/angular/projects/safing/portmaster-api/src/public-api.ts b/desktop/angular/projects/safing/portmaster-api/src/public-api.ts index 9097761ea..90d0f69ca 100644 --- a/desktop/angular/projects/safing/portmaster-api/src/public-api.ts +++ b/desktop/angular/projects/safing/portmaster-api/src/public-api.ts @@ -8,15 +8,12 @@ export * from './lib/config.service'; export * from './lib/config.types'; export * from './lib/core.types'; export * from './lib/debug-api.service'; -export * from './lib/features'; export * from './lib/meta-api.service'; export * from './lib/module'; export * from './lib/netquery.service'; export * from './lib/network.types'; export * from './lib/portapi.service'; export * from './lib/portapi.types'; -export * from './lib/spn.service'; -export * from './lib/spn.types'; export * from './lib/utils'; export * from './lib/websocket.service'; diff --git a/desktop/angular/src/app/app-routing.module.ts b/desktop/angular/src/app/app-routing.module.ts index 2324ae8bd..c7e38391a 100644 --- a/desktop/angular/src/app/app-routing.module.ts +++ b/desktop/angular/src/app/app-routing.module.ts @@ -4,7 +4,6 @@ import { AppViewComponent } from './pages/app-view'; import { DashboardPageComponent } from './pages/dashboard/dashboard.component'; import { MonitorPageComponent } from './pages/monitor'; import { SettingsComponent } from './pages/settings/settings'; -import { SpnPageComponent } from './pages/spn'; import { SupportPageComponent } from './pages/support'; import { SupportFormComponent } from './pages/support/form'; @@ -47,10 +46,6 @@ const routes: Routes = [ path: 'support/:id', component: SupportFormComponent, }, - { - path: 'spn', - component: SpnPageComponent, - }, { path: '**', redirectTo: 'dashboard' diff --git a/desktop/angular/src/app/app.module.ts b/desktop/angular/src/app/app.module.ts index 12fab1428..ebf37a39e 100644 --- a/desktop/angular/src/app/app.module.ts +++ b/desktop/angular/src/app/app.module.ts @@ -27,14 +27,10 @@ import { NavigationComponent } from './layout/navigation/navigation'; import { SideDashComponent } from './layout/side-dash/side-dash'; import { AppOverviewComponent, AppViewComponent, QuickSettingInternetButtonComponent } from './pages/app-view'; import { QsHistoryComponent } from './pages/app-view/qs-history/qs-history.component'; -import { QuickSettingSelectExitButtonComponent } from './pages/app-view/qs-select-exit/qs-select-exit'; -import { QuickSettingUseSPNButtonComponent } from './pages/app-view/qs-use-spn/qs-use-spn'; import { QuickSettingUseSplitTunButtonComponent } from './pages/app-view/qs-use-splittun/qs-use-splittun'; import { DashboardPageComponent } from './pages/dashboard/dashboard.component'; -import { FeatureCardComponent } from './pages/dashboard/feature-card/feature-card.component'; import { MonitorPageComponent } from './pages/monitor'; import { SettingsComponent } from './pages/settings/settings'; -import { SPNModule } from './pages/spn/spn.module'; import { SupportPageComponent } from './pages/support'; import { SupportFormComponent } from './pages/support/form'; import { NotificationsService } from './services'; @@ -47,10 +43,10 @@ import { EditProfileDialog } from './shared/edit-profile-dialog'; import { ExitScreenComponent } from './shared/exit-screen/exit-screen'; import { ExpertiseModule } from './shared/expertise/expertise.module'; import { ExternalLinkDirective } from './shared/external-link.directive'; -import { FeatureScoutComponent } from './shared/feature-scout'; import { SfngFocusModule } from './shared/focus'; import { FuzzySearchPipe } from './shared/fuzzySearch'; import { LoadingComponent } from './shared/loading'; +import { MapRendererComponent } from './shared/map-renderer'; import { SfngMenuModule } from './shared/menu'; import { SfngMultiSwitchModule } from './shared/multi-switch'; import { NetqueryModule } from './shared/netquery'; @@ -61,9 +57,6 @@ import { CommonPipesModule } from './shared/pipes'; import { ProcessDetailsDialogComponent } from './shared/process-details-dialog'; import { PromptListComponent } from './shared/prompt-list/prompt-list.component'; import { SecurityLockComponent } from './shared/security-lock'; -import { SPNAccountDetailsComponent } from './shared/spn-account-details'; -import { SPNLoginComponent } from './shared/spn-login'; -import { SPNStatusComponent } from './shared/spn-status'; import { PlaceholderComponent } from './shared/text-placeholder'; import { DashboardWidgetComponent } from './pages/dashboard/dashboard-widget/dashboard-widget.component'; import { MergeProfileDialogComponent } from './pages/app-view/merge-profile-dialog/merge-profile-dialog.component'; @@ -75,7 +68,7 @@ import { SupportProgressDialogComponent } from './pages/support/progress-dialog' function loadAndSetLocaleInitializer(configService: ConfigService) { return async function () { let angularLocaleID = 'en-GB'; - let nzLocaleID: string = 'en_GB'; + let nzLocaleID = 'en_GB'; try { const setting = await firstValueFrom(configService.get("core/locale")) @@ -138,8 +131,6 @@ const localeConfig = { FuzzySearchPipe, AppViewComponent, QuickSettingInternetButtonComponent, - QuickSettingUseSPNButtonComponent, - QuickSettingSelectExitButtonComponent, QuickSettingUseSplitTunButtonComponent, AppOverviewComponent, PlaceholderComponent, @@ -149,17 +140,13 @@ const localeConfig = { SupportPageComponent, SupportFormComponent, SecurityLockComponent, - SPNStatusComponent, - FeatureScoutComponent, - SPNLoginComponent, - SPNAccountDetailsComponent, NetworkScoutComponent, EditProfileDialog, ProcessDetailsDialogComponent, QsHistoryComponent, DashboardPageComponent, DashboardWidgetComponent, - FeatureCardComponent, + MapRendererComponent, MergeProfileDialogComponent, AppInsightsComponent, SupportProgressDialogComponent, @@ -202,7 +189,6 @@ const localeConfig = { NetqueryModule, CommonPipesModule, UiModule, - SPNModule, PortmasterAPIModule.forRoot({ httpAPI: environment.httpAPI, websocketAPI: environment.portAPI, diff --git a/desktop/angular/src/app/integration/browser.ts b/desktop/angular/src/app/integration/browser.ts index 3bfe8c7bf..26c38b0d5 100644 --- a/desktop/angular/src/app/integration/browser.ts +++ b/desktop/angular/src/app/integration/browser.ts @@ -2,7 +2,7 @@ import { AppInfo, IntegrationService, PortmasterDir, ProcessInfo } from "./integ export class BrowserIntegrationService implements IntegrationService { writeToClipboard(text: string): Promise { - if (!!navigator.clipboard) { + if (navigator.clipboard) { return navigator.clipboard.writeText(text); } @@ -35,7 +35,9 @@ export class BrowserIntegrationService implements IntegrationService { onExitRequest(cb: () => void): () => void { // nothing to do, there - return () => { } + return () => { + // nothing to do, there + } } } diff --git a/desktop/angular/src/app/integration/electron.ts b/desktop/angular/src/app/integration/electron.ts index 316a31380..5c05aa343 100644 --- a/desktop/angular/src/app/integration/electron.ts +++ b/desktop/angular/src/app/integration/electron.ts @@ -4,7 +4,7 @@ import { AppInfo, PortmasterDir, ProcessInfo } from "./integration"; export class ElectronIntegrationService extends BrowserIntegrationService { openExternal(pathOrUrl: string): Promise { - if (!!window.app) { + if (window.app) { return window.app.openExternal(pathOrUrl); } @@ -24,7 +24,7 @@ export class ElectronIntegrationService extends BrowserIntegrationService { } getAppIcon(info: ProcessInfo): Promise { - if (!!window.app) { + if (window.app) { return window.app.getFileIcon(info.execPath) } @@ -36,7 +36,7 @@ export class ElectronIntegrationService extends BrowserIntegrationService { } exitApp(): Promise { - if (!!window.app) { + if (window.app) { window.app.exitApp(); } @@ -44,7 +44,7 @@ export class ElectronIntegrationService extends BrowserIntegrationService { } onExitRequest(cb: () => void): () => void { - let listener = (event: MessageEvent) => { + const listener = (event: MessageEvent) => { if (event.data === 'on-app-close') { cb(); } diff --git a/desktop/angular/src/app/layout/navigation/navigation.html b/desktop/angular/src/app/layout/navigation/navigation.html index 272521913..561218a9b 100644 --- a/desktop/angular/src/app/layout/navigation/navigation.html +++ b/desktop/angular/src/app/layout/navigation/navigation.html @@ -112,19 +112,6 @@ - - - - - Pause SPN for 5 minutes - Pause SPN for 15 minutes - Pause SPN for 1 hour -
Pause for 5 minutes Pause for 15 minutes Pause for 1 hour diff --git a/desktop/angular/src/app/layout/navigation/navigation.scss b/desktop/angular/src/app/layout/navigation/navigation.scss index 4683bec54..a661aad65 100644 --- a/desktop/angular/src/app/layout/navigation/navigation.scss +++ b/desktop/angular/src/app/layout/navigation/navigation.scss @@ -83,7 +83,6 @@ fa-icon { &.dash, - &.spn, &.monitor, &.app, &.help, diff --git a/desktop/angular/src/app/layout/navigation/navigation.ts b/desktop/angular/src/app/layout/navigation/navigation.ts index 65d2597b4..cffee7c4d 100644 --- a/desktop/angular/src/app/layout/navigation/navigation.ts +++ b/desktop/angular/src/app/layout/navigation/navigation.ts @@ -1,7 +1,7 @@ import { INTEGRATION_SERVICE, IntegrationService } from 'src/app/integration'; import { ConnectedPosition } from '@angular/cdk/overlay'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Inject, OnInit, Output, inject } from '@angular/core'; -import { ConfigService, DebugAPI, PortapiService, SPNService, StringSetting, BoolSetting } from '@safing/portmaster-api'; +import { ConfigService, DebugAPI, PortapiService, StringSetting } from '@safing/portmaster-api'; import { tap } from 'rxjs/operators'; import { AppComponent } from 'src/app/app.component'; import { NotificationType, NotificationsService, StatusService, VersionStatus, GetModuleState, ControlPauseStateData } from 'src/app/services'; @@ -34,19 +34,13 @@ export class NavigationComponent implements OnInit { hasNewNotifications = false; /** The color to use for the notifcation-available hint (dot) */ - notificationColor: string = 'text-green-300'; + notificationColor = 'text-green-300'; pauseState: ControlPauseStateData | null = null; - get isPaused(): boolean { return this.pauseState?.Interception===true || this.pauseState?.SPN===true; } - get isPausedInterception(): boolean { return this.pauseState?.Interception===true; } - get isPausedSPN(): boolean { return this.pauseState?.SPN===true; } + get isPaused(): boolean { return this.pauseState?.Interception===true; } get pauseInfo(): string { - if (this.pauseState?.Interception===true && this.pauseState?.SPN===true) - return 'Portmaster and SPN are paused'; - else if (this.pauseState?.Interception===true) + if (this.pauseState?.Interception===true) return 'Portmaster is paused'; - else if (this.pauseState?.SPN===true) - return 'SPN is paused'; return ''; } get pauseInfoTillTime(): string { @@ -65,9 +59,6 @@ export class NavigationComponent implements OnInit { /** Whether or not prompting is globally enabled. */ globalPromptingEnabled = false; - /** Whether or not the SPN is currently enabled */ - spnEnabled = false; - @Output() sideDashChange = new EventEmitter<'collapsed' | 'expanded' | 'force-overlay'>(); @@ -83,7 +74,6 @@ export class NavigationComponent implements OnInit { private debugAPI: DebugAPI, private actionIndicator: ActionIndicatorService, private notificationService: NotificationsService, - private spnService: SPNService, private cdr: ChangeDetectorRef ) { } @@ -128,12 +118,6 @@ export class NavigationComponent implements OnInit { this.globalPromptingEnabled = defaultAction === 'ask'; this.cdr.markForCheck(); }) - - this.configService.watch("spn/enable") - .subscribe(value => { - this.spnEnabled = value; - this.cdr.markForCheck(); - }); this.notificationService.new$ .subscribe(notif => { @@ -207,24 +191,6 @@ export class NavigationComponent implements OnInit { )) } - /** Re-initialize the SPN */ - reinitSPN(_: Event) { - this.portapi.reinitSPN() - .subscribe(this.actionIndicator.httpObserver( - 'Re-initialized SPN', - 'Failed to re-initialize the SPN' - )) - } - - /** Logs the user out of the SPN completely by purgin the user profile from the local storage */ - logoutCompletely(_: Event) { - this.spnService.logout(true) - .subscribe(this.actionIndicator.httpObserver( - 'Logout', - 'You have been logged out of the SPN completely.' - )) - } - /** * @private * Clear the DNS name cache. @@ -293,24 +259,12 @@ export class NavigationComponent implements OnInit { event.preventDefault(); event.stopPropagation(); - this.portapi.pause(duration, false) + this.portapi.pause(duration) .subscribe(this.actionIndicator.httpObserver( 'Pausing ...', 'Failed to Pause', )) } - pauseSPN(event: Event, duration: number) { - // prevent default and stop-propagation to avoid - // expanding the accordion body. - event.preventDefault(); - event.stopPropagation(); - - this.portapi.pause(duration, true) - .subscribe(this.actionIndicator.httpObserver( - 'Pausing SPN...', - 'Failed to Pause SPN', - )) - } resume(event: Event) { // prevent default and stop-propagation to avoid // expanding the accordion body. @@ -318,12 +272,8 @@ export class NavigationComponent implements OnInit { event.stopPropagation(); let msg = 'Resuming ...'; - if (this.pauseState?.Interception===true && this.pauseState?.SPN===true) - msg = 'Resuming Portmaster and SPN ...'; - else if (this.pauseState?.Interception===true) + if (this.pauseState?.Interception===true) msg = 'Resuming Portmaster ...'; - else if (this.pauseState?.SPN===true) - msg = 'Resuming SPN ...'; this.portapi.resume() .subscribe(this.actionIndicator.httpObserver( diff --git a/desktop/angular/src/app/layout/side-dash/side-dash.html b/desktop/angular/src/app/layout/side-dash/side-dash.html index a4f8e073e..63a0b05d9 100644 --- a/desktop/angular/src/app/layout/side-dash/side-dash.html +++ b/desktop/angular/src/app/layout/side-dash/side-dash.html @@ -2,9 +2,6 @@ - - - - + diff --git a/desktop/angular/src/app/layout/side-dash/side-dash.ts b/desktop/angular/src/app/layout/side-dash/side-dash.ts index c48366346..a9e1a43e1 100644 --- a/desktop/angular/src/app/layout/side-dash/side-dash.ts +++ b/desktop/angular/src/app/layout/side-dash/side-dash.ts @@ -6,8 +6,4 @@ import { ChangeDetectionStrategy, Component } from '@angular/core'; styleUrls: ['./side-dash.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) -export class SideDashComponent { - /** Whether or not a SPN account login is required */ - spnLoginRequired = false; - -} +export class SideDashComponent { } diff --git a/desktop/angular/src/app/pages/app-view/app-view.html b/desktop/angular/src/app/pages/app-view/app-view.html index 96235c8cc..9f629339a 100644 --- a/desktop/angular/src/app/pages/app-view/app-view.html +++ b/desktop/angular/src/app/pages/app-view/app-view.html @@ -1,3 +1,4 @@ +
@@ -56,7 +57,7 @@

None + sfng-tooltip="No network history recorded for this app yet">None

@@ -67,15 +68,9 @@

- + - - - - - - @@ -122,16 +117,9 @@

{{ (100 / stats!.size) 'h-20 sfng-lg:w-32 sfng-lg:h-24': !collapseHeader }" class="flex flex-col justify-center items-center px-4 py-1 w-24 bg-gray-300 bg-opacity-75 rounded border border-gray-300 shadow transition-all duration-200"> -

+

{{ stats.bytes_received | bytes }}

- - - Available in Plus - - Received @@ -139,8 +127,7 @@

{{ (100 / stats!.size) 'h-20 sfng-lg:w-32 sfng-lg:h-24': !collapseHeader }" class="flex flex-col justify-center items-center px-4 py-1 w-24 bg-gray-300 bg-opacity-75 rounded border border-gray-300 shadow transition-all duration-200"> -

+

{{ stats.bytes_sent | bytes }}

Sent @@ -174,7 +161,7 @@

{{ (100 / stats!.size)
- diff --git a/desktop/angular/src/app/pages/app-view/app-view.ts b/desktop/angular/src/app/pages/app-view/app-view.ts index e46369526..0103286db 100644 --- a/desktop/angular/src/app/pages/app-view/app-view.ts +++ b/desktop/angular/src/app/pages/app-view/app-view.ts @@ -1,13 +1,11 @@ import { ChangeDetectorRef, Component, - DestroyRef, OnDestroy, OnInit, ViewChild, inject, } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router } from '@angular/router'; import { AppProfile, @@ -17,13 +15,11 @@ import { Database, DebugAPI, ExpertiseLevel, - FeatureID, FlatConfigObject, IProfileStats, LayeredProfile, Netquery, PortapiService, - SPNService, Setting, flattenProfileConfig, setAppSetting @@ -71,13 +67,6 @@ export class AppViewComponent implements OnInit, OnDestroy { @ViewChild(SfngNetqueryViewer) netqueryViewer?: SfngNetqueryViewer; - destroyRef = inject(DestroyRef); - spn = inject(SPNService); - - canUseHistory = false; - canViewBW = false; - canUseSPN = false; - /** subscription to our update-process observable */ private subscription = Subscription.EMPTY; @@ -234,13 +223,13 @@ export class AppViewComponent implements OnInit, OnDestroy { // Actually safe the profile this.profileService.saveProfile(this.appProfile!).subscribe({ next: () => { - if (!!event.accepted) { + if (event.accepted) { event.accepted(); } }, error: (err) => { // if there's a callback function for errors call it. - if (!!event.rejected) { + if (event.rejected) { event.rejected(err); } @@ -437,7 +426,7 @@ export class AppViewComponent implements OnInit, OnDestroy { async ([profile, queryMap, global, allSettings, viewSetting]) => { const previousProfile = this.appProfile; - if (!!profile) { + if (profile) { const key = profile![0].Source + '/' + profile![0].ID; const query: Condition = { @@ -519,7 +508,7 @@ export class AppViewComponent implements OnInit, OnDestroy { this._loading = false; - if (!!this.appProfile?.PresentationPath) { + if (this.appProfile?.PresentationPath) { let parts: string[] = []; let sep = '/'; if (this.appProfile.PresentationPath[0] === '/') { @@ -543,7 +532,7 @@ export class AppViewComponent implements OnInit, OnDestroy { // if we have a profile flatten it's configuration map to something // more useful. - if (!!this.appProfile) { + if (this.appProfile) { profileConfig = flattenProfileConfig(this.appProfile.Config); } @@ -561,7 +550,7 @@ export class AppViewComponent implements OnInit, OnDestroy { // the action button would fail and the user would not notice something // changing. // - if (!!this.highlightSettingKey) { + if (this.highlightSettingKey) { if (profileConfig[this.highlightSettingKey] === undefined) { this.viewSettingChange.next('all'); } @@ -610,19 +599,6 @@ export class AppViewComponent implements OnInit, OnDestroy { this.cdr.markForCheck(); } ); - - this.spn.profile$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ - next: (profile) => { - this.canUseHistory = - profile?.current_plan?.feature_ids?.includes(FeatureID.History) || - false; - this.canViewBW = - profile?.current_plan?.feature_ids?.includes(FeatureID.Bandwidth) || - false; - this.canUseSPN = - profile?.current_plan?.feature_ids?.includes(FeatureID.SPN) || false; - }, - }); } /** diff --git a/desktop/angular/src/app/pages/app-view/overview.html b/desktop/angular/src/app/pages/app-view/overview.html index 4fbcdc501..50303ad04 100644 --- a/desktop/angular/src/app/pages/app-view/overview.html +++ b/desktop/angular/src/app/pages/app-view/overview.html @@ -126,11 +126,11 @@

All

- + diff --git a/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.html b/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.html index 77c341996..ee615d8a6 100644 --- a/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.html +++ b/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.html @@ -3,10 +3,5 @@ Keep History - - Get Plus - - - +
diff --git a/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.ts b/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.ts index 24e6296a8..1b2f3af29 100644 --- a/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.ts +++ b/desktop/angular/src/app/pages/app-view/qs-history/qs-history.component.ts @@ -6,18 +6,12 @@ import { OnChanges, Output, SimpleChanges, - inject, } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { BoolSetting, - FeatureID, - SPNService, Setting, getActualValue, } from '@safing/portmaster-api'; -import { BehaviorSubject, Observable, map } from 'rxjs'; -import { share } from 'rxjs/operators'; import { SaveSettingEvent } from 'src/app/shared/config'; @Component({ @@ -27,18 +21,6 @@ import { SaveSettingEvent } from 'src/app/shared/config'; }) export class QsHistoryComponent implements OnChanges { currentValue = false; - historyFeatureAllowed: Observable = inject(SPNService).profile$.pipe( - takeUntilDestroyed(), - map((profile) => { - return ( - profile?.current_plan?.feature_ids?.includes(FeatureID.History) || false - ); - }), - share({ connector: () => new BehaviorSubject(false) }) - ); - - @Input() - canUse: boolean = true; @Input() settings: Setting[] = []; diff --git a/desktop/angular/src/app/pages/app-view/qs-select-exit/index.ts b/desktop/angular/src/app/pages/app-view/qs-select-exit/index.ts deleted file mode 100644 index 56c7267ea..000000000 --- a/desktop/angular/src/app/pages/app-view/qs-select-exit/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './qs-select-exit'; diff --git a/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.html b/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.html deleted file mode 100644 index 66f9fa135..000000000 --- a/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.html +++ /dev/null @@ -1,39 +0,0 @@ -
- - SPN Exit - - - - Get Pro - - - - - Automatic - - - - - - - - - - {{ option.Name }} - - - - - - - - - - Disabled - - -
diff --git a/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.scss b/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.scss deleted file mode 100644 index e69de29bb..000000000 diff --git a/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.ts b/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.ts deleted file mode 100644 index 698607b60..000000000 --- a/desktop/angular/src/app/pages/app-view/qs-select-exit/qs-select-exit.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { - ChangeDetectionStrategy, - ChangeDetectorRef, - Component, - DestroyRef, - EventEmitter, - Input, - OnChanges, - OnInit, - Output, - SimpleChanges, - inject, -} from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { - BoolSetting, - StringArraySetting, - CountrySelectionQuickSetting, - ConfigService, - Setting, - getActualValue, -} from '@safing/portmaster-api'; -import { SaveSettingEvent } from 'src/app/shared/config/generic-setting/generic-setting'; - -@Component({ - selector: 'app-qs-select-exit', - templateUrl: './qs-select-exit.html', - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class QuickSettingSelectExitButtonComponent - implements OnInit, OnChanges -{ - private destroyRef = inject(DestroyRef); - - @Input() - canUse: boolean = true; - - @Input() - settings: Setting[] = []; - - @Output() - save = new EventEmitter(); - - spnEnabled: boolean | null = null; - exitRuleSetting: StringArraySetting | null = null; - - selectedExitRules: string | undefined = undefined; - availableExitRules: CountrySelectionQuickSetting[] | null = null; - - constructor( - private configService: ConfigService, - private cdr: ChangeDetectorRef - ) {} - - updateExitRules(newExitRules: string) { - this.selectedExitRules = newExitRules; - - let newConfigValue: string[] = []; - if (!!newExitRules) { - newConfigValue = newExitRules.split(','); - } - - this.save.next({ - isDefault: false, - key: 'spn/exitHubPolicy', - value: newConfigValue, - }); - } - - ngOnChanges(changes: SimpleChanges): void { - if ('settings' in changes) { - this.exitRuleSetting = null; - this.selectedExitRules = undefined; - - const exitRuleSetting = this.settings.find( - (s) => s.Key == 'spn/exitHubPolicy' - ) as StringArraySetting | undefined; - if (exitRuleSetting) { - this.exitRuleSetting = exitRuleSetting; - this.updateOptions(); - } - } - } - - ngOnInit() { - this.configService - .watch('spn/enable') - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe((value) => { - this.spnEnabled = value; - this.updateOptions(); - }); - } - - private updateOptions() { - if (!this.exitRuleSetting) { - this.selectedExitRules = undefined; - this.availableExitRules = null; - return; - } - - if (!!this.exitRuleSetting.Value && this.exitRuleSetting.Value.length > 0) { - this.selectedExitRules = this.exitRuleSetting.Value.join(','); - } - this.availableExitRules = this.getQuickSettings(); - - this.cdr.markForCheck(); - } - - private getQuickSettings(): CountrySelectionQuickSetting[] { - if (!this.exitRuleSetting) { - return []; - } - - let val = this.exitRuleSetting.Annotations[ - 'safing/portbase:ui:quick-setting' - ] as CountrySelectionQuickSetting[]; - if (val === undefined) { - return []; - } - - if (!Array.isArray(val)) { - return []; - } - - return val; - } -} diff --git a/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.html b/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.html index a07a3736f..80fea76ab 100644 --- a/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.html +++ b/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.html @@ -1,8 +1,8 @@
- + [sfng-tooltip]="interferingSettings.length > 0 ? tooltipTemplate : null"> + Split Tunnel @@ -21,15 +21,12 @@ + style="top: 2px; transform: translateX(-2px)" *ngIf="interferingSettings.length > 0">
Settings that may interfere with Split Tunnel:
    -
  • SPN is routing all traffic, fully bypassing Split Tunnel
  • -
  • SPN is routing non-excluded connections, partially bypassing Split Tunnel
  • diff --git a/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.ts b/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.ts index 49ad402bb..2cd510368 100644 --- a/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.ts +++ b/desktop/angular/src/app/pages/app-view/qs-use-splittun/qs-use-splittun.ts @@ -7,9 +7,6 @@ const configKeys = { splitTunUse: 'splittun/use', splitTunEnable: 'splittun/enable', splitTunUsagePolicy: 'splittun/usagePolicy', - spnUse: 'spn/use', - spnEnable: 'spn/enable', - spnUsagePolicy: 'spn/usagePolicy', } as const; @Component({ @@ -34,15 +31,6 @@ export class QuickSettingUseSplitTunButtonComponent implements OnInit, OnChanges /** Whether the Split Tunneling module is globally enabled. null = not yet loaded. */ splitTunModuleEnabled: boolean | null = null; - /** Whether SPN is enabled for this app — overrides split tunnel for SPN-routed connections. */ - spnEnabled = false; - - /** Whether SPN fully overrides split tunnel: SPN in use with no Exclude rules in spn/usagePolicy. */ - spnFullOverride = false; - - /** Whether the SPN module is globally enabled. */ - private spnModuleEnabled = false; - constructor( private configService: ConfigService, private cdr: ChangeDetectorRef @@ -69,14 +57,6 @@ export class QuickSettingUseSplitTunButtonComponent implements OnInit, OnChanges this.updateInterfering(); this.cdr.markForCheck(); }); - - this.configService.watch(configKeys.spnEnable) - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(value => { - this.spnModuleEnabled = !!value; - this.updateInterfering(); - this.cdr.markForCheck(); - }); } updateUseSplitTun(enabled: boolean): void { @@ -89,24 +69,11 @@ export class QuickSettingUseSplitTunButtonComponent implements OnInit, OnChanges private updateInterfering(): void { this.interferingSettings = []; - this.spnEnabled = false; - this.spnFullOverride = false; if (!this.currentValue || !this.splitTunModuleEnabled) { return; } - const spnUseSetting = this.settings.find(s => s.Key === configKeys.spnUse) as BoolSetting | undefined; - this.spnEnabled = this.spnModuleEnabled && !!spnUseSetting && !!getActualValue(spnUseSetting); - - // If SPN is enabled, check if it fully overrides Split Tunnel (no Exclude rules in SPN policy) - if (this.spnEnabled) { - const spnPolicy = this.settings.find(s => s.Key === configKeys.spnUsagePolicy) as StringArraySetting | undefined; - const spnPolicyValue = spnPolicy ? getActualValue(spnPolicy) : []; - const hasSpnExcludeRules = Array.isArray(spnPolicyValue) && spnPolicyValue.some(rule => rule.startsWith('- ') || rule === '-'); - this.spnFullOverride = !hasSpnExcludeRules; - } - // Exclude rules in usagePolicy may prevent some connections from being tunneled const usagePolicy = this.settings.find(s => s.Key === configKeys.splitTunUsagePolicy) as StringArraySetting | undefined; if (usagePolicy) { diff --git a/desktop/angular/src/app/pages/app-view/qs-use-spn/index.ts b/desktop/angular/src/app/pages/app-view/qs-use-spn/index.ts deleted file mode 100644 index aba9748a8..000000000 --- a/desktop/angular/src/app/pages/app-view/qs-use-spn/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './qs-use-spn'; diff --git a/desktop/angular/src/app/pages/app-view/qs-use-spn/qs-use-spn.html b/desktop/angular/src/app/pages/app-view/qs-use-spn/qs-use-spn.html deleted file mode 100644 index 58ceb09dd..000000000 --- a/desktop/angular/src/app/pages/app-view/qs-use-spn/qs-use-spn.html +++ /dev/null @@ -1,42 +0,0 @@ -
    - - Use SPN - - - - Get Pro - - - - - - - Disabled - - - - - - - - -
    - - - The following enabled settings may interfere: -
      - -
    • - {{ setting.Name }} -
    • -
      -
    -
    diff --git a/desktop/angular/src/app/pages/app-view/qs-use-spn/qs-use-spn.ts b/desktop/angular/src/app/pages/app-view/qs-use-spn/qs-use-spn.ts deleted file mode 100644 index f4e5bb2ea..000000000 --- a/desktop/angular/src/app/pages/app-view/qs-use-spn/qs-use-spn.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, inject } from "@angular/core"; -import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { BoolSetting, ConfigService, Setting, getActualValue } from "@safing/portmaster-api"; -import { SaveSettingEvent } from "src/app/shared/config/generic-setting/generic-setting"; - -const interferingSettingsWhenOn = [ - 'spn/usagePolicy' -] - -@Component({ - selector: 'app-qs-use-spn', - templateUrl: './qs-use-spn.html', - changeDetection: ChangeDetectionStrategy.OnPush -}) -export class QuickSettingUseSPNButtonComponent implements OnInit, OnChanges { - private destroyRef = inject(DestroyRef); - - @Input() - canUse: boolean = true; - - @Input() - settings: Setting[] = []; - - @Output() - save = new EventEmitter(); - - currentValue = false - - interferingSettings: Setting[] = []; - - /* Whether or not the SPN is currently disabled. null means we don't know yet ... */ - spnDisabled: boolean | null = null; - - constructor( - private configService: ConfigService, - private cdr: ChangeDetectorRef - ) { } - - ngOnChanges(changes: SimpleChanges): void { - if ('settings' in changes) { - this.currentValue = false; - - const useSpnSetting = this.settings.find(s => s.Key === 'spn/use') as (BoolSetting | undefined); - if (!!useSpnSetting) { - this.currentValue = getActualValue(useSpnSetting); - this.updateInterfering(); - } - } - } - - updateUseSpn(allowed: boolean) { - this.save.next({ - isDefault: false, - key: 'spn/use', - value: allowed, - }) - } - - ngOnInit() { - this.configService.watch('spn/enable') - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(value => { - this.spnDisabled = !value; - this.cdr.markForCheck(); - this.updateInterfering(); - }) - } - - private updateInterfering() { - this.interferingSettings = []; - - // only "enabled" state has interfering settings - // only show if we already know if the SPN module is enabled - if (!this.currentValue || this.spnDisabled !== false) { - return - } - - // create a lookup map for setting key to setting - const lm = new Map(); - this.settings.forEach(s => lm.set(s.Key, s)) - - - this.interferingSettings = interferingSettingsWhenOn - .map(key => lm.get(key)) - .filter(setting => { - if (!setting) { - return false; - } - const value = getActualValue(setting); - if (Array.isArray(value)) { - return value.length > 0; - } - - return !!value; - }) as Setting[]; - } -} diff --git a/desktop/angular/src/app/pages/dashboard/dashboard.component.html b/desktop/angular/src/app/pages/dashboard/dashboard.component.html index df7e8ca7c..8da711c43 100644 --- a/desktop/angular/src/app/pages/dashboard/dashboard.component.html +++ b/desktop/angular/src/app/pages/dashboard/dashboard.component.html @@ -1,3 +1,4 @@ +
    - -
    - - -
    -
    + {{ blockedConnections }}
    + {{ activeConnections }}
    + {{ activeProfiles }}
    + - + {{ dataIncoming | bytes }} - - Available in
    Portmaster Plus -
    + - + {{ dataOutgoing | bytes }} - - Available in
    Portmaster Plus -
    -
    - - {{ activeIdentities }} - - Available in
    Portmaster Pro -
    -
    +
    -
    - - - -
    @@ -204,25 +127,15 @@

    - + - - - - - Available in Portmaster Plus - + + - - - - - Available in Portmaster Plus - + + diff --git a/desktop/angular/src/app/pages/dashboard/dashboard.component.ts b/desktop/angular/src/app/pages/dashboard/dashboard.component.ts index 6b8d2ccce..8e708669b 100644 --- a/desktop/angular/src/app/pages/dashboard/dashboard.component.ts +++ b/desktop/angular/src/app/pages/dashboard/dashboard.component.ts @@ -2,13 +2,11 @@ import { KeyValue } from "@angular/common"; import { AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, ElementRef, OnInit, QueryList, TrackByFunction, ViewChild, ViewChildren, forwardRef, inject } from "@angular/core"; import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { Router } from "@angular/router"; -import { AppProfileService, BandwidthChartResult, ChartResult, Database, FeatureID, Netquery, PortapiService, SPNService, UserProfile, Verdict } from "@safing/portmaster-api"; -import { SfngDialogService, SfngTabGroupComponent } from "@safing/ui"; +import { AppProfileService, BandwidthChartResult, ChartResult, Database, Netquery, PortapiService, Verdict } from "@safing/portmaster-api"; +import { SfngTabGroupComponent } from "@safing/ui"; import { Observable, catchError, filter, interval, map, repeat, retry, startWith, throwError } from "rxjs"; -import { ActionIndicatorService } from 'src/app/shared/action-indicator'; import { DefaultBandwidthChartConfig, SfngNetqueryLineChartComponent } from "src/app/shared/netquery/line-chart/line-chart"; -import { SPNAccountDetailsComponent } from "src/app/shared/spn-account-details"; -import { MAP_HANDLER, MapRef } from "../spn/map-renderer"; +import { MAP_HANDLER, MapRef } from "src/app/shared/map-renderer"; import { CircularBarChartConfig, splitQueryResult } from "src/app/shared/netquery/circular-bar-chart/circular-bar-chart.component"; import { BytesPipe } from "src/app/shared/pipes/bytes.pipe"; import { HttpErrorResponse } from "@angular/common/http"; @@ -62,10 +60,7 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { private readonly destroyRef = inject(DestroyRef); private readonly netquery = inject(Netquery); - private readonly spn = inject(SPNService); - private readonly actionIndicator = inject(ActionIndicatorService); private readonly cdr = inject(ChangeDetectorRef); - private readonly dialog = inject(SfngDialogService); private readonly portapi = inject(PortapiService) private readonly router = inject(Router); @@ -155,27 +150,17 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { bwChartConfig = DefaultBandwidthChartConfig; - activeConnections: number = 0; - blockedConnections: number = 0; - activeProfiles: number = 0; - activeIdentities = 0; + activeConnections = 0; + blockedConnections = 0; + activeProfiles = 0; dataIncoming = 0; dataOutgoing = 0; connectionChart: ChartResult[] = []; - tunneldConnectionChart: ChartResult[] = []; countriesPerProfile: { [profile: string]: string[] } = {} - profile: UserProfile | null = null; - - featureBw = false; - featureSPN = false; - hoveredCard: NewsCard | null = null; - features$ = this.spn.watchEnabledFeatures() - .pipe(takeUntilDestroyed()); - trackCountry: TrackByFunction> = (_, ctr) => ctr.key; trackApp: TrackByFunction = (_, bp) => bp.profileID; @@ -214,13 +199,6 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { this.hoveredCard = card; } - openAccountDetails() { - this.dialog.create(SPNAccountDetailsComponent, { - autoclose: true, - backdrop: 'light' - }) - } - onCountryHover(code: string | null) { if (!this.mapRef) { return @@ -355,16 +333,6 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { groupBy: ['profile', 'country', 'active'], databases: [Database.Live], }, - - exitNodes: { - query: { tunneled: { $eq: true }, exit_node: { $ne: "" } }, - groupBy: ['exit_node'], - select: [ - 'exit_node', - { $count: { field: '*', as: 'totalCount' } } - ], - databases: [Database.Live], - } }) .pipe( repeat({ delay: 10000 }), @@ -411,7 +379,7 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { this.updateMapCountries() // perCountryConns - let profiles = new Set(); + const profiles = new Set(); this.activeConnections = 0; this.countriesPerProfile = {}; @@ -429,9 +397,6 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { }); this.activeProfiles = profiles.size; - - // exitNodes - this.activeIdentities = response.exitNodes?.length || 0; this.cdr.markForCheck(); }) @@ -459,49 +424,5 @@ export class DashboardPageComponent implements OnInit, AfterViewInit { this.bandwidthLineChart = bw; this.cdr.markForCheck(); }) - - this.netquery - .activeConnectionChart({ tunneled: { $eq: true } }) - .pipe( - repeat({ delay: 10000 }), - takeUntilDestroyed(this.destroyRef), - ) - .subscribe(result => { - this.tunneldConnectionChart = result; - this.cdr.markForCheck(); - }) - - // SPN profile and enabled/allowed features - - this.spn - .profile$ - .pipe( - takeUntilDestroyed(this.destroyRef) - ) - .subscribe({ - next: (profile) => { - this.profile = profile || null; - this.featureBw = profile?.current_plan?.feature_ids?.includes(FeatureID.Bandwidth) || false; - this.featureSPN = profile?.current_plan?.feature_ids?.includes(FeatureID.SPN) || false; - - // force a full change-detection cylce now! - this.cdr.detectChanges() - - // force re-draw of the charts after change-detection because the - // width may change now. - this.lineCharts?.forEach(chart => chart.redraw()) - - this.cdr.markForCheck(); - }, - }) - } - - /** Logs the user out of the SPN completely by purgin the user profile from the local storage */ - logoutCompletely(_: Event) { - this.spn.logout(true) - .subscribe(this.actionIndicator.httpObserver( - 'Logout', - 'You have been logged out of the SPN completely.' - )) } } diff --git a/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.html b/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.html deleted file mode 100644 index 0695555ef..000000000 --- a/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.html +++ /dev/null @@ -1,61 +0,0 @@ -
    - - - - - - - - - - - -
    - - - - {{ feature?.Name }} - - -
    -
    - -
    - - - - BETA -
    -
    -
    -
    - - {{ (disabled ? 'Available in ' : '') + 'Portmaster ' + feature?.InPackage?.Name}} - {{ comingSoon ? ' - coming soon' : '' }} - {{ feature?.Comment }} - -
    - -
    - -
    -
    - - Active - -
    - -
    - {{ feature?.InPackage?.Name }} - -
    -
    diff --git a/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.scss b/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.scss deleted file mode 100644 index 88f5fc61e..000000000 --- a/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.scss +++ /dev/null @@ -1,60 +0,0 @@ -.feature-card { - @apply flex flex-col p-4 bg-gray-300 rounded shadow w-full relative gap-2 overflow-hidden; - - .disabled-bg { - @apply absolute top-0 left-0 text-gray-500 opacity-50; - } - - &.disabled { - @apply opacity-80 shadow-inner; - } - - &.clickable { - @apply cursor-pointer; - &:hover { - @apply bg-gray-400; - } - } - - header { - @apply flex flex-row items-center justify-start gap-2 w-full; - - img { - @apply w-5 h-5; - filter: invert(1); - } - - &>span { - @apply text-base font-light; - } - } -} - -.ribbon { - width: 90px; - height: 100%; - overflow: hidden; - position: absolute; - top: 0px; - right: 0px; - z-index: 100; -} - -.ribbon__content { - left: -7px; - top: 25px; - -webkit-transform: rotate(45deg); - -ms-transform: rotate(45deg); - transform: rotate(45deg); - position: absolute; - display: block; - width: 125px; - padding: 2px 0; - text-shadow: 0 1px 0px rgba(0, 0, 0, .2); - text-transform: uppercase; - text-align: center; - border: 2px dotted #fff; - outline-color: #fff; - outline-width: 1px; - outline-style: solid; -} diff --git a/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.ts b/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.ts deleted file mode 100644 index 41f56591b..000000000 --- a/desktop/angular/src/app/pages/dashboard/feature-card/feature-card.component.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { coerceBooleanProperty } from '@angular/cdk/coercion'; -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy, SimpleChanges, inject } from '@angular/core'; -import { Router } from '@angular/router'; -import { BoolSetting, ConfigService, Feature } from '@safing/portmaster-api'; -import { Subscription } from 'rxjs'; -import { INTEGRATION_SERVICE } from 'src/app/integration'; - -@Component({ - selector: 'app-feature-card', - templateUrl: './feature-card.component.html', - styleUrls: ['./feature-card.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush -}) -export class FeatureCardComponent implements OnChanges, OnDestroy { - private readonly cdr = inject(ChangeDetectorRef); - private readonly configService = inject(ConfigService); - private readonly router = inject(Router); - private readonly integration = inject(INTEGRATION_SERVICE); - - private configValueSubscription = Subscription.EMPTY; - - @Input() - set disabled(v: any) { - this._disabled = coerceBooleanProperty(v) - } - get disabled() { return this._disabled } - _disabled = false; - - get comingSoon() { return this.feature?.ComingSoon || false } - - @Input() - feature?: Feature; - - planColor: string | null = null; - - configValue: boolean | undefined = undefined; - - ngOnChanges(changes: SimpleChanges): void { - if ('feature' in changes) { - this.configValueSubscription.unsubscribe(); - this.configValueSubscription = Subscription.EMPTY; - - if (!!this.feature?.ConfigKey) { - this.configValueSubscription = - this.configService.watch(this.feature!.ConfigKey) - .subscribe(value => { - this.configValue = value; - this.cdr.markForCheck(); - }); - } - - if (this.feature?.InPackage?.HexColor) { - this.planColor = getContrastFontColor(this.feature.InPackage.HexColor); - // console.log(this.feature.InPackage.HexColor, this.planColor) - this.cdr.markForCheck(); - } - } - } - - ngOnDestroy() { - this.configValueSubscription.unsubscribe(); - } - - updateSettingsValue(newValue: boolean) { - this.configService.save(this.feature!.ConfigKey, newValue) - .subscribe() - } - - navigateToConfigScope() { - if (this.disabled) { - this.integration.openExternal("https://safing.io/pricing?source=Portmaster") - return; - } - - let key: string | undefined; - if (this.feature?.ConfigKey) { - key = this.feature?.ConfigKey; - } else { - key = 'config:' + this.feature?.ConfigScope; - } - - if (!key) { - return - } - - - this.router.navigate(['/settings'], { - queryParams: { - setting: key, - } - }) - } -} - -function parseColor(input: string): number[] { - if (input.substr(0, 1) === '#') { - const collen = (input.length - 1) / 3; - const fact = [17, 1, 0.062272][collen - 1]; - return [ - Math.round(parseInt(input.substr(1, collen), 16) * fact), - Math.round(parseInt(input.substr(1 + collen, collen), 16) * fact), - Math.round(parseInt(input.substr(1 + 2 * collen, collen), 16) * fact), - ]; - } - - return input - .split('(')[1] - .split(')')[0] - .split(',') - .map((x) => +x); -} - -function getContrastFontColor(bgColor: string): string { - // if (red*0.299 + green*0.587 + blue*0.114) > 186 use #000000 else use #ffffff - // based on https://stackoverflow.com/a/3943023 - - let col = bgColor; - if (bgColor.startsWith('#') && bgColor.length > 7) { - col = bgColor.slice(0, 7); - } - const [r, g, b] = parseColor(col); - - if (r * 0.299 + g * 0.587 + b * 0.114 > 186) { - return '#000000'; - } - - return '#ffffff'; -} diff --git a/desktop/angular/src/app/pages/monitor/monitor.html b/desktop/angular/src/app/pages/monitor/monitor.html index 1d6fb177e..67a0995e7 100644 --- a/desktop/angular/src/app/pages/monitor/monitor.html +++ b/desktop/angular/src/app/pages/monitor/monitor.html @@ -24,12 +24,9 @@

    No network history data available. - + Enable - - Available in Portmaster Plus - diff --git a/desktop/angular/src/app/pages/monitor/monitor.ts b/desktop/angular/src/app/pages/monitor/monitor.ts index d6ce3374c..125a6eadb 100644 --- a/desktop/angular/src/app/pages/monitor/monitor.ts +++ b/desktop/angular/src/app/pages/monitor/monitor.ts @@ -1,6 +1,6 @@ import { Component, inject } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { BoolSetting, ConfigService, Database, FeatureID, Netquery, SPNService } from '@safing/portmaster-api'; +import { BoolSetting, ConfigService, Database, Netquery } from '@safing/portmaster-api'; import { Subject, interval, map, merge, repeat } from 'rxjs'; import { SessionDataService } from 'src/app/services'; import { ActionIndicatorService } from 'src/app/shared/action-indicator'; @@ -23,13 +23,6 @@ export class MonitorPageComponent { historyEnabled = inject(ConfigService) .watch('history/enable'); - canUseHistory = inject(SPNService).profile$ - .pipe( - map(profile => { - return profile?.current_plan?.feature_ids?.includes(FeatureID.History) || false; - }) - ); - history = inject(Netquery) .query({ select: [ diff --git a/desktop/angular/src/app/pages/settings/settings.html b/desktop/angular/src/app/pages/settings/settings.html index f85c752b8..3b35eee92 100644 --- a/desktop/angular/src/app/pages/settings/settings.html +++ b/desktop/angular/src/app/pages/settings/settings.html @@ -1,7 +1,7 @@
    - diff --git a/desktop/angular/src/app/pages/spn/country-details/country-details.html b/desktop/angular/src/app/pages/spn/country-details/country-details.html deleted file mode 100644 index f4e439637..000000000 --- a/desktop/angular/src/app/pages/spn/country-details/country-details.html +++ /dev/null @@ -1,154 +0,0 @@ -

    - - {{ countryName }} - - - - - -

    - - - - - - - - - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Total Nodes - {{ totalAliveCount }}
    - - - by Safing - - {{ safingNodeCount }}
    - - - by Community - - {{ communityNodeCount }}
    - Exit Nodes - {{ exitNodeCount }}
    - - - by Safing - - {{ safingExitNodeCount }}
    - - - by Community - - {{ communityExitNodeCount }}
    - Nodes In Use - {{ activeNodeCount }}
    - - - by Safing - - {{ activeSafingNodeCount }}
    - - - by Community - - {{ activeCommunityNodeCount }}
    -
    -
    - - - - -
    - The following Apps have connections that are routed through the - SPN and use an - exit node in {{ countryName }} ({{ countryCode }}): - - - - - - - - -
    - - {{ app.profile.Name }} - - {{ app.count }} connections - -
    -
    - - - - - - -
    - -
    - - - - -
    -
    -
    -
    -
    - -
    diff --git a/desktop/angular/src/app/pages/spn/country-details/country-details.ts b/desktop/angular/src/app/pages/spn/country-details/country-details.ts deleted file mode 100644 index 3fa34f1c7..000000000 --- a/desktop/angular/src/app/pages/spn/country-details/country-details.ts +++ /dev/null @@ -1,217 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Inject, Input, OnChanges, OnDestroy, OnInit, Optional, Output, SimpleChanges, TrackByFunction } from "@angular/core"; -import { AppProfile, AppProfileService, Netquery } from '@safing/portmaster-api'; -import { SFNG_DIALOG_REF, SfngDialogRef, SfngDialogService } from "@safing/ui"; -import { Subscription, forkJoin, of, switchMap } from 'rxjs'; -import { repeat } from 'rxjs/operators'; -import { MapPin, MapService } from './../map.service'; -import { PinDetailsComponent } from './../pin-details/pin-details'; - -@Component({ - templateUrl: './country-details.html', - changeDetection: ChangeDetectionStrategy.OnPush, - styles: [ - `:host{ - display: block; - min-width: 630px; - height: 400px; - overflow: hidden; - }` - ] -}) -export class CountryDetailsComponent implements OnInit, OnChanges, OnDestroy { - /** Subscription to poll map pins and profiles. */ - private subscription = Subscription.EMPTY; - - /** The two letter ISO country code */ - @Input() - countryCode: string = ''; - - /** The name of the country */ - @Input() - countryName: string = ''; - - /** Emits the ID of the pin that is hovered in the list. null if no pin is hovered */ - @Output() - pinHover = new EventEmitter(); - - /** @private - The list of pins available in this country */ - pins: MapPin[] = []; - - /** @private - A list of app profiles that use this country as an exit node */ - profiles: { profile: AppProfile, count: number }[] = []; - - /** @private - A {@link TrackByFunction} for all profiles that use this country for exit */ - trackProfile: TrackByFunction = (_: number, profile: this['profiles'][0]) => `${profile.profile.Source}/${profile.profile.ID}`; - - /** The number of alive nodes in this country */ - totalAliveCount = 0; - - /** The number of exit nodes in this country */ - exitNodeCount = 0; - - /** The number of active (used) nodes in this country */ - activeNodeCount = 0; - - /** The number of active (used) nodes operated by safing */ - activeSafingNodeCount = 0; - - /** The number of active (used) nodes operated by the community */ - activeCommunityNodeCount = 0; - - /** The number of nodes operated by safing */ - safingNodeCount = 0; - - /** The number of exit nodes operated by safing */ - safingExitNodeCount = 0; - - /** The number of nodes operated by a community member */ - communityNodeCount = 0; - - /** The number of exit ndoes operated by the community */ - communityExitNodeCount = 0; - - /** holds the text format of a netquery search to show all connections that exit in this country */ - filterConnectionsByCountryNodes = ''; - - constructor( - private mapService: MapService, - private netquery: Netquery, - private appService: AppProfileService, - private cdr: ChangeDetectorRef, - private dialog: SfngDialogService, - @Inject(SFNG_DIALOG_REF) @Optional() public dialogRef?: SfngDialogRef, - ) { } - - openPinDetails(id: string) { - this.dialog.create(PinDetailsComponent, { - data: id, - backdrop: false, - autoclose: true, - dragable: true, - }) - } - - ngOnInit() { - // if we got opened as a dialog we get the code and name of the country - // from the dialogRef.data field. - if (!!this.dialogRef) { - this.countryCode = this.dialogRef.data.code; - this.countryName = this.dialogRef.data.name; - } - - this.subscription.unsubscribe(); - - this.subscription = - this.mapService - .pins$ - .pipe( - switchMap(pins => { - // get a list of pins in that country - const countryPins = pins.filter(pin => pin.entity.Country === this.countryCode); - - // prepare a netquery query that loads the IDs of all profiles that use one of the countries - // pins as an exit node. Then, map those IDs to the actual app profile object - const profiles = this.netquery - .query({ - select: [ - 'profile', - { $count: { field: '*', as: 'totalCount' } } - ], - groupBy: ['profile'], - query: { - 'exit_node': { - $in: countryPins.map(pin => pin.pin.ID), - } - } - }, 'get-connections-per-profile-in-country') - .pipe( - switchMap(queryResult => { - if (queryResult.length === 0) { - return of([]); - } - - return forkJoin( - queryResult.map(row => forkJoin({ - profile: this.appService.getAppProfile(row.profile!), - count: of(row.totalCount), - }) - ) - ) - }), - ); - - return forkJoin({ - pins: of(countryPins), - profiles: profiles, - }) - } - ), - repeat({ - delay: 5000 - }), - ) - .subscribe(result => { - this.pins = result.pins; - this.profiles = result.profiles - - this.activeNodeCount = 0; - this.activeCommunityNodeCount = 0; - this.activeSafingNodeCount = 0; - this.exitNodeCount = 0; - this.safingNodeCount = 0; - this.communityNodeCount = 0; - this.safingExitNodeCount = 0; - this.communityExitNodeCount = 0; - - this.pins.forEach(pin => { - if (pin.isOffline) { - return - } - this.totalAliveCount++; - - if (pin.pin.VerifiedOwner === 'Safing') { - this.safingNodeCount++; - - if (pin.isExit) { - this.exitNodeCount++; - this.safingExitNodeCount++; - } - if (pin.isActive) { - this.activeSafingNodeCount++; - this.activeNodeCount++; - } - - } else { - this.communityNodeCount++; - - if (pin.isExit) { - this.exitNodeCount++; - this.communityExitNodeCount++; - } - if (pin.isActive) { - this.activeCommunityNodeCount++; - this.activeNodeCount++; - } - } - }) - - // create a netquery text-query in the format of "exit_node: exit_node: ..." - this.filterConnectionsByCountryNodes = this.pins.map(pin => `exit_node:${pin.pin.ID}`).join(" ") - - this.cdr.markForCheck(); - }) - } - - ngOnChanges(changes: SimpleChanges): void { - // if we are rendered as a regular component (not as a dialog) we need to - // handle updates to our @Inputs(). - // just let ngOnInit() do it's thing if the countryCode changed. - if (!!changes['countryCode']) { - this.ngOnInit(); - } - } - - ngOnDestroy() { - this.subscription.unsubscribe(); - } -} diff --git a/desktop/angular/src/app/pages/spn/country-details/index.ts b/desktop/angular/src/app/pages/spn/country-details/index.ts deleted file mode 100644 index 3ff2c6850..000000000 --- a/desktop/angular/src/app/pages/spn/country-details/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './country-details'; diff --git a/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.html b/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.html deleted file mode 100644 index 6ea2166f0..000000000 --- a/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - {{ countryName }} - - - - - - Safing Nodes: - {{ safingNodes.length }} - - - - - Community Nodes: - {{ communityNodes.length }} - - - - - Click country for details - - diff --git a/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.scss b/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.scss deleted file mode 100644 index be98030ce..000000000 --- a/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.scss +++ /dev/null @@ -1,40 +0,0 @@ -:host { - @apply flex flex-row items-center justify-center; -} - -.country-content-wrapper { - @apply flex flex-col gap-2 items-center justify-center bg-gray-200 border bg-opacity-50 border-gray-600 border-opacity-25; -} - -.country-name { - @apply text-sm flex flex-row gap-1 items-center justify-center bg-gray-100 bg-opacity-50 py-2 w-full; -} - -.country-stats { - @apply flex flex-col gap-2 items-start py-2 px-4; - - &>span { - @apply flex flex-row gap-1 items-center; - @apply text-xs font-light; - } - - .count { - @apply text-sm font-normal; - } -} - -.country-stats--safing { - svg polygon { - fill: #0376bb; - stroke: #0376bb; - transform: scale(1.15) - } -} - -.country-stats--community { - svg circle { - fill: #239215; - stroke: #239215; - transform: scale(1.15) - } -} diff --git a/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.ts b/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.ts deleted file mode 100644 index 2af05a268..000000000 --- a/desktop/angular/src/app/pages/spn/country-overlay/country-overlay.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core'; -import { BehaviorSubject, combineLatest, map } from 'rxjs'; -import { takeWhile } from 'rxjs/operators'; -import { MapPin, MapService } from './../map.service'; - -@Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'spn-map-country-overlay', - templateUrl: './country-overlay.html', - changeDetection: ChangeDetectionStrategy.OnPush, - styleUrls: [ - './country-overlay.scss' - ] -}) -export class CountryOverlayComponent implements OnInit, OnChanges, OnDestroy { - /** The two-letter ISO code of the country */ - @Input() - countryCode!: string; - - /** The (english) name of the country */ - @Input() - countryName!: string; - - /** all nodes in this country operated by Safing */ - safingNodes: MapPin[] = []; - - /** all nodes in this country operated by a community member */ - communityNodes: MapPin[] = []; - - /** used to trigger a reload onChanges */ - private reload$ = new BehaviorSubject(undefined); - - constructor( - private mapService: MapService, - private cdr: ChangeDetectorRef, - ) { } - - ngOnChanges(changes: SimpleChanges): void { - this.reload$.next(); - } - - ngOnInit(): void { - combineLatest([ - this.mapService.pins$, - this.reload$ - ]) - .pipe( - takeWhile(() => !this.reload$.closed), - map(([pins]) => pins.filter(pin => pin.entity.Country === this.countryCode)), - ) - .subscribe(pinsInCountry => { - this.safingNodes = []; - this.communityNodes = []; - - pinsInCountry.forEach(pin => { - if (pin.isOffline && !pin.isActive) { - return - } - - if (pin.pin.VerifiedOwner === 'Safing') { - this.safingNodes.push(pin) - } else { - this.communityNodes.push(pin) - } - }) - - this.cdr.markForCheck(); - }) - } - - ngOnDestroy(): void { - this.reload$.complete(); - } -} - diff --git a/desktop/angular/src/app/pages/spn/country-overlay/index.ts b/desktop/angular/src/app/pages/spn/country-overlay/index.ts deleted file mode 100644 index 2e61e978d..000000000 --- a/desktop/angular/src/app/pages/spn/country-overlay/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './country-overlay'; diff --git a/desktop/angular/src/app/pages/spn/index.ts b/desktop/angular/src/app/pages/spn/index.ts deleted file mode 100644 index cc24eeea3..000000000 --- a/desktop/angular/src/app/pages/spn/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './spn-page'; diff --git a/desktop/angular/src/app/pages/spn/map-legend/index.ts b/desktop/angular/src/app/pages/spn/map-legend/index.ts deleted file mode 100644 index 111ec8c05..000000000 --- a/desktop/angular/src/app/pages/spn/map-legend/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './map-legend'; diff --git a/desktop/angular/src/app/pages/spn/map-legend/map-legend.html b/desktop/angular/src/app/pages/spn/map-legend/map-legend.html deleted file mode 100644 index 07cf2a9b4..000000000 --- a/desktop/angular/src/app/pages/spn/map-legend/map-legend.html +++ /dev/null @@ -1,54 +0,0 @@ -
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - Safing Nodes - {{ safingNodeCount }}
    - - - used as Transit - - {{ safingActiveCount }}
    - - - used as Exit - - {{ safingExitCount }}
    - - Community Nodes - {{ communityNodeCount }}
    - - - used as Transit - - {{ communityActiveCount }}
    - - - used as Exit - - {{ communityExitCount }}
    -
    diff --git a/desktop/angular/src/app/pages/spn/map-legend/map-legend.ts b/desktop/angular/src/app/pages/spn/map-legend/map-legend.ts deleted file mode 100644 index e561111e0..000000000 --- a/desktop/angular/src/app/pages/spn/map-legend/map-legend.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from "@angular/core"; -import { Subscription } from 'rxjs'; -import { MapService } from './../map.service'; - -@Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'spn-map-legend', - templateUrl: './map-legend.html', - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class SpnMapLegendComponent implements OnInit, OnDestroy { - private subscription = Subscription.EMPTY; - - safingNodeCount = 0; - safingExitCount = 0; - safingActiveCount = 0; - - communityNodeCount = 0; - communityExitCount = 0; - communityActiveCount = 0; - - constructor( - private mapService: MapService, - private cdr: ChangeDetectorRef, - ) { } - - ngOnInit() { - this.subscription = this.mapService - .pins$ - .subscribe(pins => { - this.safingActiveCount = 0; - this.safingExitCount = 0; - this.safingNodeCount = 0; - this.communityActiveCount = 0; - this.communityExitCount = 0; - this.communityNodeCount = 0; - - pins.forEach(pin => { - if (pin.pin.VerifiedOwner === 'Safing') { - if (pin.isActive) { - this.safingActiveCount++; - } - - if (pin.isExit) { - this.safingExitCount++ - } - - this.safingNodeCount++ - } else { - if (pin.isActive) { - this.communityActiveCount++; - } - - if (pin.isExit) { - this.communityExitCount++; - } - - this.communityNodeCount++; - } - }) - - this.cdr.markForCheck(); - }) - } - - ngOnDestroy() { - this.subscription.unsubscribe(); - } -} diff --git a/desktop/angular/src/app/pages/spn/map-renderer/map-style.scss b/desktop/angular/src/app/pages/spn/map-renderer/map-style.scss deleted file mode 100644 index 0f319ba73..000000000 --- a/desktop/angular/src/app/pages/spn/map-renderer/map-style.scss +++ /dev/null @@ -1,167 +0,0 @@ -::ng-deep { - .pin { - opacity: 0; - - &.in-view { - opacity: 1; - } - } -} - -::ng-deep #spn-map { - --map-bg: #111112; - --map-country-active: #424141; - --map-country-inactive: #2a2a2a; - --map-country-border-width: 2px; - --map-country-border-color: #1e1e1e; - --map-country-border-color-selected: #858585; - --map-country-blocked-primary: #858585; - --map-country-blocked-secondary: #402323; - - .overlay { - fill: none; - pointer-events: all; - } - - g { - - circle, - polygon { - fill: #626262; - stroke: #626262; - stroke-width: 1; - stroke-linejoin: round; - transition: all 200ms linear 0s; - } - - circle:hover, - polygon:hover { - fill: theme('colors.yellow.200'); - stroke: theme('colors.yellow.300'); - stroke-width: 2; - } - } - - g[in-use=true] { - circle { - fill: #239215; - stroke: #239215; - transform: scale(1.15) - } - - polygon { - fill: #0376bb; - stroke: #0376bb; - transform: scale(1.15) - } - } - - g[is-exit=true] { - - circle, - polygon { - transform: scale(1.3); - stroke-width: 2; - } - - polygon { - stroke: #039af4; - fill: #0376bb; - } - - circle { - stroke: #30ae20; - fill: #239215; - } - } - - g[is-home=true] circle { - stroke: white; - stroke-width: 4.5; - fill: black; - transform: scale(1); - } - - g[raise=true] { - - circle, - polygon { - fill: theme('colors.yellow.200'); - stroke: theme('colors.yellow.300'); - stroke-width: 2; - transform: scale(1.8); - } - } - - .marker { - cursor: pointer; - fill: #252525; - stroke: rgba(151, 151, 151, 0.8); - transition: all 250ms 0s cubic-bezier(0.175, 0.885, 0.32, 1.275); - } - - .marker-label { - fill: white; - } - - path.lane { - stroke: rgba(151, 151, 151, 0.2); - fill: transparent; - - &[in-use=true] { - stroke-width: 2; - stroke: #0376bb; - } - - &[is-live=true] { - stroke-width: 1; - stroke: theme('colors.red.300'); - - &[is-encrypted=true] { - stroke: theme('colors.green.200'); - } - - &:hover { - stroke-width: 3; - } - } - } - - #world-group { - path { - fill: var(--map-country-border-color); - stroke: var(--map-country-border-color); - stroke-width: var(--map-country-border-width); - stroke-linejoin: round; - } - - path[has-nodes=true] { - fill: var(--map-country-inactive); - } - - path[in-use=true] { - fill: var(--map-country-active); - } - - path:hover { - cursor: pointer; - fill: var(--map-country-active); - } - - path.selected { - stroke: var(--map-country-border-color-selected); - } - } -} - -:host-context(.disabled) { - @apply bg-white; - - #world-group { - path { - fill: #000000; - stroke: #111111; - stroke-width: .5px; - } - } -} diff --git a/desktop/angular/src/app/pages/spn/map.service.ts b/desktop/angular/src/app/pages/spn/map.service.ts deleted file mode 100644 index b8c0a65ae..000000000 --- a/desktop/angular/src/app/pages/spn/map.service.ts +++ /dev/null @@ -1,250 +0,0 @@ -import { Injectable } from '@angular/core'; -import { AppProfile, GeoCoordinates, IntelEntity, Netquery, Pin, SPNService, UnknownLocation, getPinCoords } from '@safing/portmaster-api'; -import { BehaviorSubject, Observable, combineLatest, debounceTime, interval, of, startWith, switchMap } from 'rxjs'; -import { distinctUntilChanged, filter, map, share } from 'rxjs/operators'; -import { SPNStatus } from './../../../../projects/safing/portmaster-api/src/lib/spn.types'; - -export interface MapPin { - pin: Pin; - // location is set to the geo-coordinates that should be used - // for that pin. - location: GeoCoordinates; - // entity is set to the intel entity that should be used for - // this pin. - entity: IntelEntity; - - // whether the pin is regarded as offline / not available. - isOffline: boolean; - - // whether or not the pin is currently used as an exit node - isExit: boolean; - - // whether or not the pin is used as a transit node - isTransit: boolean; - - // whether or not the pin is currently active. - isActive: boolean; - - // whether or not the pin is used as the entry-node. - isHome: boolean; - - // whether the pin has any known issues - hasIssues: boolean; -} - -@Injectable({ providedIn: 'root' }) -export class MapService { - /** - * activeSince$ emits the pre-formatted duration since the SPN is active - * it formats the duration as "HH:MM:SS" or null if the SPN is not enabled. - */ - activeSince$: Observable; - - /** Emits the current status of the SPN */ - status$: Observable; - - /** Emits all map pins */ - _pins$ = new BehaviorSubject([]); - - get pins$(): Observable { - return this._pins$.asObservable(); - } - - pinsMap$ = this.pins$ - .pipe( - filter(allPins => !!allPins.length), - map(allPins => { - const lm = new Map(); - allPins.forEach(pin => lm.set(pin.pin.ID, pin)); - - return lm - }), - share(), - ) - - constructor( - private spnService: SPNService, - private netquery: Netquery, - ) { - this.status$ = this.spnService - .status$ - .pipe( - map(status => !!status ? status.Status : 'disabled'), - distinctUntilChanged() - ); - - // setup the activeSince$ observable that emits every second how long the - // SPN has been active. - this.activeSince$ = combineLatest([ - this.spnService.status$, - interval(1000).pipe(startWith(-1)) - ]).pipe( - map(([status]) => !!status.ConnectedSince ? this.formatActiveSinceDate(status.ConnectedSince) : null), - share(), - ); - - let pinMap = new Map(); - let pinResult: MapPin[] = []; - - // create a stream of pin updates from the SPN service if it is enabled. - this.status$ - .pipe( - switchMap(status => { - if (status !== 'disabled') { - return combineLatest([ - this.spnService.watchPins(), - interval(5000) - .pipe( - startWith(-1), - switchMap(() => this.getPinIDsUsedAsExit()) - ) - ]) - } - return of([[], []]); - }), - map(([pins, exitPinIDs]) => { - const exitPins = new Set(exitPinIDs); - const activePins = new Set(); - const transitPins = new Set(); - const seenPinIDs = new Set(); - - let hasChanges = false; - - pins.forEach(pin => pin.Route?.forEach((hop, index) => { - if (index < pin.Route!.length - 1) { - transitPins.add(hop) - } - - activePins.add(hop); - })); - - pins.forEach(pin => { - // Save Pin ID as seen. - seenPinIDs.add(pin.ID); - - const oldPinModel = pinMap.get(pin.ID); - - // Get states of new model. - const isOffline = pin.States.includes('Offline') || !pin.States.includes('Reachable'); - const isHome = pin.HopDistance === 1; - const isTransit = transitPins.has(pin.ID); - - const isExit = exitPins.has(pin.ID); - const isActive = activePins.has(pin.ID); - const hasIssues = pin.States.includes('ConnectivityIssues'); - - const pinHasChanged = !oldPinModel || oldPinModel.pin !== pin || - oldPinModel.isOffline !== isOffline || oldPinModel.isHome !== isHome || oldPinModel.isTransit !== isTransit || - oldPinModel.isExit !== isExit || oldPinModel.isActive !== isActive || oldPinModel.hasIssues !== hasIssues; - - if (pinHasChanged) { - const newPinModel: MapPin = { - pin: pin, - location: getPinCoords(pin) || UnknownLocation, - entity: (pin.EntityV4 || pin.EntityV6)!, - isExit, - isTransit, - isActive, - isOffline, - isHome, - hasIssues, - } - - pinMap.set(pin.ID, newPinModel); - - hasChanges = true; - } - }) - - for (let key of pinMap.keys()) { - if (!seenPinIDs.has(key)) { - // this pin has been removed - pinMap.delete(key) - hasChanges = true; - } - } - - if (hasChanges) { - pinResult = Array.from(pinMap.values()); - } - - return pinResult; - }), - debounceTime(10), - distinctUntilChanged(), - ) - .subscribe(pins => this._pins$.next(pins)) - } - - getExitPinIDsForProfile(profile: AppProfile) { - return this.netquery - .query({ - select: ['exit_node'], - groupBy: ['exit_node'], - query: { - profile: { $eq: `${profile.Source}/${profile.ID}` }, - } - }, 'map-service-get-exit-pin-ids-for-profile') - .pipe(map(result => result.map(row => row.exit_node!))) - } - - getPinIDsWithActiveSession() { - return this.pins$ - .pipe( - map(result => result.filter(pin => pin.pin.SessionActive).map(pin => pin.pin.ID)) - ) - } - - getPinIDsUsedAsExit() { - return this.netquery - .query({ - select: ['exit_node'], - groupBy: ['exit_node'] - }, 'map-service-get-pins-used-as-exit') - .pipe( - map(result => result.map(row => row.exit_node!)) - ) - } - - getPinIDsWithActiveConnections() { - return this.netquery.query({ - select: ['exit_node'], - groupBy: ['exit_node'], - query: { - active: { $eq: true } - } - }, 'map-service-get-pins-with-connections') - .pipe( - map(activeExitNodes => { - const pins = this._pins$.getValue(); - - const pinIDs = new Set(); - const pinLookupMap = new Map(); - - pins.forEach(p => pinLookupMap.set(p.pin.ID, p)) - - activeExitNodes.map(row => { - const pin = pinLookupMap.get(row.exit_node!); - if (!!pin) { - pin.pin.Route?.forEach(hop => { - pinIDs.add(hop) - }) - } - }) - - return Array.from(pinIDs); - }) - ) - } - - private formatActiveSinceDate(date: string): string { - const d = new Date(date); - const diff = Math.floor((new Date().getTime() - d.getTime()) / 1000); - const hours = Math.floor(diff / 3600); - const minutes = Math.floor((diff - (hours * 3600)) / 60); - const secs = diff - (hours * 3600) - (minutes * 60); - const pad = (d: number) => d < 10 ? `0${d}` : '' + d; - - return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`; - } -} diff --git a/desktop/angular/src/app/pages/spn/node-icon/index.ts b/desktop/angular/src/app/pages/spn/node-icon/index.ts deleted file mode 100644 index 715f271da..000000000 --- a/desktop/angular/src/app/pages/spn/node-icon/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './node-icon'; diff --git a/desktop/angular/src/app/pages/spn/node-icon/node-icon.html b/desktop/angular/src/app/pages/spn/node-icon/node-icon.html deleted file mode 100644 index faf8c6847..000000000 --- a/desktop/angular/src/app/pages/spn/node-icon/node-icon.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - diff --git a/desktop/angular/src/app/pages/spn/node-icon/node-icon.scss b/desktop/angular/src/app/pages/spn/node-icon/node-icon.scss deleted file mode 100644 index b62c9bac5..000000000 --- a/desktop/angular/src/app/pages/spn/node-icon/node-icon.scss +++ /dev/null @@ -1,38 +0,0 @@ -svg { - - circle, - polygon { - fill: #626262; - stroke: #626262; - stroke-width: 1; - stroke-linejoin: round; - transition: all 200ms linear 0s; - } - - polygon.active, - polygon.exit { - fill: #0376bb; - stroke: #0376bb; - transform: scale(1.15) - } - - circle.active, - circle.exit { - fill: #239215; - stroke: #239215; - transform: scale(1.15) - } - - circle.exit, - polygon.exit { - stroke-width: 2; - } - - circle.exit { - stroke: #30ae20; - } - - polygon.exit { - stroke: #039af4; - } -} diff --git a/desktop/angular/src/app/pages/spn/node-icon/node-icon.ts b/desktop/angular/src/app/pages/spn/node-icon/node-icon.ts deleted file mode 100644 index daad9a153..000000000 --- a/desktop/angular/src/app/pages/spn/node-icon/node-icon.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { coerceBooleanProperty } from '@angular/cdk/coercion'; -import { ChangeDetectionStrategy, Component, Input } from "@angular/core"; - -@Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'spn-node-icon', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './node-icon.html', - styleUrls: ['./node-icon.scss'], -}) -export class SpnNodeIconComponent { - @Input() - set bySafing(v: any) { - this._bySafing = coerceBooleanProperty(v); - } - get bySafing() { return this._bySafing } - private _bySafing = false; - - @Input() - set isActive(v: any) { - this._isActive = coerceBooleanProperty(v); - } - get isActive() { return this._isActive } - private _isActive = false; - - @Input() - set isExit(v: any) { - this._isExit = coerceBooleanProperty(v); - } - get isExit() { return this._isExit; } - private _isExit = false; - - get nodeClass() { - if (this._isExit) { - return 'exit'; - } - - if (this.isActive) { - return 'active' - } - - return ''; - } -} diff --git a/desktop/angular/src/app/pages/spn/pin-details/index.ts b/desktop/angular/src/app/pages/spn/pin-details/index.ts deleted file mode 100644 index 9a9851da5..000000000 --- a/desktop/angular/src/app/pages/spn/pin-details/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './pin-details'; diff --git a/desktop/angular/src/app/pages/spn/pin-details/pin-details.html b/desktop/angular/src/app/pages/spn/pin-details/pin-details.html deleted file mode 100644 index 8e53befc6..000000000 --- a/desktop/angular/src/app/pages/spn/pin-details/pin-details.html +++ /dev/null @@ -1,127 +0,0 @@ -

    - - {{ pin?.pin?.Name || 'N/A' }} - - - - -

    - - - This SPN Node is run by - - - - {{ pin.pin.VerifiedOwner || 'Community' }} - - -
    - Node is Offline -
    -
    - Node has Issues -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ID{{ pin.pin.ID }}
    Verified Owner -
    {{ pin.pin.VerifiedOwner }}
    -
    First Seen{{ pin.pin.FirstSeen | date:'medium' }}
    IPv4 -
    - - - {{ entity.ASOrg }} - ({{ entity.ASN }}) - - - {{ entity.IP || 'N/A' }} - -
    -
    IPv6 -
    - - - {{ entity.ASOrg }} - ({{ entity.ASN }}) - - - {{ entity.IP || 'N/A' }} - -
    -
    States -
    {{ pin.pin.States.join(", ") }}
    -
    SessionActive -
    {{ pin.pin.SessionActive }}
    -
    HopDistance -
    {{ pin.pin.HopDistance }}
    -
    Exit Connections -
    -
    {{ exitConnectionCount }}
    - - - - - - -
    -
    -
    - - -
    - -
    -
    - - - - - -
    diff --git a/desktop/angular/src/app/pages/spn/pin-details/pin-details.ts b/desktop/angular/src/app/pages/spn/pin-details/pin-details.ts deleted file mode 100644 index f7e83faeb..000000000 --- a/desktop/angular/src/app/pages/spn/pin-details/pin-details.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, Input, OnChanges, OnDestroy, OnInit, Optional, SimpleChanges } from '@angular/core'; -import { Netquery } from '@safing/portmaster-api'; -import { SFNG_DIALOG_REF, SfngDialogRef } from '@safing/ui'; -import { Subscription, forkJoin, map, of, switchMap } from 'rxjs'; -import { LaneModel } from '../pin-list/pin-list'; -import { MapPin, MapService } from './../map.service'; - -@Component({ - templateUrl: './pin-details.html', - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class PinDetailsComponent implements OnInit, OnChanges, OnDestroy { - private subscription = Subscription.EMPTY; - - @Input() - mapPinID!: string; - - pin: MapPin | null = null; - - /** Holds all pins this pin has a active connection to */ - connectedPins: LaneModel[] = []; - - /** The number of connections that exit at this pin */ - exitConnectionCount: number = 0; - - constructor( - private mapService: MapService, - private netquery: Netquery, - private cdr: ChangeDetectorRef, - @Optional() @Inject(SFNG_DIALOG_REF) public dialogRef?: SfngDialogRef, - ) { } - - ngOnInit(): void { - // if we got opened via a dialog we get the map pin ID from the dialog data. - if (!!this.dialogRef) { - this.mapPinID = this.dialogRef.data; - } - - this.subscription.unsubscribe(); - - this.subscription = this.mapService - .pins$ - .pipe( - map(pins => { - return [pins.find(p => p.pin.ID === this.mapPinID), pins] as [MapPin, MapPin[]]; - }), - switchMap(([pin, allPins]) => forkJoin({ - pin: of(pin), - allPins: of(allPins), - exitConnections: this.netquery.query({ - select: [ - { $count: { field: '*', as: 'totalCount', } }, - ], - query: { - exit_node: pin.pin.ID, - }, - groupBy: ['exit_node'] - }, 'pin-details-get-connections-per-exit-node') - })) - ) - .subscribe((result) => { - this.pin = result.pin || null; - - const lm = new Map(); - result.allPins.forEach(pin => lm.set(pin.pin.ID, pin)) - - const connectedTo = this.pin?.pin.ConnectedTo || {}; - this.connectedPins = Object.keys(connectedTo) - .map(pinID => { - const pin = lm.get(pinID)!; - return { - ...connectedTo[pinID], - mapPin: pin, - } - }); - - if (result.exitConnections.length) { - // we expect only one row to be returned for the above query. - this.exitConnectionCount = result.exitConnections[0].totalCount; - } else { - this.exitConnectionCount = 0; - } - - this.cdr.markForCheck(); - }) - } - - ngOnChanges(changes: SimpleChanges) { - // if we got rendered directly (without a dialog) we need to - // handle updates to the mapPinID input field by re-loading the - // pin details. We do that by simply re-running ngOnInit - if (!!changes['mapPinID']) { - this.ngOnInit() - } - } - - ngOnDestroy(): void { - this.subscription.unsubscribe(); - } -} diff --git a/desktop/angular/src/app/pages/spn/pin-list/index.ts b/desktop/angular/src/app/pages/spn/pin-list/index.ts deleted file mode 100644 index e69de29bb..000000000 diff --git a/desktop/angular/src/app/pages/spn/pin-list/pin-list.html b/desktop/angular/src/app/pages/spn/pin-list/pin-list.html deleted file mode 100644 index b21077e4e..000000000 --- a/desktop/angular/src/app/pages/spn/pin-list/pin-list.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameOperatorUsed AsLatencyCapacityIPv4IPv6
    - - - {{ pin.pin.Name }} - -
    - - - - - {{ pin.pin.VerifiedOwner || 'Community' }} - -
    -
    -
    - - - - - - - - - - - - - - - - - -
    -
    - {{ val.Latency / 1000 / 1000 | number:'1.0-2' }} ms - - {{ val.Capacity / 1000 / 1000 | number:'1.0-2' }} Mbit/s - {{ pin.pin.EntityV4?.IP || 'N/A' }}{{ pin.pin.EntityV6?.IP || 'N/A' }} - - - -
    diff --git a/desktop/angular/src/app/pages/spn/pin-list/pin-list.ts b/desktop/angular/src/app/pages/spn/pin-list/pin-list.ts deleted file mode 100644 index 6f3eeedfd..000000000 --- a/desktop/angular/src/app/pages/spn/pin-list/pin-list.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { coerceBooleanProperty } from '@angular/cdk/coercion'; -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, Output, TrackByFunction } from '@angular/core'; -import { Lane } from '@safing/portmaster-api'; -import { take } from 'rxjs/operators'; -import { MapPin } from '../map.service'; -import { MapService } from './../map.service'; - -export interface LaneModel extends Lane { - mapPin: MapPin; -} - -@Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'spn-pin-list', - templateUrl: './pin-list.html', - changeDetection: ChangeDetectionStrategy.OnPush -}) -export class SpnPinListComponent { - @Input() - set allowHover(v: any) { - this._allowHover = coerceBooleanProperty(v); - } - get allowHover() { return this._allowHover } - private _allowHover = true; - - @Input() - set allowClick(v: any) { - this._allowClick = coerceBooleanProperty(v); - } - get allowClick() { return this._allowClick } - private _allowClick = true; - - @Input() - set pins(pins: (string | MapPin | LaneModel)[]) { - this.mapService - .pinsMap$ - .pipe(take(1)) - .subscribe(allPins => { - this.lanes = null; - - this._pins = (pins || []).map(idOrPin => { - if (typeof idOrPin === 'string') { - return allPins.get(idOrPin)!; - } - - if ('mapPin' in idOrPin) { // LaneModel - if (this.lanes === null) { - this.lanes = new Map(); - } - - this.lanes.set(idOrPin.HubID, { - Capacity: idOrPin.Capacity, - Latency: idOrPin.Latency, - }) - - return idOrPin.mapPin; - } - - return idOrPin; // MapPin - }) - - this.cdr.markForCheck(); - }) - } - get pins(): MapPin[] { - return this._pins; - } - private _pins: MapPin[] = []; - - /** If we got LaneModel in @Input() pins than this will contain a map with the capacity/latency */ - lanes: Map> | null = null; - - /** Emits the ID of the pin that got hovered, null if the mouse left a pin */ - @Output() - pinHover = new EventEmitter(); - - @Output() - pinClick = new EventEmitter(); - - /** @private - A {@link TrackByFunction} for all pins available in this country */ - trackPin: TrackByFunction = (_: number, pin: MapPin) => pin.pin.ID; - - constructor( - private mapService: MapService, - private cdr: ChangeDetectorRef - ) { } -} diff --git a/desktop/angular/src/app/pages/spn/pin-overlay/index.ts b/desktop/angular/src/app/pages/spn/pin-overlay/index.ts deleted file mode 100644 index 620c76d30..000000000 --- a/desktop/angular/src/app/pages/spn/pin-overlay/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './pin-overlay'; diff --git a/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.html b/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.html deleted file mode 100644 index 4bcd2f4c9..000000000 --- a/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.html +++ /dev/null @@ -1,117 +0,0 @@ -
    -
    - - Show Details - Show exit connections - Copy Node ID - - - - - {{ mapPin.pin.Name }} - - - - - - - - - - - - - - - - - - -
    -
    - IPv4 - {{ mapPin.pin.EntityV4?.IP || 'N/A' }} -
    -
    - IPv6 - {{ mapPin.pin.EntityV6?.IP || 'N/A' }} -
    -
    - Run By - - - - - - - {{ mapPin.pin.VerifiedOwner || 'Community' }} - -
    -
    - Used As - -
    - - - - - - - Home Node - - - - - - - - - - Exit Node - - - - - - - - - - Transit Node - - - - -
    -
    -
    - - - - - - - - - diff --git a/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.scss b/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.scss deleted file mode 100644 index 68c4ea1fb..000000000 --- a/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.scss +++ /dev/null @@ -1,4 +0,0 @@ -:host { - min-width: 220px; - display: block; -} diff --git a/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.ts b/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.ts deleted file mode 100644 index 00122703d..000000000 --- a/desktop/angular/src/app/pages/spn/pin-overlay/pin-overlay.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { AnimationEvent, animate, keyframes, style, transition, trigger } from '@angular/animations'; -import { CdkDrag, CdkDragHandle, CdkDragRelease } from '@angular/cdk/drag-drop'; -import { Overlay, OverlayRef, PositionStrategy } from '@angular/cdk/overlay'; -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, HostListener, Inject, Input, OnInit, Output, ViewChild, inject } from '@angular/core'; -import { Router } from '@angular/router'; -import { SfngDialogService } from '@safing/ui'; -import { PinDetailsComponent } from '../pin-details'; -import { MapOverlay, Path } from '../spn-page'; -import { ActionIndicatorService } from './../../../shared/action-indicator/action-indicator.service'; -import { MapPin } from './../map.service'; -import { OVERLAY_REF } from './../utils'; -import { INTEGRATION_SERVICE } from 'src/app/integration'; - -export interface PinOverlayHoverEvent { - type: 'enter' | 'leave'; - pinID: string; -} - -@Component({ - templateUrl: './pin-overlay.html', - styleUrls: [ - './pin-overlay.scss' - ], - changeDetection: ChangeDetectionStrategy.OnPush, - animations: [ - trigger('moveIn', [ - transition(':enter', [ - style({ transform: 'scale(0)', transformOrigin: 'top left' }), - animate('200ms {{ delay }}ms cubic-bezier(0, 0, 0.2, 1)', - keyframes([ - style({ transform: 'scaleX(1) scaleY(0.1)', transformOrigin: 'top left', offset: 0.3 }), - style({ transform: 'scaleX(1) scaleY(1)', transformOrigin: 'top left', offset: 0.8 }), - ]) - ) - ], { params: { delay: "0" } }), - transition(':leave', [ - style({ transform: 'scale(1)', opacity: 1, transformOrigin: 'top left' }), - animate('500ms cubic-bezier(0, 0, 0.2, 1)', - keyframes([ - style({ transform: 'scaleX(1) scaleY(0.1)', opacity: 0.5, transformOrigin: 'top left', offset: 0.3 }), - style({ transform: 'scaleX(0) scaleY(0)', opacity: 0, transformOrigin: 'top left', offset: 0.8 }), - ]) - ) - ]) - ]) - ] -}) -export class PinOverlayComponent implements OnInit { - private readonly integration = inject(INTEGRATION_SERVICE); - - @Input() - mapPin!: MapPin; - - @Input() - routeHome?: Path; - - @Input() - additionalPaths?: Path[] = []; - - @Input() - delay: number = 0; - - @Output() - afterDispose = new EventEmitter(); - - @Output() - overlayHover = new EventEmitter(); - - @ViewChild(CdkDrag) - dragContainer!: CdkDrag; - - @ViewChild(CdkDragHandle) - dragHandle!: CdkDragHandle; - - showContent = false; - - /** Indicates whether or not the pin overlay has been moved by the user */ - hasBeenMoved = false; - - private oldPositionStrategy?: PositionStrategy; - - @HostListener('mouseenter') - onHostElementMouseEnter(event: MouseEvent) { - this.overlayHover.next({ - type: 'enter', - pinID: this.mapPin.pin.ID - }) - - this.containerClass = ''; - } - - @HostListener('mouseleave') - onHostElementMouseLeave(event: MouseEvent) { - this.overlayHover.next({ - type: 'leave', - pinID: this.mapPin.pin.ID - }) - - this.containerClass = 'bg-opacity-90' - } - - /** on double-click, restore the old pin overlay position (before being initialy dragged by the user) */ - onDragDblClick() { - if (!!this.oldPositionStrategy) { - this.overlayRef.updatePositionStrategy(this.oldPositionStrategy); - this.overlayRef.updatePosition(); - this.hasBeenMoved = false; - } - } - - onDragStart() { - this.containerClass = 'outline' - } - - openPinDetails() { - this.dialog.create(PinDetailsComponent, { - data: this.mapPin.pin.ID, - autoclose: true, - backdrop: false, - dragable: true, - }) - } - - onDragRelease(event: CdkDragRelease) { - if (!this.dragContainer || !this.overlayRef.hostElement || !this.overlayRef.hostElement.parentElement) { - return; - } - - const bbox = this.dragContainer.element.nativeElement.getBoundingClientRect(); - const parent = this.overlayRef.hostElement.parentElement!.getBoundingClientRect(); - - if (!this.oldPositionStrategy) { - this.oldPositionStrategy = this.overlayRef.getConfig().positionStrategy; - } - - this.containerClass = ''; - - this.dragContainer.reset() - - this.overlayRef.updatePositionStrategy( - this.overlay.position() - .global() - .top((bbox.top - parent.top) + 'px') - .left((bbox.left - parent.left) + 'px') - ); - - this.hasBeenMoved = true; - } - - onAnimationComplete(event: AnimationEvent) { - if (event.toState === 'void') { - this.afterDispose.next(this.mapPin.pin.ID) - this.overlayRef.dispose(); - } - } - - containerClass = ''; - - constructor( - @Inject(OVERLAY_REF) public readonly overlayRef: OverlayRef, - @Inject(MapOverlay) public overlay: Overlay, - private dialog: SfngDialogService, - private actionIndicator: ActionIndicatorService, - private router: Router, - private cdr: ChangeDetectorRef, - ) { } - - ngOnInit(): void { - this.showContent = true; - this.cdr.markForCheck(); - } - - disposeOverlay() { - this.showContent = false; - this.cdr.markForCheck(); - } - - showExitConnections() { - this.router.navigate(['/monitor'], { - queryParams: { - q: 'exit_node:' + this.mapPin.pin.ID - } - }) - } - - async copyNodeID() { - await this.integration.writeToClipboard(this.mapPin?.pin.ID) - this.actionIndicator.success("Copied to Clipboard") - } -} diff --git a/desktop/angular/src/app/pages/spn/pin-route/index.ts b/desktop/angular/src/app/pages/spn/pin-route/index.ts deleted file mode 100644 index f97ea758e..000000000 --- a/desktop/angular/src/app/pages/spn/pin-route/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './pin-route'; diff --git a/desktop/angular/src/app/pages/spn/pin-route/pin-route.html b/desktop/angular/src/app/pages/spn/pin-route/pin-route.html deleted file mode 100644 index 1927c5cdf..000000000 --- a/desktop/angular/src/app/pages/spn/pin-route/pin-route.html +++ /dev/null @@ -1,53 +0,0 @@ - -
    - -
    -
      -
    • - - - - - Your Device - -
    • - -
    • - - - - - - {{ node.entity.Country || 'No Location' }} - {{ node.entity.IP || '' - }} - Home - Exit -
      {{ node.pin.Name }} - - - by - - {{ node.pin.VerifiedOwner || 'Community' }} - -
      - -
      AS{{ node.entity.ASN }} - {{ node.entity.ASOrg || - 'AS Organization not in DB' - }}
      - -
      {{ node.pin.ID }}
      -
    • - -
    • - - - - - - Destination - - -
    • -
    -
    diff --git a/desktop/angular/src/app/pages/spn/pin-route/pin-route.scss b/desktop/angular/src/app/pages/spn/pin-route/pin-route.scss deleted file mode 100644 index 2c66a8ee1..000000000 --- a/desktop/angular/src/app/pages/spn/pin-route/pin-route.scss +++ /dev/null @@ -1,67 +0,0 @@ -.tunnel-path { - position: relative; - - .line { - position: absolute; - top: 10px; - bottom: 10px; - left: 8px; - width: 1px; - background-color: rgba(255, 255, 255, 0.1); - } - - .node-tag { - border-radius: 1px solid rgba(255, 255, 255, 0.2); - background-color: rgba(255, 255, 255, 0.1); - padding: 2px; - font-size: 85%; - border-radius: 2px; - transform: scale(0.85); - display: inline-block; - } - - ul { - position: relative; - padding-left: 20px; - - li:not(:last-of-type) { - padding-bottom: 0.35rem; - } - - .ip { - margin-left: 0.35rem; - } - - .hop-icon { - display: inline-block; - margin-left: -17px; - margin-right: 4px; - font-weight: 400; - - &.country { - margin-left: -20px; - } - } - - .hop-title { - margin-right: 2px; - } - - .country { - display: inline-block; - margin-left: -20px; - margin-right: 4px; - - &.unknown { - height: 14px; - width: 16px; - position: relative; - top: 3px; - border: 1px solid rgba(0, 0, 0, 0.25); - opacity: 0.5; - border-radius: 3px; - @apply bg-buttons-icon; - } - } - } -} diff --git a/desktop/angular/src/app/pages/spn/pin-route/pin-route.ts b/desktop/angular/src/app/pages/spn/pin-route/pin-route.ts deleted file mode 100644 index d862619de..000000000 --- a/desktop/angular/src/app/pages/spn/pin-route/pin-route.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input } from "@angular/core"; -import { TunnelNode } from "@safing/portmaster-api"; -import { take } from 'rxjs'; -import { MapPin, MapService } from './../map.service'; - -@Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'sfng-spn-pin-route', - templateUrl: './pin-route.html', - styleUrls: ['./pin-route.scss'], - changeDetection: ChangeDetectionStrategy.OnPush -}) -export class SpnPinRouteComponent { - @Input() - set route(path: (string | MapPin | TunnelNode)[] | null) { - this.mapService - .pinsMap$ - .pipe( - take(1), - ) - .subscribe(lm => { - this._route = (path || []).map(idOrPin => { - if (typeof idOrPin === 'string') { - return lm.get(idOrPin)!; - } - - if ('ID' in idOrPin) { // TunnelNode - return lm.get(idOrPin.ID)! - } - - return idOrPin; - }); - - this.cdr.markForCheck(); - }) - } - get route(): MapPin[] { - return this._route - } - private _route: MapPin[] = []; - - constructor( - private mapService: MapService, - private cdr: ChangeDetectorRef, - ) { } -} diff --git a/desktop/angular/src/app/pages/spn/spn-feature-carousel/index.ts b/desktop/angular/src/app/pages/spn/spn-feature-carousel/index.ts deleted file mode 100644 index d07cc9e10..000000000 --- a/desktop/angular/src/app/pages/spn/spn-feature-carousel/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './spn-feature-carousel'; diff --git a/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.html b/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.html deleted file mode 100644 index b73683f42..000000000 --- a/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.html +++ /dev/null @@ -1,274 +0,0 @@ -
    - - - - - - -
    -
    -

    Get - Multiple Identities for Each App

    - - Automatically get a vast amount of identities (IP addresses). The SPN calculates an individual path for - every - connection through the privacy network. Spread your connections across the globe, without any effort. - -
    - -
    -
    - - - - -
    -
    -

    Easily Adjust Your Privacy

    - - SPN just works and does the heavy lifting for you. But of course you can easily configure the settings, so - it fits your needs: Exclude certain apps and domains from the SPN. Or never exit in specific countries. And - so much more... - -
    - -
    -
    - - -
    -
    -

    Built from Scratch, for Your Privacy

    - - SPN is built from the ground up. Privacy is cooked right into it. Inspired by Tor, it comes with onion - routing and state of the art encryption. Fully open source so all our claims can be validated. - -
    - -
    -
    - - -
    -
    -

    Bye Bye, VPNs

    - - VPN technology was NOT built for user privacy, but for company security. Because of that, you can only trust - a VPN provider's policy - and many have been caught abusing user data. Honestly, the best way forward: just - stop paying for outdated technology. - -
    - -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - Most VPNs -
    - Read Comparison Blog -
    -
    SPNTor
    Multiple Identities (simultaneous) - - - - - -
    Individual Apps Settings - - - - - -
    Easy Setup - - - - Browser Only
    Availabilty -
    - - - - -
    -
    -
    - - -
    -
    -
    - - - - -
    -
    Open Source - - - - - -
    Built for Privacy - - - - - -
    -
    -
    -
    - - - - - -
    - -
    - -
    diff --git a/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.scss b/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.scss deleted file mode 100644 index 7ffa92a2b..000000000 --- a/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.scss +++ /dev/null @@ -1,62 +0,0 @@ -:host { - @apply flex flex-col gap-2 justify-center items-center relative; -} - -section { - @apply flex flex-row items-start gap-4 justify-evenly text-background; - - &.reverse { - @apply flex-row-reverse - } - - &>div { - @apply flex flex-col w-1/3 gap-6; - - span { - @apply text-base break-normal text-background text-opacity-80; - } - - h1, - h1>span { - @apply text-2xl font-semibold break-normal md:text-3xl lg:text-4xl xl:text-5xl text-background; - - } - - h1>span { - &.text-blue { - color: theme('colors.blue.DEFAULT') !important; - } - } - } - - img { - position: relative; - max-width: 50%; - } - - table { - @apply mb-12; - - th { - @apply text-base; - } - - td { - @apply text-center p-2 leading-6; - } - - tr>td:first-of-type { - @apply text-left p-2 font-semibold text-base whitespace-nowrap; - } - } -} - -::ng-deep { - spn-feature-carousel { - sfng-tab-outlet { - &>div { - overflow: visible !important; - } - } - } -} diff --git a/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.ts b/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.ts deleted file mode 100644 index e68edbb3a..000000000 --- a/desktop/angular/src/app/pages/spn/spn-feature-carousel/spn-feature-carousel.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, HostListener, OnDestroy, QueryList, ViewChild, ViewChildren } from "@angular/core"; -import { SfngTabComponent, SfngTabGroupComponent } from '@safing/ui'; -import { filter, interval, startWith, Subscription } from 'rxjs'; - -@Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'spn-feature-carousel', - changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl: './spn-feature-carousel.html', - styleUrls: [ - './spn-feature-carousel.scss' - ] -}) -export class SPNFeatureCarouselComponent implements AfterViewInit, OnDestroy { - private sub: Subscription = Subscription.EMPTY; - - pause = false; - currentIndex = -1; - - @HostListener('mouseenter') - onMouseEnter() { - this.pause = true - } - - @HostListener('mouseleave') - onMouseLeave() { - this.pause = false; - } - - /** A list of all carousel templates */ - @ViewChildren(SfngTabComponent) - carousel!: QueryList; - - @ViewChild(SfngTabGroupComponent) - tabGroup!: SfngTabGroupComponent; - - constructor( - private cdr: ChangeDetectorRef - ) { } - - ngAfterViewInit(): void { - this.sub = interval(5000) - .pipe( - startWith(-1), - filter(() => !this.pause), - ) - .subscribe(() => { - this.openTab(this.currentIndex + 1, 'left') - }) - } - - ngOnDestroy(): void { - this.sub.unsubscribe() - } - - openTab(idx: number, direction?: 'left' | 'right') { - // force animation to circle if we go before the first - // or after the last one. - if (idx < 0) { - idx = this.carousel.length - 1; - direction = 'right' - } - if (idx >= this.carousel.length) { - direction = 'left' - } - - this.currentIndex = idx % this.carousel.length; - this.tabGroup.activateTab(this.currentIndex, direction)!; - this.cdr.markForCheck(); - } - - showNext() { - this.sub.unsubscribe() - - this.openTab(this.currentIndex + 1) - } - - showPrev() { - this.sub.unsubscribe() - - this.openTab(this.currentIndex - 1) - } -} diff --git a/desktop/angular/src/app/pages/spn/spn-page.html b/desktop/angular/src/app/pages/spn/spn-page.html deleted file mode 100644 index 28a61450d..000000000 --- a/desktop/angular/src/app/pages/spn/spn-page.html +++ /dev/null @@ -1,102 +0,0 @@ - -
    -
    - -
    - - Loading data, please wait ... -
    -
    -
    - -
    - - - -
    - - -
    - -
    - - - - - - - -
    - - - - Pro Tip: - -
    - - -
    -
    - - - - Hold -
    CTRL
    key and click a node on the map to immediately open the node details dialog. -
    - - - Hold -
    SHIFT
    key to open more than one node overlay when clicking the node icon. -
    - - - To keep node overlays open move them using - - - . Double click to revert the overlay position on the map. - - - - Click on a country to get more information about all nodes in that country and a list of Apps that use nodes in the - country as an identity. - -
    diff --git a/desktop/angular/src/app/pages/spn/spn-page.scss b/desktop/angular/src/app/pages/spn/spn-page.scss deleted file mode 100644 index 40441ef47..000000000 --- a/desktop/angular/src/app/pages/spn/spn-page.scss +++ /dev/null @@ -1,143 +0,0 @@ -:host { - @apply flex flex-row w-full h-full justify-items-stretch items-stretch relative; -} - -.text-info-red { - color: theme("colors.info.red"); -} - -.network-status-dialog { - width: 50vw; - height: 50vh; - min-height: 300px; - min-width: 400px; - padding: 12px; - overflow: auto; - display: flex; - flex-direction: column; - - .issue { - flex-grow: 1; - } - - .issue-list { - width: 100% !important; - flex-grow: 1; - - ul { - overflow: auto; - } - } - - .issue.expanded { - background-color: var(--button-light) !important; - } - - .body { - background-color: var(--cards-primary) !important; - } -} - -.connect-button { - - &.spn-connected { - @apply bg-info-blue; - } - - &.spn-connecting { - @apply bg-info-blue; - } - - &.spn-failed { - @apply bg-info-red; - } - - &:hover { - @apply bg-info-blue opacity-75; - } -} - -.table { - @apply w-full font-normal; - - &>div { - @apply text-xs border-buttons-dark flex flex-row justify-between py-1; - - &:not(:last-child) { - @apply border-b; - } - - span:first-child { - @apply text-tertiary; - } - - span:last-child { - @apply text-primary; - } - } -} - - -table tr:nth-child(odd) { - background: none; -} - - -.tunnel-path { - position: relative; - - .line { - position: absolute; - top: 10px; - bottom: 10px; - left: 8px; - width: 1px; - background-color: rgba(255, 255, 255, 0.1); - } - - - ul { - position: relative; - padding-left: 20px; - - li:not(:last-of-type) { - padding-bottom: 0.35rem; - } - - .ip { - margin-left: 0.35rem; - } - - .hop-icon { - display: inline-block; - margin-left: -17px; - margin-right: 4px; - font-weight: 400; - - &.country { - margin-left: -20px; - } - } - - .hop-title { - margin-right: 2px; - } - - .country { - display: inline-block; - margin-left: -20px; - margin-right: 4px; - - &.unknown { - height: 14px; - width: 16px; - position: relative; - top: 3px; - border: 1px solid rgba(0, 0, 0, 0.25); - opacity: 0.5; - border-radius: 3px; - @apply bg-buttons-icon; - } - } - } -} diff --git a/desktop/angular/src/app/pages/spn/spn-page.ts b/desktop/angular/src/app/pages/spn/spn-page.ts deleted file mode 100644 index 992dbe192..000000000 --- a/desktop/angular/src/app/pages/spn/spn-page.ts +++ /dev/null @@ -1,1012 +0,0 @@ -import { coerceElement } from "@angular/cdk/coercion"; -import { Overlay, OverlayContainer } from "@angular/cdk/overlay"; -import { ComponentPortal } from '@angular/cdk/portal'; -import { HttpClient } from '@angular/common/http'; -import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, DestroyRef, ElementRef, Inject, Injectable, InjectionToken, Injector, OnDestroy, OnInit, QueryList, TemplateRef, ViewChild, ViewChildren, forwardRef, inject } from "@angular/core"; -import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { ActivatedRoute, ParamMap, Router } from "@angular/router"; -import { AppProfile, ConfigService, Connection, ExpertiseLevel, FeatureID, Netquery, PORTMASTER_HTTP_API_ENDPOINT, PortapiService, SPNService, SPNStatus, UserProfile } from "@safing/portmaster-api"; -import { SfngDialogService } from "@safing/ui"; -import { Line as D3Line, Selection, interpolateString, line, select } from 'd3'; -import { BehaviorSubject, Observable, Subscription, combineLatest, interval, of } from "rxjs"; -import { catchError, debounceTime, map, mergeMap, share, startWith, switchMap, take, takeUntil, withLatestFrom } from "rxjs/operators"; -import { fadeInAnimation, fadeInListAnimation, fadeOutAnimation } from "src/app/shared/animations"; -import { ExpertiseService } from "src/app/shared/expertise/expertise.service"; -import { SPNAccountDetailsComponent } from "src/app/shared/spn-account-details"; -import { CountryDetailsComponent } from "./country-details"; -import { CountryEvent, MAP_HANDLER, MapRef, MapRendererComponent } from "./map-renderer/map-renderer"; -import { MapPin, MapService } from "./map.service"; -import { PinDetailsComponent } from "./pin-details"; -import { PinOverlayComponent } from "./pin-overlay"; -import { OVERLAY_REF } from './utils'; - -export const MapOverlay = new InjectionToken('MAP_OVERLAY') - -export type PinGroup = Selection; -export type LaneGroup = Selection; - -export interface Path { - id: string; - points: (MapPin | [number, number])[]; - attributes?: { - [key: string]: string; - } -} - -export interface PinEvent { - event?: MouseEvent; - mapPin: MapPin; -} - - -/** - * A custom class that implements the OverlayContainer interface of CDK. This - * is used so we can configure a custom container element that will hold all overlays created - * by the map component. This way the overlays will be bound to the map container and not overflow - * the sidebar or other overlays that are created by the "root" app. - */ -@Injectable() -class MapOverlayContainer { - private _overlayContainer?: HTMLElement; - - setOverlayContainer(element: ElementRef | HTMLElement) { - this._overlayContainer = coerceElement(element); - } - - getContainerElement(): HTMLElement { - if (!this._overlayContainer) { - throw new Error("Overlay container element not initialized. Call setOverlayContainer first.") - } - - return this._overlayContainer; - } -} - -@Component({ - templateUrl: './spn-page.html', - styleUrls: ['./spn-page.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - providers: [ - MapOverlayContainer, - { provide: MapOverlay, useClass: Overlay }, - { provide: OverlayContainer, useExisting: MapOverlayContainer }, - { provide: MAP_HANDLER, useExisting: forwardRef(() => SpnPageComponent), multi: true } - ], - animations: [ - fadeInListAnimation, - fadeInAnimation, - fadeOutAnimation - ] -}) -export class SpnPageComponent implements OnInit, OnDestroy, AfterViewInit { - private destroyRef = inject(DestroyRef); - - private countryDebounceTimer: any | null = null; - - /** a list of opened country details. required to close them on destry */ - private openedCountryDetails: CountryDetailsComponent[] = []; - - readonly featureID = FeatureID.SPN; - - paths: Path[] = []; - - @ViewChild('overlayContainer', { static: true, read: ElementRef }) - overlayContainer!: ElementRef; - - @ViewChild(MapRendererComponent, { static: true }) - mapRenderer!: MapRendererComponent; - - @ViewChild('accountDetails', { read: TemplateRef, static: true }) - accountDetails: TemplateRef | null = null; - - /** A list of pro-tip templates in our view */ - @ViewChildren('proTip', { read: TemplateRef }) - proTipTemplates!: QueryList>; - - /** The selected pro-tip template */ - proTipTemplate: TemplateRef | null = null; - - /** currentUser holds the current SPN user profile if any */ - currentUser: UserProfile | null = null; - - /** An observable that emits all active processes. */ - activeProfiles$: Observable; - - /** Whether or not we are still waiting for all data in order to satisfy a "show process/pin" request by query-params */ - loading = true; - - /** a list of currently selected pins */ - selectedPins: PinOverlayComponent[] = []; - - /** the currently hovered country, if any */ - hoveredCountry: { - countryName: string; - countryCode: string; - } | null = null; - - liveMode = false; - liveModePaths: Path[] = []; - - private liveModeSubscription = Subscription.EMPTY; - - /** - * spnStatusTranslation translates the spn status to the text that is displayed - * at the view - */ - readonly spnStatusTranslation: Readonly> = { - connected: 'Connected', - connecting: 'Connecting', - disabled: 'Disabled', - failed: 'Failure' - } - - - private mapRef: MapRef | null = null; - private lineFunc: D3Line<(MapPin | [number, number])> | null = null; - private highlightedPins = new Set(); - - registerMap(ref: MapRef) { - this.mapRef = ref; - - ref.onMapReady(() => { - // we want to have straight lines between our hubs so we use a custom - // path function that updates x and y coordinates based on the mercator projection - // without, points will no be at the correct geo-coordinates. - this.lineFunc = line() - .x(d => { - if (Array.isArray(d)) { - return this.mapRef!.projection([d[0], d[1]])![0]; - } - return this.mapRef!.projection([d.location.Longitude, d.location.Latitude])![0]; - }) - .y(d => { - if (Array.isArray(d)) { - return this.mapRef!.projection([d[0], d[1]])![1]; - } - return this.mapRef!.projection([d.location.Longitude, d.location.Latitude])![1]; - }) - - this.mapRef!.root.append('g').attr('id', 'line-group') - this.mapRef!.root.append('g').attr('id', 'pin-group') - - if (this.mapService._pins$.getValue().length > 0) { - this.renderPins(this.mapService._pins$.getValue()) - } - }) - - ref.onCountryClick(event => this.onCountryClick(event)) - ref.onCountryHover(event => this.onCountryHover(event)) - ref.onZoomPan(() => this.onZoomAndPan()) - } - - unregisterMap(ref: MapRef) { - this.mapRef = null; - this.lineFunc = null; - } - - constructor( - private configService: ConfigService, - private spnService: SPNService, - private netquery: Netquery, - private expertiseService: ExpertiseService, - private router: Router, - private route: ActivatedRoute, - private portapi: PortapiService, - @Inject(PORTMASTER_HTTP_API_ENDPOINT) private httpAPI: string, - private http: HttpClient, - public mapService: MapService, - @Inject(MapOverlay) private mapOverlay: Overlay, - private dialog: SfngDialogService, - private overlayContainerService: MapOverlayContainer, - private cdr: ChangeDetectorRef, - private injector: Injector, - ) { - this.activeProfiles$ = interval(5000) - .pipe( - startWith(-1), - switchMap(() => this.netquery.getActiveProfiles()), - share({ connector: () => new BehaviorSubject([]) }) - ) - } - - ngAfterViewInit() { - // configure our custom overlay container - this.overlayContainerService.setOverlayContainer(this.overlayContainer); - - // Select a random "Pro-Tip" template and run change detection - this.proTipTemplate = this.proTipTemplates.get(Math.floor(Math.random() * this.proTipTemplates.length)) || null; - this.cdr.detectChanges(); - } - - openAccountDetails() { - this.dialog.create(SPNAccountDetailsComponent, { - autoclose: true, - backdrop: 'light' - }) - } - - ngOnInit() { - this.spnService - .profile$ - .pipe( - takeUntilDestroyed(this.destroyRef), - catchError(() => of(null)) - ) - .subscribe((user: UserProfile | null) => { - if (user?.state !== '') { - this.currentUser = user || null; - } else { - this.currentUser = null; - } - - this.cdr.markForCheck(); - }) - - let previousQueryMap: ParamMap | null = null; - - combineLatest([ - this.route.queryParamMap, - this.mapService.pins$, - this.activeProfiles$, - ]) - .pipe( - takeUntilDestroyed(this.destroyRef), - ).subscribe(([params, pins, profiles]) => { - if (params !== previousQueryMap) { - const app = params.get("app") - if (!!app) { - const profile = profiles.find(p => `${p.Source}/${p.ID}` === app); - if (!!profile) { - const pinID = params.get("pin") - const pin = pins.find(p => p.pin.ID === pinID); - - this.selectGroup(profile, pin) - } - } - - previousQueryMap = params; - } - - this.renderPins(pins); - - // we're done with everything now. - this.loading = false; - }) - - } - - toggleLiveMode(enabled: boolean) { - this.liveMode = enabled; - - if (!enabled) { - this.liveModeSubscription.unsubscribe(); - this.liveModePaths = []; - this.updatePaths([]); - this.cdr.markForCheck(); - - return; - } - - this.liveModeSubscription = this.portapi.watchAll("network:tree") - .pipe( - withLatestFrom(this.mapService.pinsMap$), - takeUntilDestroyed(this.destroyRef), - debounceTime(100), - ) - .subscribe(([connections, mapPins]) => { - connections = connections.filter(conn => conn.Ended === 0 && !!conn.TunnelContext); - - this.liveModePaths = connections.map(conn => { - const points: (MapPin | [number, number])[] = conn.TunnelContext!.Path.map(hop => mapPins.get(hop.ID)!) - - if (!!conn.Entity.Coordinates) { - points.push([conn.Entity.Coordinates.Longitude, conn.Entity.Coordinates.Latitude]) - } - - return { - id: conn.Entity.Domain || conn.ID, - points: points, - attributes: { - 'is-live': 'true', - 'is-encrypted': `${conn.Encrypted}` - } - } - }) - - this.updatePaths([]) - this.cdr.markForCheck(); - }) - } - - /** - * Toggle the spn/enable setting. This does NOT update the view as that - * will happen as soon as we get an update from the db qsub. - * - * @private - template only - */ - toggleSPN() { - this.configService.get('spn/enable') - .pipe( - map(setting => setting.Value ?? setting.DefaultValue), - mergeMap(active => this.configService.save('spn/enable', !active)) - ) - .subscribe() - } - - /** - * Select one or more pins by ID. If shift key is hold then all currently - * selected pin overlays will be cleared before selecting the new ones. - */ - private selectPins(event: MouseEvent | undefined, pinIDs: Observable) { - combineLatest([ - this.mapService.pins$, - pinIDs, - ]) - .pipe(take(1)) - .subscribe(([allPins, pinIDs]) => { - if (event?.shiftKey !== true) { - this.selectedPins - .filter(overlay => !overlay.hasBeenMoved) - .forEach(selected => selected.disposeOverlay()) - } - - pinIDs - .filter(id => !this.selectedPins.find(selectedPin => selectedPin.mapPin.pin.ID === id)) - .map(id => allPins.find(pin => pin.pin.ID === id)) - .filter(mapPin => !!mapPin) - .forEach(mapPin => this.onPinClick({ - mapPin: mapPin!, - })); - }) - } - - /** - * Select all pins that are used for transit. - * - * @private - template only - */ - selectTransitNodes(event: MouseEvent) { - this.selectPins(event, this.mapService.getPinIDsWithActiveSession()) - } - - /** - * Select all pins that are used as an exit hub. - * - * @private - template only - */ - selectExitNodes(event: MouseEvent) { - this.selectPins(event, this.mapService.getPinIDsUsedAsExit()) - } - - /** - * Select all pins that currently host alive connections. - * - * @private - template only - */ - selectNodesWithAliveConnections(event: MouseEvent) { - this.selectPins(event, this.mapService.getPinIDsWithActiveConnections()) - } - - navigateToMonitor(process: AppProfile) { - this.router.navigate(['/app', process.Source, process.ID]) - } - - ngOnDestroy() { - this.openedCountryDetails.forEach(cmp => cmp.dialogRef!.close()); - } - - onZoomAndPan() { - this.updateOverlayPositions(); - - if (this.mapRef) { - this.mapRef.root - .select('#lines-group') - .selectAll('path') - .attr('d', d => this.lineFunc!(d.points)) - - this.mapRef.root - .select("#pin-group") - .selectAll('g') - .attr('transform', d => `translate(${this.mapRef!.projection([d.location.Longitude, d.location.Latitude])})`) - } - - this.cdr.markForCheck(); - } - - private createPinOverlay(pinEvent: PinEvent, lm: Map): PinOverlayComponent { - const paths = this.getRouteHome(pinEvent.mapPin, lm, false) - const overlayBoundingRect = this.overlayContainer.nativeElement.getBoundingClientRect(); - const target = pinEvent.event?.target || this.getPinElem(pinEvent.mapPin.pin.ID)?.children[0]; - let delay = 0; - if (paths.length > 0) { - delay = paths[0].points.length * MapRendererComponent.LineAnimationDuration; - } - - const overlayRef = this.mapOverlay.create({ - positionStrategy: this.mapOverlay.position() - .flexibleConnectedTo(new ElementRef(target)) - .withDefaultOffsetY(-overlayBoundingRect.y - 10) - .withDefaultOffsetX(-overlayBoundingRect.x + 20) - .withPositions([ - { - overlayX: 'start', - overlayY: 'top', - originX: 'start', - originY: 'top' - } - ]), - scrollStrategy: this.mapOverlay.scrollStrategies.reposition(), - }) - - const injector = Injector.create({ - providers: [ - { - provide: OVERLAY_REF, - useValue: overlayRef, - } - ], - parent: this.injector - }) - - - const pinOverlay = overlayRef.attach( - new ComponentPortal(PinOverlayComponent, undefined, injector) - ).instance; - - pinOverlay.delay = delay; - pinOverlay.mapPin = pinEvent.mapPin; - if (paths.length > 0) { - pinOverlay.routeHome = { - ...(paths[0]), - } - pinOverlay.additionalPaths = paths.slice(1); - } - - return pinOverlay; - } - - - private openPinDetails(id: string) { - this.dialog.create(PinDetailsComponent, { - data: id, - backdrop: false, - autoclose: true, - dragable: true, - }) - } - - private openCountryDetails(event: CountryEvent) { - // abort if we already have the country details open. - if (this.openedCountryDetails.find(cmp => cmp.countryCode === event.countryCode)) { - return; - } - - const ref = this.dialog.create(CountryDetailsComponent, { - data: { - name: event.countryName, - code: event.countryCode, - }, - autoclose: false, - dragable: true, - backdrop: false, - }) - const component = (ref.contentRef() as ComponentRef).instance; - - // used to track whether we highlighted a map pin - let hasPinHighlightActive = false; - - combineLatest([ - component.pinHover, - this.mapService.pins$, - ]) - .pipe( - takeUntil(ref.onClose), - ) - .subscribe(([hovered, pins]) => { - hasPinHighlightActive = hovered !== null; - - if (hovered !== null) { - this.onPinHover({ - mapPin: pins.find(p => p.pin.ID === hovered)!, - }) - this.highlightPin(hovered, true) - } else { - this.onPinHover(null); - this.clearPinHighlights(); - } - - - this.cdr.markForCheck(); - }) - - ref.onClose - .subscribe(() => { - if (hasPinHighlightActive) { - this.clearPinHighlights(); - } - - const index = this.openedCountryDetails.findIndex(cmp => cmp === component); - if (index >= 0) { - this.openedCountryDetails.splice(index, 1); - } - }) - - this.openedCountryDetails.push(component); - } - - private updateOverlayPositions() { - this.mapService.pinsMap$ - .pipe(take(1)) - .subscribe(allPins => { - this.selectedPins.forEach(pin => { - const pinObj = allPins.get(pin.mapPin.pin.ID); - if (!pinObj) { - return; - } - - pin.overlayRef.updatePosition(); - }) - }) - } - - onCountryClick(countryEvent: CountryEvent) { - this.openCountryDetails(countryEvent); - } - - onCountryHover(countryEvent: CountryEvent | null) { - if (this.countryDebounceTimer !== null) { - clearTimeout(this.countryDebounceTimer); - } - - if (!!countryEvent) { - this.hoveredCountry = { - countryCode: countryEvent.countryCode, - countryName: countryEvent.countryName, - } - this.cdr.markForCheck(); - - return; - } - - this.countryDebounceTimer = setTimeout(() => { - this.hoveredCountry = null; - this.countryDebounceTimer = null; - this.cdr.markForCheck(); - }, 200) - } - - onPinClick(pinEvent: PinEvent) { - // if the control key hold when clicking a map pin, we immediately open the - // pin details instead of the overlay. - if (pinEvent.event?.ctrlKey) { - this.openPinDetails(pinEvent.mapPin.pin.ID); - } - - const overlay = this.selectedPins.find(por => por.mapPin.pin.ID === pinEvent.mapPin.pin.ID); - if (!!overlay) { - overlay.disposeOverlay() - return; - } - - // if shiftKey was not pressed during the pinClick we dispose all active overlays that have not been - // moved by the user - if (!pinEvent.event?.shiftKey) { - this.selectedPins - .filter(overlay => !overlay.hasBeenMoved) - .forEach(selected => selected.disposeOverlay()) - } - - this.mapService.pinsMap$ - .pipe(take(1)) - .subscribe(async lm => { - const overlayComp = this.createPinOverlay(pinEvent, lm); - - // when the user wants to dispose a pin overlay (by clicking the X) we - // - make sure the pin is not highlighted anymore - // - remove the pin from the selectedPins list - // - remove lines showing the route to the home hub - overlayComp.afterDispose - .subscribe(pinID => { - this.highlightPin(pinID, false); - - const overlayIdx = this.selectedPins.findIndex(por => por.mapPin.pin.ID === pinEvent.mapPin.pin.ID); - this.selectedPins.splice(overlayIdx, 1) - - this.updatePaths() - this.cdr.markForCheck(); - }) - - // when the user hovers/leaves a pin overlay, we: - // - move the pin-overlay to the top when the user hovers it so stacking order is correct - // - (un)hightlight the pin element on the map - overlayComp.overlayHover - .subscribe(evt => { - this.highlightPin(evt.pinID, evt.type === 'enter') - - // over the overlay component to the top - if (evt.type === 'enter') { - this.selectedPins.forEach(ref => { - if (ref !== overlayComp && ref.overlayRef.hostElement) { - ref.overlayRef.hostElement.style.zIndex = '0'; - } - }) - - overlayComp.overlayRef.hostElement.style.zIndex = ''; - } - }) - - this.selectedPins.push(overlayComp) - - this.updatePaths([]); - this.cdr.markForCheck(); - }) - } - - private updatePaths(additional: Path[] = []) { - const paths = [ - ...(this.selectedPins - .reduce((list, pin) => { - if (pin.routeHome) { - list.push(pin.routeHome) - } - - return [ - ...list, - ...(pin.additionalPaths || []) - ] - }, [] as Path[])), - ...this.liveModePaths, - ...additional - ] - - this.paths = paths.map(p => { - return { - ...p, - attributes: { - class: 'lane', - ...(p.attributes || {}) - } - } - }); - - this.renderPaths(this.paths) - } - - onPinHover(pinEvent: PinEvent | null) { - if (!pinEvent) { - this.updatePaths([]); - this.onCountryHover(null); - - return; - } - - // we also emit a country hover event here to keep the country - // overlay open. - const countryName = this.mapRenderer.countryNames[pinEvent.mapPin.entity.Country] - this.onCountryHover({ - event: pinEvent.event, - countryCode: pinEvent.mapPin.entity.Country, - countryName: countryName!, - }) - - // in developer mode, we show all connected lanes of the hovered pin. - if (this.expertiseService.currentLevel === ExpertiseLevel.Developer) { - this.mapService.pinsMap$ - .pipe(take(1)) - .subscribe(lm => { - const lanes = this.getConnectedLanes(pinEvent?.mapPin, lm) - this.updatePaths(lanes); - this.cdr.markForCheck(); - }) - } - } - - /** - * Marks a process group as selected and either selects one or all exit pins - * of that group. If shiftKey is pressed during click, the ID(s) will be added - * to the list of selected pins instead of replacing it. If shiftKey is pressed - * the process group itself will NOT be displayed as selected. - * - * @private - template only - */ - selectGroup(grp: AppProfile, pin?: MapPin | null, event?: MouseEvent) { - if (!!pin) { - this.selectPins(event, of([pin.pin.ID])) - return; - } - - this.selectPins(event, this.mapService.getExitPinIDsForProfile(grp)) - } - - /** Returns a list of lines that represent the route from pin to home. */ - private getRouteHome(pin: MapPin, lm: Map, includeAllRoutes = false): Path[] { - let pinsToEval: MapPin[] = [pin]; - - // decide whether to draw all connection routes that travel through pin. - if (includeAllRoutes) { - pinsToEval = [ - ...pinsToEval, - ...Array.from(lm.values()) - .filter(p => p.pin.Route?.includes(pin.pin.ID)) - ] - } - - return pinsToEval.map(pin => ({ - id: `route-home-from-${pin.pin.ID}`, - points: (pin.pin.Route || []).map(hop => lm.get(hop)!), - attributes: { - 'in-use': 'true' - } - })); - } - - /** Returns a list of lines the represent all lanes to connected pins of pin */ - private getConnectedLanes(pin: MapPin, lm: Map): Path[] { - let result: Path[] = []; - - // add all lanes for connected hubs - Object.keys(pin.pin.ConnectedTo).forEach(target => { - const p = lm.get(target); - if (!!p) { - result.push({ - id: lineID([pin, p]), - points: [ - pin, - p - ] - }) - } - }); - - return result; - - } - - private async renderPaths(paths: Path[]) { - if (!this.mapRef) { - return; - } - - const ref = this.mapRef! - - const linesGroup: LaneGroup = this.mapRef.select("#line-group")! - - const self = this; - const renderedPaths = linesGroup.selectAll('path') - .data(paths, p => p.id); - - renderedPaths - .enter() - .append('path') - .attr('d', path => { - return self.lineFunc!(path.points) - }) - .attr("stroke-width", d => { - if (d.attributes) { - if (d.attributes['in-use']) { - return 2 / ref.zoomScale - } - } - - return 1 / ref.zoomScale; - }) - .call(sel => { - if (sel.empty()) { - return; - } - const data = sel.datum()?.attributes || {}; - Object.keys(data) - .forEach(key => { - sel.attr(key, data[key]) - }) - }) - .transition("enter-lane") - .duration(d => d.points.length * MapRendererComponent.LineAnimationDuration) - .attrTween('stroke-dasharray', tweenDashEnter) - - renderedPaths.exit() - .interrupt("enter-lane") - .transition("leave-lane") - .duration(200) - .attrTween('stroke-dasharray', tweenDashExit) - .remove(); - } - - private async renderPins(pins: MapPin[]) { - pins = pins.filter(pin => !pin.isOffline || pin.isActive); - - if (!this.mapRef) { - return - } - - const ref = this.mapRef!; - - const countriesWithNodes = new Set(); - - pins.forEach(pin => { - countriesWithNodes.add(pin.entity.Country) - }) - - const pinsGroup = ref.select('#pin-group')! - - const pinElements = pinsGroup - .selectAll('g') - .data(pins, pin => pin.pin.ID) - - const self = this; - - // add new pins - pinElements - .enter() - .append('g') - .append(d => { - const val = MapRendererComponent.MarkerSize / ref.zoomScale; - - if (d.isHome) { - const homeIcon = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - homeIcon.setAttribute('r', `${val * 1.25}`) - - return homeIcon; - } - - if (d.pin.VerifiedOwner === 'Safing') { - const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') - polygon.setAttribute('points', `0,-${val} -${val},${val} ${val},${val}`) - - return polygon; - } - - const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - circle.setAttribute('r', `${val}`) - - return circle; - }) - .attr("stroke-width", d => { - if (d.isExit || self.highlightedPins.has(d.pin.ID)) { - return 2 / ref.zoomScale - } - - if (d.isHome) { - return 4.5 / ref.zoomScale - } - - return 1 / ref.zoomScale - }) - .call(selection => { - selection - .style('opacity', 0) - .attr('transform', d => 'scale(0)') - .transition('enter-marker') - /**/.duration(1000) - /**/.attr('transform', d => `scale(1)`) - /**/.style('opacity', 1) - }) - .on('click', function (e: MouseEvent) { - const pin = select(this).datum() as MapPin; - self.onPinClick({ - event: e, - mapPin: pin - }); - }) - .on('mouseenter', function (e: MouseEvent) { - const pin = select(this).datum() as MapPin; - self.onPinHover({ - event: e, - mapPin: pin, - }) - }) - .on('mouseout', function (e: MouseEvent) { - self.onPinHover(null); - }) - - // remove pins from the map that disappeared - pinElements - .exit() - .remove() - - // update all pins to their correct position and update their attributes - pinsGroup.selectAll('g') - .attr('hub-id', d => d.pin.ID) - .attr('is-home', d => d.isHome) - .attr('transform', d => `translate(${ref.projection([d.location.Longitude, d.location.Latitude])})`) - .attr('in-use', d => d.isTransit) - .attr('is-exit', d => d.isExit) - .attr('raise', d => this.highlightedPins.has(d.pin.ID)) - - // update the attributes of the country shapes - ref.worldGroup.selectAll('path') - .attr('has-nodes', d => countriesWithNodes.has(d.properties.iso_a2)) - - // get all in-use pins and raise them to the top - pinsGroup.selectAll('g[in-use=true]') - .raise() - - // finally, re-raise all pins that are highlighted - pinsGroup.selectAll('g[raise=true]') - .raise() - - const activeCountrySet = new Set(); - pins.forEach(pin => { - if (pin.isTransit) { - activeCountrySet.add(pin.pin.ID) - } - }) - - // update the in-use attributes of the country shapes - ref.worldGroup.selectAll('path') - .attr('in-use', d => activeCountrySet.has(d.properties.iso_a2)) - - this.cdr.detectChanges(); - } - - public getPinElem(pinID: string) { - if (!this.mapRef) { - return - } - - return this.mapRef.root - .select("#pin-group") - .select(`g[hub-id=${pinID}]`) - .node() - } - - public clearPinHighlights() { - if (!this.mapRef) { - return - } - - this.mapRef.root - .select('#pin-group') - .select(`g[raise=true]`) - .attr('raise', false) - - this.highlightedPins.clear(); - } - - public highlightPin(pinID: string, highlight: boolean) { - if (highlight) { - this.highlightedPins.add(pinID) - } else { - this.highlightedPins.delete(pinID); - } - - if (!this.mapRef) { - return - } - const pinElemn = this.mapRef!.root - .select("#pin-group") - .select(`g[hub-id=${pinID}]`) - .attr('raise', highlight) - - if (highlight) { - pinElemn - .raise() - } - } -} - -function lineID(l: [MapPin, MapPin]): string { - return [l[0].pin.ID, l[1].pin.ID].sort().join("-") -} - -const tweenDashEnter = function (this: SVGPathElement) { - const len = this.getTotalLength(); - const interpolate = interpolateString(`0, ${len}`, `${len}, ${len}`); - return (t: number) => { - if (t === 1) { - return '0'; - } - return interpolate(t); - } -} - -const tweenDashExit = function (this: SVGPathElement) { - const len = this.getTotalLength(); - const interpolate = interpolateString(`${len}, ${len}`, `0, ${len}`); - return (t: number) => { - if (t === 1) { - return `${len}`; - } - return interpolate(t); - } -} diff --git a/desktop/angular/src/app/pages/spn/spn.module.ts b/desktop/angular/src/app/pages/spn/spn.module.ts deleted file mode 100644 index 737ae25f6..000000000 --- a/desktop/angular/src/app/pages/spn/spn.module.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { A11yModule } from '@angular/cdk/a11y'; -import { DragDropModule } from '@angular/cdk/drag-drop'; -import { OverlayModule } from '@angular/cdk/overlay'; -import { CommonModule } from '@angular/common'; -import { NgModule } from '@angular/core'; -import { FormsModule } from '@angular/forms'; -import { RouterModule } from '@angular/router'; -import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; -import { SfngToggleSwitchModule, SfngTooltipModule, TabModule } from '@safing/ui'; -import { SfngAppIconModule } from 'src/app/shared/app-icon'; -import { CountIndicatorModule } from 'src/app/shared/count-indicator'; -import { CountryFlagModule } from 'src/app/shared/country-flag'; -import { ExpertiseModule } from 'src/app/shared/expertise/expertise.module'; -import { SfngFocusModule } from 'src/app/shared/focus'; -import { SfngMenuModule } from 'src/app/shared/menu'; -import { CommonPipesModule } from 'src/app/shared/pipes'; -import { SpnPageComponent } from './'; -import { CountryDetailsComponent } from './country-details'; -import { CountryOverlayComponent } from './country-overlay'; -import { SpnMapLegendComponent } from './map-legend'; -import { MapRendererComponent } from './map-renderer'; -import { SpnNodeIconComponent } from './node-icon'; -import { PinDetailsComponent } from './pin-details'; -import { SpnPinListComponent } from './pin-list/pin-list'; -import { PinOverlayComponent } from './pin-overlay'; -import { SpnPinRouteComponent } from './pin-route'; -import { SPNFeatureCarouselComponent } from './spn-feature-carousel'; - -@NgModule({ - imports: [ - CommonModule, - FormsModule, - CountryFlagModule, - SfngTooltipModule, - SfngMenuModule, - SfngFocusModule, - SfngAppIconModule, - SfngToggleSwitchModule, - TabModule, - A11yModule, - ExpertiseModule, - OverlayModule, - CountIndicatorModule, - FontAwesomeModule, - CommonPipesModule, - DragDropModule, - RouterModule, - ], - declarations: [ - MapRendererComponent, - PinOverlayComponent, - CountryOverlayComponent, - CountryDetailsComponent, - SpnNodeIconComponent, - SpnMapLegendComponent, - PinDetailsComponent, - SpnPinRouteComponent, - SPNFeatureCarouselComponent, - SpnPageComponent, - SpnPinListComponent, - ], - exports: [ - SpnPageComponent, - SpnPinRouteComponent, - SpnNodeIconComponent, - MapRendererComponent, - ] -}) -export class SPNModule { } diff --git a/desktop/angular/src/app/pages/spn/utils.ts b/desktop/angular/src/app/pages/spn/utils.ts deleted file mode 100644 index eaeefe499..000000000 --- a/desktop/angular/src/app/pages/spn/utils.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { OverlayRef } from '@angular/cdk/overlay'; -import { InjectionToken } from '@angular/core'; - -export const OVERLAY_REF = new InjectionToken('OVERLAY_REF'); diff --git a/desktop/angular/src/app/pages/support/form/support-form.ts b/desktop/angular/src/app/pages/support/form/support-form.ts index fe9b86729..29c776e41 100644 --- a/desktop/angular/src/app/pages/support/form/support-form.ts +++ b/desktop/angular/src/app/pages/support/form/support-form.ts @@ -4,8 +4,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router } from '@angular/router'; import { DebugAPI } from '@safing/portmaster-api'; import { ConfirmDialogConfig, SfngDialogService } from '@safing/ui'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { debounceTime, mergeMap } from 'rxjs/operators'; +import { BehaviorSubject } from 'rxjs'; +import { debounceTime } from 'rxjs/operators'; import { SessionDataService, StatusService } from 'src/app/services'; import { Issue, SupportHubService } from 'src/app/services/supporthub.service'; import { ActionIndicatorService } from 'src/app/shared/action-indicator'; @@ -27,13 +27,13 @@ export class SupportFormComponent implements OnInit { page: SupportPage | null = null; - debugData: string = ''; - title: string = ''; + debugData = ''; + title = ''; form: { [key: string]: string } = {} - selectedRepo: string = ''; + selectedRepo = ''; haveGhAccount = false; - version: string = ''; - buildDate: string = ''; + version = ''; + buildDate = ''; titleMissing = false; relatedIssues: Issue[] = []; @@ -94,7 +94,7 @@ export class SupportFormComponent implements OnInit { for (let pIdx = 0; pIdx < supportTypes.length; pIdx++) { const pageSection = supportTypes[pIdx]; const page = pageSection.choices.find(choice => choice.type !== 'link' && choice.id === id); - if (!!page) { + if (page) { this.page = page as SupportPage; break; } @@ -161,7 +161,8 @@ export class SupportFormComponent implements OnInit { const ticketData: TicketData = { repo: this.selectedRepo || '', title: this.title, - debugInfo: this.debugData, + // Debug information is never uploaded. It stays in the form to copy. + debugInfo: '', sections: this.page?.sections.map(section => ({ title: section.title, body: this.form[section.title], @@ -202,29 +203,9 @@ export class SupportFormComponent implements OnInit { return; } - if (genUrl === undefined && this.haveGhAccount) { - genUrl = true; - } - - if (genUrl === undefined) { - this.dialog.confirm({ - canCancel: true, - caption: 'Caution', - header: 'Create Issue on GitHub', - message: 'You can easily create the issue with your own GitHub account. Or create the GitHub issue privately, but then we will have no way to communicate with you for further information.', - buttons: [ - { id: 'createWithout', text: 'Create Without Account', class: 'outline' }, - { id: 'openGithub', text: 'Use My Account' }, - ] - }) - .onAction('openGithub', () => { - this.createIssue('github', true) - }) - .onAction('createWithout', () => { - this.createIssue('github', false) - }) - return; - } + // Issues are only created by the user on GitHub: the app opens a + // pre-filled "new issue" page and sends nothing itself. + this.createIssue('github', genUrl ?? true); } openIssue(issue: Issue) { diff --git a/desktop/angular/src/app/pages/support/pages.ts b/desktop/angular/src/app/pages/support/pages.ts index 97ca99838..e5bc79cf5 100644 --- a/desktop/angular/src/app/pages/support/pages.ts +++ b/desktop/angular/src/app/pages/support/pages.ts @@ -40,19 +40,19 @@ export const supportTypes: PageSections[] = [ { type: 'link', title: '📘 Portmaster Wiki & FAQ', - url: 'https://wiki.safing.io/?source=Portmaster', + url: 'https://wiki.safing.io/', shortHelp: 'Search the Portmaster knowledge base and FAQ.', }, { type: 'link', title: '🔖 Settings Handbook', - url: 'https://docs.safing.io/portmaster/settings?source=Portmaster', + url: 'https://docs.safing.io/portmaster/settings', shortHelp: 'A reference document of all Portmaster settings.' }, { type: 'link', title: '📑 Safing Blog', - url: 'https://safing.io/blog?source=Portmaster', + url: 'https://safing.io/blog', shortHelp: 'Read our blog posts and announcements.', } ] @@ -75,15 +75,9 @@ export const supportTypes: PageSections[] = [ }, { type: 'link', - title: 'Follow us on Twitter', - url: 'https://twitter.com/SafingIO', - shortHelp: 'Get updates and privacy jokes on Twitter.' - }, - { - type: 'link', - title: 'Safing Support via Email', - url: 'mailto:support@safing.io', - shortHelp: 'As a subscriber, reach out to the Safing team directly.' + title: 'Follow us on X', + url: 'https://x.com/SafingIO', + shortHelp: 'Get updates and privacy jokes on X.' } ] }, @@ -115,7 +109,6 @@ export const supportTypes: PageSections[] = [ }, ], includeDebugData: true, - privateTicket: true, ghIssuePreset: "report-bug.md", repositories: [] }, @@ -133,7 +126,6 @@ export const supportTypes: PageSections[] = [ } ], includeDebugData: false, - privateTicket: true, ghIssuePreset: "suggest-feature.md", repositories: [] }, @@ -156,7 +148,6 @@ export const supportTypes: PageSections[] = [ }, ], includeDebugData: true, - privateTicket: true, ghIssuePreset: "report-compatibility.md", repositories: [] // not needed with the default being "portmaster" }, diff --git a/desktop/angular/src/app/services/notifications.types.ts b/desktop/angular/src/app/services/notifications.types.ts index 5f683dae6..11e3a0a45 100644 --- a/desktop/angular/src/app/services/notifications.types.ts +++ b/desktop/angular/src/app/services/notifications.types.ts @@ -56,7 +56,6 @@ export const PageIDs = { 'support': '/support', 'settings': '/settings', 'apps': '/app/overview', - 'spn': '/spn', } export interface OpenSettingAction extends BaseAction { diff --git a/desktop/angular/src/app/services/supporthub.service.ts b/desktop/angular/src/app/services/supporthub.service.ts index 9b8cfd7c8..750dd5aca 100644 --- a/desktop/angular/src/app/services/supporthub.service.ts +++ b/desktop/angular/src/app/services/supporthub.service.ts @@ -1,7 +1,6 @@ -import { HttpClient, HttpParams } from '@angular/common/http'; +/* eslint-disable @typescript-eslint/no-unused-vars -- the signatures stay as before for the callers, the arguments are no longer sent anywhere */ import { Injectable } from '@angular/core'; -import { Observable } from 'rxjs'; -import { map } from 'rxjs/operators'; +import { Observable, of, throwError } from 'rxjs'; import { environment } from 'src/environments/environment'; export interface SupportSection { @@ -20,63 +19,57 @@ export interface Issue { labels: string[]; } +/** + * Error returned for private support tickets, which were a service of Safing. + */ +export const ERR_TICKETS_REMOVED = + 'Private support tickets are not available in portmasterpro. Please open a GitHub issue instead.'; + +/** + * SupportHubService used to talk to Safing's support hub: + * it listed issues, uploaded debug information and created issues and + * private tickets there. + * + * portmasterpro sends nothing to Safing. Issues are created by opening a + * pre-filled "new issue" page of the project repository in the browser, so + * the user sees and confirms everything that is submitted. Debug information + * is never uploaded. + */ @Injectable({ providedIn: 'root' }) export class SupportHubService { - constructor(private http: HttpClient) { } - + /** Issues are not fetched from any server. */ loadIssues(): Observable { - interface LoadIssuesResponse { - issues: Issue[]; - } - return this.http.get(`${environment.supportHub}/api/v1/issues`) - .pipe(map(res => res.issues.map(issue => ({ - ...issue, - createdAt: new Date(issue.createdAt), - })).reverse())); + return of([]); } - /** Uploads content under name */ - uploadText(name: string, content: string): Observable { - interface UploadResponse { - urls: { - [key: string]: string[]; - } - } - const blob = new Blob([content], { type: 'text/plain' }); - const data = new FormData(); - data.set("file", blob, name); - - return this.http.post(`${environment.supportHub}/api/v1/upload`, data) - .pipe(map(res => res.urls['file'][0])); + /** + * Debug information is not uploaded. Returns an empty URL, so that the + * issue does not reference an upload. + */ + uploadText(_name: string, _content: string): Observable { + return of(''); } - /** Create github issue */ - createIssue(repo: string, preset: string, title: string, sections: SupportSection[], debugInfoUrl?: string, opts?: { + /** + * Returns the URL of a pre-filled "new issue" page in the project + * repository. Nothing is sent: the user opens the page and submits it. + */ + createIssue(_repo: string, _preset: string, title: string, sections: SupportSection[], _debugInfoUrl?: string, _opts?: { generateUrl: boolean, }): Observable { - interface CreateIssueResponse { - url: string; - } - const req = { - title, - sections, - debugInfoUrl - } - let params = new HttpParams(); - if (!!opts?.generateUrl) { - params = params.set('generate-url', '') - } - return this.http.post(`${environment.supportHub}/api/v1/issues/${repo}/${preset}`, req, { params }).pipe(map(r => r.url)) + const body = [ + ...sections + .filter(section => !!section.body?.trim()) + .map(section => `### ${section.title}\n\n${section.body.trim()}`), + '_Debug information is not uploaded. If it helps, copy it from the support page and paste the relevant parts here._', + ].join('\n\n'); + + const params = new URLSearchParams({ title, body }); + return of(`${environment.issueTracker}/new?${params.toString()}`); } - createTicket(repoName: string, title: string, email: string, sections: SupportSection[], debugInfoUrl?: string): Observable { - const req = { - title, - sections, - debugInfoUrl, - email, - repoName, - } - return this.http.post(`${environment.supportHub}/api/v1/ticket`, req) + /** Private tickets were a support service of Safing and are not available. */ + createTicket(_repoName: string, _title: string, _email: string, _sections: SupportSection[], _debugInfoUrl?: string): Observable { + return throwError(() => new Error(ERR_TICKETS_REMOVED)); } } diff --git a/desktop/angular/src/app/shared/config/generic-setting/generic-setting.html b/desktop/angular/src/app/shared/config/generic-setting/generic-setting.html index 7c2f9bd1b..1858e34ba 100644 --- a/desktop/angular/src/app/shared/config/generic-setting/generic-setting.html +++ b/desktop/angular/src/app/shared/config/generic-setting/generic-setting.html @@ -41,16 +41,6 @@

    Invalid Value: {{ rejected }} - - - - - - This feature requires a subscription. -
    -
    - -
    - - - - - - - - - - - - - - - - -
    - -
    -
    - - - - SPN is connecting...
    - Fail-safe blocking enabled -
    - - SPN failed to connect
    - Fail-safe blocking enabled -
    - - SPN is connecting...
    - Fail-safe blocking enabled -
    - - - - - {{ spnStatus?.HomeHubName }} - - in - - - {{ spnStatus?.ConnectedCountry?.Name }} - -
    - -
    -
    - - - -
    - - - - SPN Home (Entry) Node -
      -
    • Connected to {{ spnStatus?.ConnectedIP }}
    • -
    • Uplink is always encrypted
    • -
    • Built with transport/decoy {{ spnStatus?.ConnectedTransport }}
    • -
    -
    diff --git a/desktop/angular/src/app/shared/feature-scout/feature-scout.scss b/desktop/angular/src/app/shared/feature-scout/feature-scout.scss deleted file mode 100644 index 5ae271f6d..000000000 --- a/desktop/angular/src/app/shared/feature-scout/feature-scout.scss +++ /dev/null @@ -1,15 +0,0 @@ -.feature-icon { - @apply text-primary text-opacity-80; - - &.feature-icon-off { - opacity: 0.25; - } -} - -.status-info { - @apply text-primary text-opacity-80 text-xxs text-center; - - &:hover { - cursor: default; - } -} diff --git a/desktop/angular/src/app/shared/feature-scout/feature-scout.ts b/desktop/angular/src/app/shared/feature-scout/feature-scout.ts deleted file mode 100644 index 596edf140..000000000 --- a/desktop/angular/src/app/shared/feature-scout/feature-scout.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, OnInit, inject } from "@angular/core"; -import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { BoolSetting, ConfigService, FeatureID, Netquery, SPNService, SPNStatus, UserProfile } from "@safing/portmaster-api"; -import { catchError, of } from "rxjs"; -import { fadeInAnimation, fadeOutAnimation } from "../animations"; -import { CountryFlagModule } from 'src/app/shared/country-flag'; - -@Component({ - selector: 'app-feature-scout', - templateUrl: './feature-scout.html', - styleUrls: [ - './feature-scout.scss' - ], - changeDetection: ChangeDetectionStrategy.OnPush, - animations: [ - fadeInAnimation, - fadeOutAnimation, - ] -}) -export class FeatureScoutComponent implements OnInit { - private destroyRef = inject(DestroyRef); - - /** The current SPN user profile */ - profile: UserProfile | null = null; - - /** Whether or not the SPN is currently enabled */ - spnEnabled = false; - - /** The current status of the SPN module */ - spnStatus: SPNStatus | null = null; - - /** Whether or not the Network History is currently enabled */ - historyEnabled = false; - - /** Returns whether or not the current package has the SPN feature */ - get packageHasSPN() { - return this.profile?.current_plan?.feature_ids?.includes(FeatureID.SPN) - } - - /** Returns whether or not the current package has the Network History feature */ - get packageHasHistory() { - return this.profile?.current_plan?.feature_ids?.includes(FeatureID.History) - } - - constructor( - private configService: ConfigService, - private spnService: SPNService, - private cdr: ChangeDetectorRef, - ) { } - - ngOnInit(): void { - this.spnService - .profile$ - .pipe( - takeUntilDestroyed(this.destroyRef), - catchError(() => of(null)) - ) - .subscribe(profile => { - this.profile = profile || null; - - this.cdr.markForCheck(); - }); - - this.spnService.status$ - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(status => { - this.spnStatus = status; - - this.cdr.markForCheck(); - }) - - this.configService.watch("spn/enable") - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(value => { - this.spnEnabled = value; - - this.cdr.markForCheck(); - }); - - this.configService.watch("history/enable") - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(value => { - this.historyEnabled = value; - - this.cdr.markForCheck(); - }); - } - - setSPNEnabled(v: boolean) { - this.configService.save(`spn/enable`, v) - .subscribe(); - } - - setHistoryEnabled(v: boolean) { - this.configService.save(`history/enable`, v) - .subscribe(); - } -} diff --git a/desktop/angular/src/app/shared/feature-scout/index.ts b/desktop/angular/src/app/shared/feature-scout/index.ts deleted file mode 100644 index 6fc7f6102..000000000 --- a/desktop/angular/src/app/shared/feature-scout/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './feature-scout'; diff --git a/desktop/angular/src/app/pages/spn/map-renderer/index.ts b/desktop/angular/src/app/shared/map-renderer/index.ts similarity index 100% rename from desktop/angular/src/app/pages/spn/map-renderer/index.ts rename to desktop/angular/src/app/shared/map-renderer/index.ts diff --git a/desktop/angular/src/app/pages/spn/map-renderer/map-renderer.ts b/desktop/angular/src/app/shared/map-renderer/map-renderer.ts similarity index 91% rename from desktop/angular/src/app/pages/spn/map-renderer/map-renderer.ts rename to desktop/angular/src/app/shared/map-renderer/map-renderer.ts index b794a8cc9..ca395c7ed 100644 --- a/desktop/angular/src/app/pages/spn/map-renderer/map-renderer.ts +++ b/desktop/angular/src/app/shared/map-renderer/map-renderer.ts @@ -34,8 +34,7 @@ export interface MapHandler { export const MAP_HANDLER = new InjectionToken('MAP_HANDLER'); @Component({ - // eslint-disable-next-line @angular-eslint/component-selector - selector: 'spn-map-renderer', + selector: 'app-map-renderer', changeDetection: ChangeDetectionStrategy.OnPush, template: '', styleUrls: [ @@ -61,7 +60,7 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { // Projection and line rendering functions projection!: GeoProjection; - zoomScale: number = 1 + zoomScale = 1 private pathFunc!: GeoPath; @@ -70,7 +69,7 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { } @Input() - mapId: string = 'map' + mapId = 'map' constructor( private mapRoot: ElementRef, @@ -134,7 +133,7 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { return; } - if (!!this.svg) { + if (this.svg) { this.svg.remove() } @@ -190,7 +189,6 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { private renderWorld(countries: any) { // actually render the countries const data = countries.features; - const self = this; data.forEach((country: any) => { this.countryNames[country.properties.iso_a2] = country.properties.name @@ -205,32 +203,26 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { .attr('countryCode', (d: any) => d.properties.iso_a2) .attr('name', (d: any) => d.properties.name) .attr('d', this.pathFunc) - .on('mouseenter', function (event: MouseEvent) { - const country = select(this).datum() as any; + .on('mouseenter', (event: MouseEvent, country: any) => { const countryEvent: CountryEvent = { event: event, countryCode: country.properties.iso_a2, countryName: country.properties.name, } - self._countryHoverCb.forEach(cb => cb(countryEvent)) + this._countryHoverCb.forEach(cb => cb(countryEvent)) }) - .on('mouseout', function (event: MouseEvent) { - self._countryHoverCb.forEach(cb => cb(null)) + .on('mouseout', () => { + this._countryHoverCb.forEach(cb => cb(null)) }) - .on('click', function (event: MouseEvent) { - const country = select(this).datum() as any; + .on('click', (event: MouseEvent, country: any) => { const countryEvent: CountryEvent = { event: event, countryCode: country.properties.iso_a2, countryName: country.properties.name, } - const loc = self.projection.invert!([event.clientX, event.clientY]) - - console.log(loc) - - self._countryClickCb.forEach(cb => cb(countryEvent)) + this._countryClickCb.forEach(cb => cb(countryEvent)) }) } @@ -295,16 +287,14 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { k: 0, } - const self = this; - - let z = zoom() + const z = zoom() .scaleExtent(scaleExtent as [number, number]) .on('zoom', (e) => { const t: ZoomTransform = e.transform; if (t.k != tlast.k) { - let p = pointer(e) - let scrollToMouse = () => { }; + const p = pointer(e) + let scrollToMouse = () => { /* only set when the pointer is on the map */ }; if (!!p && !!p[0]) { const tp = this.projection.translate(); @@ -329,7 +319,7 @@ export class MapRendererComponent implements OnInit, AfterViewInit, OnDestroy { // use x translation to rotate based on current scale this.projection.rotate([yaw + 360.0 * dx / size.width * scaleExtent[0] / t.k, 0, 0]) // use y translation to translate projection clamped to bounds - let bounds = mercatorBounds(); + const bounds = mercatorBounds(); if (bounds[0][1] + dy > 0) { dy = -bounds[0][1]; } else if (bounds[1][1] + dy < size.height) { diff --git a/desktop/angular/src/app/shared/map-renderer/map-style.scss b/desktop/angular/src/app/shared/map-renderer/map-style.scss new file mode 100644 index 000000000..e88282cf1 --- /dev/null +++ b/desktop/angular/src/app/shared/map-renderer/map-style.scss @@ -0,0 +1,11 @@ +:host-context(.disabled) { + @apply bg-white; + + #world-group { + path { + fill: #000000; + stroke: #111111; + stroke-width: .5px; + } + } +} diff --git a/desktop/angular/src/app/shared/netquery/circular-bar-chart/circular-bar-chart.component.ts b/desktop/angular/src/app/shared/netquery/circular-bar-chart/circular-bar-chart.component.ts index 6db5db2f5..07daade19 100644 --- a/desktop/angular/src/app/shared/netquery/circular-bar-chart/circular-bar-chart.component.ts +++ b/desktop/angular/src/app/shared/netquery/circular-bar-chart/circular-bar-chart.component.ts @@ -38,7 +38,7 @@ export interface CircularBarChartConfig { export function splitQueryResult(results: T[], series: K[]): (QueryResult & { series: string, value: number })[] { - let mapped: (QueryResult & { series: string, value: number })[] = []; + const mapped: (QueryResult & { series: string, value: number })[] = []; results.forEach(row => { series.forEach(seriesKey => { @@ -109,7 +109,7 @@ export class CircularBarChartComponent implements OnInit, AfterViewInit { } private prepareChart() { - if (!!this.svg) { + if (this.svg) { const parent = this.svg.node()?.parentElement parent?.remove() } @@ -359,7 +359,7 @@ export class CircularBarChartComponent implements OnInit, AfterViewInit { .attr("font-size", "0.6rem") .attr("fill", "#fff") .text(d => { - if (!!this.config?.seriesLabel) { + if (this.config?.seriesLabel) { return this.config.seriesLabel(d) } diff --git a/desktop/angular/src/app/shared/netquery/connection-details/conn-details.html b/desktop/angular/src/app/shared/netquery/connection-details/conn-details.html index fcbe03cbd..8b3f0692e 100644 --- a/desktop/angular/src/app/shared/netquery/connection-details/conn-details.html +++ b/desktop/angular/src/app/shared/netquery/connection-details/conn-details.html @@ -80,10 +80,6 @@ Encrypted: {{ conn.encrypted ? 'yes' : 'no' }}
    - - SPN Protected: - {{ conn.tunneled ? 'yes' : 'no' }} - Data Received: @@ -221,40 +217,6 @@

    -
    -

    SPN Tunnel

    - - - This connection has not been routed through the Safing Privacy Network. - - - -
    -
    - - - - -
    -
    - - Path Costs: - {{ conn.extra_data?.tunnel?.PathCost }} - - - Routing Algorithm: - {{ conn.extra_data?.tunnel?.RoutingAlg }} - -
    -
    - - - The connection was routed through the Safing Privacy Network, but the tunnel information is not available. Try - reloading the connections. - -
    -
    -

    Split Tunnel

    diff --git a/desktop/angular/src/app/shared/netquery/connection-helper.service.ts b/desktop/angular/src/app/shared/netquery/connection-helper.service.ts index 89b8ff0a3..77a4385df 100644 --- a/desktop/angular/src/app/shared/netquery/connection-helper.service.ts +++ b/desktop/angular/src/app/shared/netquery/connection-helper.service.ts @@ -1,7 +1,7 @@ import { DOCUMENT } from '@angular/common'; import { Inject, Injectable, Renderer2, inject } from '@angular/core'; import { Router } from '@angular/router'; -import { AppProfile, AppProfileService, ConfigService, IPScope, NetqueryConnection, Pin, PossilbeValue, QueryResult, SPNService, Verdict, deepClone, flattenProfileConfig, getAppSetting, setAppSetting } from '@safing/portmaster-api'; +import { AppProfile, AppProfileService, ConfigService, IPScope, NetqueryConnection, PossilbeValue, QueryResult, Verdict, deepClone, flattenProfileConfig, getAppSetting, setAppSetting } from '@safing/portmaster-api'; import { BehaviorSubject, Observable, OperatorFunction, Subject, combineLatest } from 'rxjs'; import { distinctUntilChanged, filter, map, switchMap, take, takeUntil } from 'rxjs/operators'; import { ActionIndicatorService } from '../action-indicator'; @@ -35,7 +35,6 @@ export class NetqueryHelper { private addToFilter$ = new Subject(); private destroy$ = new Subject(); private appProfiles$ = new BehaviorSubject([]); - private spnMapPins$ = new BehaviorSubject(null); private readonly integration = inject(INTEGRATION_SERVICE); readonly onShiftKey: Observable; @@ -47,7 +46,6 @@ export class NetqueryHelper { private configService: ConfigService, private actionIndicator: ActionIndicatorService, private renderer: Renderer2, - private spnService: SPNService, @Inject(DOCUMENT) private document: Document, ) { const cleanupKeyDown = this.renderer.listen(this.document, 'keydown', (event: KeyboardEvent) => { @@ -102,12 +100,6 @@ export class NetqueryHelper { } })) }); - - this.spnService.watchPins() - .pipe(takeUntil(this.destroy$)) - .subscribe(pins => { - this.spnMapPins$.next(pins); - }) } decodePrettyValues(field: keyof NetqueryConnection, values: any[]): any[] { @@ -119,7 +111,7 @@ export class NetqueryHelper { return values.map(val => { // check if it's a value of the IPScope enum const scopeValue = IPScope[val]; - if (!!scopeValue) { + if (scopeValue) { return scopeValue; } @@ -149,14 +141,6 @@ export class NetqueryHelper { }) } - if (field === 'exit_node') { - const lm = new Map(); - (this.spnMapPins$.getValue() || []) - .forEach(pin => lm.set(pin.Name, pin)); - - return values.map(val => lm.get(val)?.ID || val) - } - return values; } @@ -166,7 +150,7 @@ export class NetqueryHelper { this.appProfiles$, ]).pipe( map(([items, profiles]) => { - let lm = new Map(); + const lm = new Map(); profiles.forEach(profile => { lm.set(`${profile.Source}/${profile.ID}`, profile) }) @@ -182,42 +166,15 @@ export class NetqueryHelper { ) } - attachPins(): OperatorFunction { - return source => combineLatest([ - source, - this.spnMapPins$ - .pipe( - filter(result => result !== null), - take(1), - ), - ]).pipe( - map(([items, pins]) => { - let lm = new Map(); - pins!.forEach(pin => { - lm.set(pin.ID, pin) - }) - - return items.map(item => { - if ('exit_node' in item) { - item.__exitNode = lm.get(item.exit_node!) - } - - return item; - }) - }) - ) - } - encodeToPossibleValues(field: string): OperatorFunction { return source => combineLatest([ source, this.appProfiles$, - this.spnMapPins$, ]).pipe( - map(([items, profiles, pins]) => { + map(([items, profiles]) => { // convert profile IDs to profile name if (field === 'profile') { - let lm = new Map(); + const lm = new Map(); profiles.forEach(profile => { lm.set(`${profile.Source}/${profile.ID}`, profile) }) @@ -283,21 +240,6 @@ export class NetqueryHelper { }) } - if (field === 'exit_node') { - const lm = new Map(); - pins!.forEach(pin => lm.set(pin.ID, pin)); - - return items.map(item => { - const pin = lm.get(item.exit_node!); - return { - Name: pin?.Name || item.exit_node, - Value: item.exit_node, - Description: 'Operated by ' + (pin?.VerifiedOwner || 'N/A'), - ...item - } - }) - } - // the rest is just converted into the {@link PossibleValue} form // by using the value as the "Name". return items.map(item => ({ @@ -378,7 +320,7 @@ export class NetqueryHelper { let profile = conn.profile - if (!!reason.Profile) { + if (reason.Profile) { profile = reason.Profile; } diff --git a/desktop/angular/src/app/shared/netquery/netquery.component.html b/desktop/angular/src/app/shared/netquery/netquery.component.html index dac7211c2..e4a622779 100644 --- a/desktop/angular/src/app/shared/netquery/netquery.component.html +++ b/desktop/angular/src/app/shared/netquery/netquery.component.html @@ -119,8 +119,7 @@

    -
    +
    Search History: @@ -165,7 +164,7 @@

    +

    Connections

    @@ -173,7 +172,7 @@

    +

    Data Usage

    @@ -216,20 +215,8 @@

    - - ( - - ) - - {{ data.__exitNode.Name }} - - - {{ data[key] || 'N/A' }} diff --git a/desktop/angular/src/app/shared/netquery/netquery.component.ts b/desktop/angular/src/app/shared/netquery/netquery.component.ts index 994267ad6..8edd2d46b 100644 --- a/desktop/angular/src/app/shared/netquery/netquery.component.ts +++ b/desktop/angular/src/app/shared/netquery/netquery.component.ts @@ -3,7 +3,7 @@ import { FormatWidth, formatDate, getLocaleDateFormat, getLocaleId } from "@angu import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, EventEmitter, Input, LOCALE_ID, OnDestroy, OnInit, Output, QueryList, TemplateRef, TrackByFunction, ViewChildren, inject, isDevMode } from "@angular/core"; import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { ActivatedRoute, Router } from "@angular/router"; -import { BandwidthChartResult, ChartResult, Condition, Database, FeatureID, GreaterOrEqual, IPScope, LessOrEqual, Netquery, NetqueryConnection, OrderBy, Pin, PossilbeValue, Query, QueryResult, SPNService, Select, Verdict } from "@safing/portmaster-api"; +import { BandwidthChartResult, ChartResult, Condition, Database, GreaterOrEqual, IPScope, LessOrEqual, Netquery, NetqueryConnection, OrderBy, PossilbeValue, Query, QueryResult, Select, Verdict } from "@safing/portmaster-api"; import { Datasource, DynamicItemsPaginator, SelectOption } from "@safing/ui"; import { BehaviorSubject, Observable, Subject, combineLatest, forkJoin, interval, merge, of, timer } from "rxjs"; import { catchError, filter, map, share, skip, startWith, switchMap, take, takeUntil } from "rxjs/operators"; @@ -73,7 +73,6 @@ interface LocalQueryResult extends QueryResult { _chart: Observable | null; _group: Observable> | null; __profile?: LocalAppProfile; - __exitNode?: Pin; } interface QuickDateSetting { @@ -206,13 +205,13 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { paginator!: DynamicItemsPaginator; /** @private - The total amount of connections without the filter applied */ - totalConnCount: number = 0; + totalConnCount = 0; /** @private - The total amount of connections with the filter applied */ - totalResultCount: number = 0; + totalResultCount = 0; /** The value of the free-text search */ - textSearch: string = ''; + textSearch = ''; /** The date filter */ dateFilter: Date[] = [] @@ -261,7 +260,7 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { /** Auto-reload: The list of all intervals */ readonly reloadIntervals = Object.keys(reloadIntervalValues); /** Auto-reload: The name of the currently selected auto-reload interval */ - autoReloadIntervalName: string = ''; + autoReloadIntervalName = ''; /** Auto-reload: The timestamp of auto-reload being enabled */ autoReloadEnabledTimestamp: Date | null = null; /** Auto-reload: Enable/disable auto-reload and set the interval */ @@ -317,29 +316,6 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { return [Database.Live, Database.History]; } - // whether or not the current use has the history feature available. - canUseHistory$ = inject(SPNService).profile$ - .pipe( - map(profile => { - if (!profile) { - return false; - } - - return profile.current_plan?.feature_ids?.includes(FeatureID.History) || false; - }) - ); - - featureBw$ = inject(SPNService).profile$ - .pipe( - map(profile => { - if (!profile) { - return false; - } - - return profile.current_plan?.feature_ids?.includes(FeatureID.Bandwidth) || false; - }) - ); - trackPageItem: TrackByFunction = (_, r) => { if (this.groupByKeys?.length) { return this.groupByKeys.map(key => r[key]).join('-') @@ -541,12 +517,7 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { menuTitle: 'Active', suggestions: booleanSuggestionValues(), }, - tunneled: { - visible: 'combinedMenu', - menuTitle: 'SPN', - suggestions: booleanSuggestionValues(), - tipupKey: 'spn' - }, + tunneled: {}, from: { virtual: true }, @@ -579,7 +550,6 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { return this.netquery.query(query, 'netquery-viewer') .pipe( this.helper.attachProfile(), - this.helper.attachPins(), map(results => { return (results || []).map(r => { const grpFilter: Condition = { @@ -589,10 +559,10 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { grpFilter[key] = r[key]; }) - let page = { + const page = { ...r, - _chart: !!this.groupByKeys.length ? this.getGroupChart(grpFilter) : null, - _group: !!this.groupByKeys.length ? this.lazyLoadGroup(grpFilter) : null, + _chart: this.groupByKeys.length ? this.getGroupChart(grpFilter) : null, + _group: this.groupByKeys.length ? this.lazyLoadGroup(grpFilter) : null, } return page; @@ -857,7 +827,7 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { // handle any filter preset // - if (!!this.filterPreset) { + if (this.filterPreset) { try { const result = Parser.parse(this.filterPreset); this.onFieldsParsed({ @@ -990,7 +960,7 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { // create a set that we can use to lookup if a value // is currently selected. // This is needed to ensure selected values are sorted to the top. - let currentlySelected = new Set(); + const currentlySelected = new Set(); this.models[field]!.searchValues.forEach( val => currentlySelected.add(val) ); @@ -1203,7 +1173,7 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { } let select: Query['select'] | undefined = undefined; - if (!!this.groupByKeys.length) { + if (this.groupByKeys.length) { // we always want to show the total and the number of allowed connections // per group so we need to add those to the select part of the query select = [ @@ -1232,7 +1202,7 @@ export class SfngNetqueryViewer implements OnInit, OnDestroy, AfterViewInit { ] } - let normalizedQuery = mergeConditions(query, this.mergeFilter || {}) + const normalizedQuery = mergeConditions(query, this.mergeFilter || {}) let orderBy: string[] | OrderBy[] = this.orderByKeys; if (!orderBy || orderBy.length === 0) { diff --git a/desktop/angular/src/app/shared/netquery/netquery.module.ts b/desktop/angular/src/app/shared/netquery/netquery.module.ts index 5a4336667..cf2cc2d1b 100644 --- a/desktop/angular/src/app/shared/netquery/netquery.module.ts +++ b/desktop/angular/src/app/shared/netquery/netquery.module.ts @@ -13,7 +13,6 @@ import { ExpertiseModule } from "../expertise/expertise.module"; import { SfngFocusModule } from "../focus"; import { SfngMenuModule } from "../menu"; import { CommonPipesModule } from "../pipes"; -import { SPNModule } from './../../pages/spn/spn.module'; import { SfngNetqueryAddToFilterDirective } from "./add-to-filter"; import { CombinedMenuPipe } from "./combined-menu.pipe"; import { SfngNetqueryConnectionDetailsComponent } from "./connection-details"; @@ -48,7 +47,6 @@ import { CircularBarChartComponent } from './circular-bar-chart/circular-bar-cha CountIndicatorModule, FontAwesomeModule, CommonPipesModule, - SPNModule, NzDatePickerModule, ], exports: [ diff --git a/desktop/angular/src/app/shared/netquery/pipes/country-name.pipe.ts b/desktop/angular/src/app/shared/netquery/pipes/country-name.pipe.ts index 93e6bc61d..ccc5f62de 100644 --- a/desktop/angular/src/app/shared/netquery/pipes/country-name.pipe.ts +++ b/desktop/angular/src/app/shared/netquery/pipes/country-name.pipe.ts @@ -1,6 +1,6 @@ import { HttpClient } from '@angular/common/http'; import { Pipe, PipeTransform, Injectable, inject } from '@angular/core'; -import { GeoCoordinates, SPNService } from '@safing/portmaster-api'; +import { GeoCoordinates } from '@safing/portmaster-api'; import { environment } from 'src/environments/environment'; import { ActionIndicatorService } from '../../action-indicator'; import { objKeys } from '../../utils'; @@ -20,7 +20,6 @@ export interface CountryListResponse { @Injectable() export class CountryNameService { - private readonly spn = inject(SPNService); private readonly http = inject(HttpClient); private readonly uai = inject(ActionIndicatorService); diff --git a/desktop/angular/src/app/shared/network-scout/network-scout.html b/desktop/angular/src/app/shared/network-scout/network-scout.html index b314d86b9..7a286d835 100644 --- a/desktop/angular/src/app/shared/network-scout/network-scout.html +++ b/desktop/angular/src/app/shared/network-scout/network-scout.html @@ -34,85 +34,12 @@

    Sort By

    - - - - - - - - -
    - - -
    - {{ profile.exitPins.length }} - IDENTITIES -
    - - - Connections from {{ profile.Name }} have not been routed through the SPN. - - -
      -
    • - - - - {{ entity.IP }} - - -
      - - {{ identity.count }} - Connections - - - HOPS: - {{ identity.HopDistance }} - -
      -
    • -
    - - - {{ profile.showMore ? 'Show Less Identities' : 'Show More Identities'}} - -
    -
    - - -
    - - - - +
    +
    @@ -122,19 +49,6 @@

    Sort By

    -
    - - - - - - -
    -
    @@ -179,4 +93,4 @@

    Sort By

    - +
    diff --git a/desktop/angular/src/app/shared/network-scout/network-scout.ts b/desktop/angular/src/app/shared/network-scout/network-scout.ts index 8c3c7d880..50ddf9ae4 100644 --- a/desktop/angular/src/app/shared/network-scout/network-scout.ts +++ b/desktop/angular/src/app/shared/network-scout/network-scout.ts @@ -1,20 +1,12 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, OnInit, TrackByFunction, inject } from "@angular/core"; import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { BoolSetting, Condition, ConfigService, ExpertiseLevel, IProfileStats, Netquery, Pin, SPNService } from "@safing/portmaster-api"; -import { Subject, combineLatest, debounceTime, filter, finalize, interval, retry, startWith, switchMap, take, takeUntil } from "rxjs"; +import { Condition, ExpertiseLevel, IProfileStats, Netquery } from "@safing/portmaster-api"; +import { Subject, combineLatest, debounceTime, filter, finalize, interval, retry, startWith, switchMap, take } from "rxjs"; import { UIStateService } from "src/app/services"; import { fadeInListAnimation } from "../animations"; import { ExpertiseService } from './../expertise/expertise.service'; -interface _Pin extends Pin { - count: number; -} - -interface _Profile extends IProfileStats { - exitPins: _Pin[]; - showMore: boolean; - expanded: boolean; -} +type _Profile = IProfileStats; export enum SortTypes { static = 'Static', @@ -23,7 +15,6 @@ export enum SortTypes { totalConnections = "Total Connections", connectionsDenied = "Denied Connections", connectionsAllowed = "Allowed Connections", - spnIdentities = "SPN Identities", bytesSent = "Bytes Sent", bytesReceived = "Bytes Received", totalBytes = "Total Bytes" @@ -54,7 +45,6 @@ export class NetworkScoutComponent implements OnInit { SortTypes.totalConnections, SortTypes.connectionsDenied, SortTypes.connectionsAllowed, - SortTypes.spnIdentities ] readonly sortMethods = new Map([ @@ -65,7 +55,6 @@ export class NetworkScoutComponent implements OnInit { [SortTypes.totalConnections, (a: _Profile, b: _Profile) => (b.countAllowed + b.countUnpermitted) - (a.countAllowed + a.countUnpermitted)], [SortTypes.connectionsAllowed, (a: _Profile, b: _Profile) => b.countAllowed - a.countAllowed], [SortTypes.connectionsDenied, (a: _Profile, b: _Profile) => b.countUnpermitted - a.countUnpermitted], - [SortTypes.spnIdentities, (a: _Profile, b: _Profile) => a.identities.length - b.identities.length], [SortTypes.bytesReceived, (a: _Profile, b: _Profile) => b.bytes_received - a.bytes_received], [SortTypes.bytesSent, (a: _Profile, b: _Profile) => b.bytes_sent - a.bytes_sent], [SortTypes.totalBytes, (a: _Profile, b: _Profile) => (b.bytes_received + b.bytes_sent) - (a.bytes_received + a.bytes_sent)] @@ -82,24 +71,11 @@ export class NetworkScoutComponent implements OnInit { triggerSearch = new Subject(); /** The current search term as entered in the input[type="text"] */ - searchTerm: string = ''; + searchTerm = ''; /** A list of all active profiles without any search applied */ allProfiles: _Profile[] = []; - /** Defines if new elements should be expanded or collapsed */ - expandCollapseState: 'expand' | 'collapse' = 'expand'; - - /** Whether or not the SPN is enabled */ - spnEnabled = false; - - /** - * Emits when the user clicks the "expand all" or "collapse all" buttons. - * Once the user did that we stop updating the default state depending on whether the - * SPN is enabled or not. - */ - private userChangedState = new Subject(); - /** * A list of profiles that are currently displayed. This is basically allProfiles but with * text search applied. @@ -109,13 +85,8 @@ export class NetworkScoutComponent implements OnInit { /** TrackByFunction for the profiles. */ trackProfile: TrackByFunction<_Profile> = (_, profile) => profile.ID; - /** TrackByFunction for the exit pins */ - trackPin: TrackByFunction<_Pin> = (_, pin) => pin.ID; - constructor( private netquery: Netquery, - private spn: SPNService, - private configService: ConfigService, private stateService: UIStateService, private expertise: ExpertiseService, private cdr: ChangeDetectorRef, @@ -144,10 +115,6 @@ export class NetworkScoutComponent implements OnInit { return true; } - if (p.exitPins.some(pin => pin.Name.toLocaleLowerCase().includes(lowerCaseTerm))) { - return true; - } - return false; }) @@ -177,52 +144,19 @@ export class NetworkScoutComponent implements OnInit { }) } - expandAll() { - this.expandCollapseState = 'expand'; - this.allProfiles.forEach(profile => profile.expanded = profile.identities.length > 0) - this.searchProfiles(this.searchTerm) - this.userChangedState.next(); - - this.cdr.markForCheck() - } - - collapseAll() { - this.expandCollapseState = 'collapse'; - this.allProfiles.forEach(profile => profile.expanded = false) - this.searchProfiles(this.searchTerm) - this.userChangedState.next(); - - this.cdr.markForCheck() - } - ngOnInit(): void { this.stateService.uiState() .pipe(take(1)) .subscribe(state => { - this.sortOrder = state.netscoutSortOrder; + // fall back to the default if the stored sort order is no longer + // available (e.g. the removed "SPN Identities" order). + this.sortOrder = Object.values(SortTypes).includes(state.netscoutSortOrder) + ? state.netscoutSortOrder + : SortTypes.static; this.searchProfiles(this.searchTerm); }) - this.configService.watch('spn/enable') - .pipe( - takeUntilDestroyed(this.destroyRef), - takeUntil(this.userChangedState), - ) - .subscribe(enabled => { - // if the SPN is enabled and the user did not yet change the - // collapse/expand state we switch to "expand" for the default. - // Otherwise, there will be no identities so there's no reason - // to expand them at all so we switch to collapse - if (enabled) { - this.expandCollapseState = 'expand' - } else { - this.expandCollapseState = 'collapse' - } - - this.spnEnabled = enabled; - }); - let updateInProgress = false; combineLatest([ @@ -236,7 +170,7 @@ export class NetworkScoutComponent implements OnInit { .pipe( startWith(-1), switchMap(() => { - let query: Condition = {}; + const query: Condition = {}; if (this.expertise.currentLevel !== ExpertiseLevel.Developer) { query["internal"] = { $eq: false } } @@ -251,12 +185,6 @@ export class NetworkScoutComponent implements OnInit { retry({ delay: 5000 }) ), - this.spn.watchPins() - .pipe( - debounceTime(100), - startWith([]), - ), - this.triggerSearch .pipe( debounceTime(100), @@ -266,39 +194,8 @@ export class NetworkScoutComponent implements OnInit { .pipe( takeUntilDestroyed(this.destroyRef), ) - .subscribe(([res, pins, searchTerm]) => { - // create a lookup map for the the SPN map pins - const pinLookupMap = new Map(); - pins.forEach(p => pinLookupMap.set(p.ID, p)) - - // create a lookup map from already known profiles so we can - // inherit states like "showMore". - const profileLookupMap = new Map(); - this.allProfiles.forEach(p => profileLookupMap.set(p.ID, p)) - - // map the list of profile statistics to include the exit Pin information - // as well. - this.allProfiles = res.map(s => { - const existing = profileLookupMap.get(s.ID); - return { - ...s, - exitPins: s.identities - .map(ident => { - const pin = pinLookupMap.get(ident.exit_node); - if (!pin) { - return null; - } - - return { - count: ident.count, - ...pin - } - }) - .filter(pin => !!pin), - showMore: existing?.showMore ?? false, - expanded: existing?.expanded ?? (this.expandCollapseState === 'expand' && s.identities.length > 1 /* there's always the "direct" identity */), - } as _Profile - }); + .subscribe(([res, searchTerm]) => { + this.allProfiles = res; this.searchProfiles(searchTerm); @@ -306,7 +203,7 @@ export class NetworkScoutComponent implements OnInit { // make sure our sort methods are updated. if (this.profiles.some(p => p.bytes_received > 0 || p.bytes_sent > 0)) { if (!this.sortTypes.includes(SortTypes.bytesReceived)) { - this.sortTypes.push.apply(this.sortTypes, bandwidthSorts) + this.sortTypes.push(...bandwidthSorts) } this.sortTypes = [...this.sortTypes]; diff --git a/desktop/angular/src/app/shared/security-lock/security-lock.ts b/desktop/angular/src/app/shared/security-lock/security-lock.ts index 2172ebdb3..88b28938f 100644 --- a/desktop/angular/src/app/shared/security-lock/security-lock.ts +++ b/desktop/angular/src/app/shared/security-lock/security-lock.ts @@ -68,8 +68,6 @@ export class SecurityLockComponent implements OnInit { const pauseData = pausedState.Data as ControlPauseStateData; if (pauseData.Interception === true) { this.lockLevel.displayText = 'Insecure: PAUSED'; - } else if (pauseData.SPN === true) { - this.lockLevel.displayText = 'Secure (SPN Paused)'; } } diff --git a/desktop/angular/src/app/shared/spn-account-details/index.ts b/desktop/angular/src/app/shared/spn-account-details/index.ts deleted file mode 100644 index 623342d5f..000000000 --- a/desktop/angular/src/app/shared/spn-account-details/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './spn-account-details'; diff --git a/desktop/angular/src/app/shared/spn-account-details/spn-account-details.html b/desktop/angular/src/app/shared/spn-account-details/spn-account-details.html deleted file mode 100644 index 3b5940579..000000000 --- a/desktop/angular/src/app/shared/spn-account-details/spn-account-details.html +++ /dev/null @@ -1,101 +0,0 @@ - -

    Account Details

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Your Package{{ currentUser.current_plan?.name }}
    Access Until{{ currentUser.subscription.ends_at | date:'medium' }}
    Your Subscription{{ currentUser.current_plan?.name }}
    Status{{ currentUser.subscription.state }}
    Next Payment Date - {{ currentUser.subscription.next_billing_date | date:'medium' }} - via - {{ currentUser.subscription.payment_provider }} -
    Access Paid Until{{ currentUser.subscription.ends_at | date:'medium' }}
    Username{{ currentUser.username }}
    Device Name{{ currentUser.device?.name }}
    Account State{{ currentUser.state }}
    Features{{ currentUser.current_plan?.feature_ids?.join(", ") }}
    Device ID{{currentUser.device?.id}}
    Logged in Since{{ currentUser.LoggedInAt | date:'medium' }}
    - -
    - - -
    - - - Open Account Page - - - - -
    -
    - - diff --git a/desktop/angular/src/app/shared/spn-account-details/spn-account-details.scss b/desktop/angular/src/app/shared/spn-account-details/spn-account-details.scss deleted file mode 100644 index f1c7dc0d6..000000000 --- a/desktop/angular/src/app/shared/spn-account-details/spn-account-details.scss +++ /dev/null @@ -1,7 +0,0 @@ -table tr { - background-color: transparent !important; -} - -table .table-section-start { - border-top: 1.5rem solid transparent; -} diff --git a/desktop/angular/src/app/shared/spn-account-details/spn-account-details.ts b/desktop/angular/src/app/shared/spn-account-details/spn-account-details.ts deleted file mode 100644 index 512f6674b..000000000 --- a/desktop/angular/src/app/shared/spn-account-details/spn-account-details.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, Inject, OnInit, Optional, inject } from "@angular/core"; -import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { SPNService, UserProfile } from "@safing/portmaster-api"; -import { SFNG_DIALOG_REF, SfngDialogRef } from "@safing/ui"; -import { catchError, delay, of, tap } from "rxjs"; -import { ActionIndicatorService } from "../action-indicator"; - -@Component({ - templateUrl: './spn-account-details.html', - styleUrls: ['./spn-account-details.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class SPNAccountDetailsComponent implements OnInit { - private destroyRef = inject(DestroyRef); - - /** Whether or not we're currently refreshing the user profile from the customer agent */ - refreshing = false; - - /** Whether or not we're still waiting for the user profile to be fetched from the backend */ - loadingProfile = true; - - currentUser: UserProfile | null = null; - - constructor( - private spnService: SPNService, - private cdr: ChangeDetectorRef, - private uai: ActionIndicatorService, - @Inject(SFNG_DIALOG_REF) @Optional() public dialogRef: SfngDialogRef, - ) { } - - /** - * Force a refresh of the local user account - * - * @private - template only - */ - refreshAccount() { - this.refreshing = true; - this.spnService.userProfile(true) - .pipe( - delay(1000), - tap(() => { - this.refreshing = false; - this.cdr.markForCheck(); - }), - ) - .subscribe() - } - - /** - * Logout of your safing account - * - * @private - template only - */ - logout() { - this.spnService.logout() - .pipe(tap(() => this.dialogRef?.close())) - .subscribe(this.uai.httpObserver('SPN Logout', 'SPN Logout')) - } - - ngOnInit(): void { - this.loadingProfile = false; - this.spnService.profile$ - .pipe( - takeUntilDestroyed(this.destroyRef), - catchError(err => of(null)), - ) - .subscribe({ - next: (profile) => { - this.loadingProfile = false; - this.currentUser = profile || null; - - this.cdr.markForCheck(); - }, - complete: () => { - // Database entry deletion will complete the observer. - this.loadingProfile = false; - this.currentUser = null; - - this.cdr.markForCheck(); - }, - }) - } -} diff --git a/desktop/angular/src/app/shared/spn-login/index.ts b/desktop/angular/src/app/shared/spn-login/index.ts deleted file mode 100644 index 258508560..000000000 --- a/desktop/angular/src/app/shared/spn-login/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './spn-login'; diff --git a/desktop/angular/src/app/shared/spn-login/spn-login.html b/desktop/angular/src/app/shared/spn-login/spn-login.html deleted file mode 100644 index 8f59d86c2..000000000 --- a/desktop/angular/src/app/shared/spn-login/spn-login.html +++ /dev/null @@ -1,70 +0,0 @@ - -
    -

    -
    - - - - - - - - - - - - - - - - -
    - - Safing Account Login - - Unlock powerful features. - - -

    - - -
    - You have been logged out by the account server. -
    - Please check your account. -
    - -
    -
    -
    - - -
    - -
    - - -
    - -
    - - -
    -
    -
    -
    diff --git a/desktop/angular/src/app/shared/spn-login/spn-login.scss b/desktop/angular/src/app/shared/spn-login/spn-login.scss deleted file mode 100644 index 232d51eee..000000000 --- a/desktop/angular/src/app/shared/spn-login/spn-login.scss +++ /dev/null @@ -1,53 +0,0 @@ -:host { - display: block; - width: 100%; -} - -.custom-form-input { - background: none; - @apply border-0 border-b border-buttons-light text-secondary font-medium px-0; - - &:active, - &:focus { - background: none; - } -} - -.logo-image { - @apply w-16 absolute; -} - -svg.logo-image { - animation-timing-function: cubic-bezier(0.445, 0.05, 0.55, 0.95); -} - -.spin { - animation-name: spin; - animation-duration: 3500ms; - animation-iteration-count: infinite; - animation-timing-function: linear; -} - -.reverse { - animation-name: spin-reverse; -} - -@keyframes spin { - 0% { - transform: rotate(0deg); - } - - 100% { - transform: rotate(360deg); - } -} - -@keyframes spin-reverse { - 0% { - transform: rotate(360deg); - } - - 100% { - transform: rotate(0deg); - } -} diff --git a/desktop/angular/src/app/shared/spn-login/spn-login.ts b/desktop/angular/src/app/shared/spn-login/spn-login.ts deleted file mode 100644 index a5ae41721..000000000 --- a/desktop/angular/src/app/shared/spn-login/spn-login.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { coerceBooleanProperty } from "@angular/cdk/coercion"; -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, Input, OnInit, inject } from "@angular/core"; -import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { SPNService, UserProfile } from "@safing/portmaster-api"; -import { catchError, finalize, of } from "rxjs"; -import { ActionIndicatorService } from "../action-indicator"; - -@Component({ - selector: 'app-spn-login', - templateUrl: './spn-login.html', - styleUrls: ['./spn-login.scss'], - changeDetection: ChangeDetectionStrategy.OnPush -}) -export class SPNLoginComponent implements OnInit { - private destroyRef = inject(DestroyRef); - - /** The current user profile if the user is already logged in */ - profile: UserProfile | null = null; - - /** The value of the username text box */ - username: string = ''; - - /** The value of the password text box */ - password: string = ''; - - @Input() - set forcedLogout(v: any) { - this._forcedLogout = coerceBooleanProperty(v); - } - get forcedLogout() { return this._forcedLogout } - private _forcedLogout = false; - - constructor( - private spnService: SPNService, - private uai: ActionIndicatorService, - private cdr: ChangeDetectorRef - ) { } - - login(): void { - if (!this.username || !this.password) { - return; - } - - this.spnService.login({ - username: this.username, - password: this.password - }) - .pipe(finalize(() => { - this.password = ''; - })) - .subscribe(this.uai.httpObserver('SPN Login', 'SPN Login')) - } - - ngOnInit(): void { - this.spnService.profile$ - .pipe( - takeUntilDestroyed(this.destroyRef), - catchError(() => of(null)) - ) - .subscribe(profile => { - this.profile = profile || null; - - if (!!this.profile) { - this.username = this.profile.username; - } - - this.cdr.markForCheck(); - }); - } -} diff --git a/desktop/angular/src/app/shared/spn-network-status/index.ts b/desktop/angular/src/app/shared/spn-network-status/index.ts deleted file mode 100644 index bfa12d5d6..000000000 --- a/desktop/angular/src/app/shared/spn-network-status/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './spn-network-status'; diff --git a/desktop/angular/src/app/shared/spn-network-status/spn-network-status.html b/desktop/angular/src/app/shared/spn-network-status/spn-network-status.html deleted file mode 100644 index 83196071c..000000000 --- a/desktop/angular/src/app/shared/spn-network-status/spn-network-status.html +++ /dev/null @@ -1,28 +0,0 @@ - -
    -

    Network Status

    - -
    - - Loading Network Status ... -
    -
      -
    • -
      - {{ issue.title }} - {{ issue.closed ? 'closed' : 'opened'}} by {{ issue.user }} - {{ - issue.createdAt | timeAgo - }} -
      - -
      - - -
      -
    • -
    -
    diff --git a/desktop/angular/src/app/shared/spn-network-status/spn-network-status.scss b/desktop/angular/src/app/shared/spn-network-status/spn-network-status.scss deleted file mode 100644 index 6c73c8bb0..000000000 --- a/desktop/angular/src/app/shared/spn-network-status/spn-network-status.scss +++ /dev/null @@ -1,71 +0,0 @@ -:host { - @apply block; - min-width: 500px; - width: 50vw; -} - -.issue-list { - width: 100%; - - &, - ul { - overflow-y: auto; - } - - .issue { - position: relative; - display: flex; - flex-direction: column; - cursor: pointer; - @apply mx-2; - - .header { - @apply p-4; - display: flex; - flex-direction: column; - align-items: flex-start; - justify-content: center; - cursor: pointer; - } - - @apply rounded; - @apply bg-cards-primary; - - .title { - @apply mr-4; - } - - span { - word-break: keep-all; - } - - &:not(:last-child) { - margin-bottom: 0.5rem; - } - - .body { - @apply bg-cards-secondary; - @apply rounded-b; - @apply p-4; - } - - .meta { - @apply text-tertiary; - @apply font-normal; - opacity: .7; - font-size: 95%; - } - - &:hover { - @apply bg-cards-tertiary; - } - - fa-icon { - position: absolute; - right: 1rem; - top: 1rem; - opacity: .8; - cursor: pointer; - } - } -} diff --git a/desktop/angular/src/app/shared/spn-network-status/spn-network-status.ts b/desktop/angular/src/app/shared/spn-network-status/spn-network-status.ts deleted file mode 100644 index 131c907fc..000000000 --- a/desktop/angular/src/app/shared/spn-network-status/spn-network-status.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, TrackByFunction, inject } from "@angular/core"; -import { map } from "rxjs"; -import { INTEGRATION_SERVICE } from "src/app/integration"; -import { Issue, SupportHubService } from "src/app/services"; - -/** The name of the SPN repository used to filter SPN support hub issues. */ -const SPNRepository = "spn"; - -/** A set of issue labels that are eligible to be displayed */ -const SPNTagSet = new Set(["network status"]) - -interface _Issue extends Issue { - expanded: boolean; -} - -@Component({ - selector: 'app-spn-network-status', - templateUrl: './spn-network-status.html', - styleUrls: ['./spn-network-status.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class SPNNetworkStatusComponent implements OnInit { - private readonly integration = inject(INTEGRATION_SERVICE); - private readonly supportHub = inject(SupportHubService); - private readonly cdr = inject(ChangeDetectorRef); - - /** trackIssue is used as a track-by function when rendering SPN issues. */ - trackIssue: TrackByFunction<_Issue> = (_: number, issue: _Issue) => issue.url; - - spnIssues: _Issue[] = []; - - ngOnInit(): void { - this.supportHub.loadIssues() - .pipe( - map(issues => { - return issues - .filter(issue => issue.repository === SPNRepository && issue.labels?.some(l => { - return SPNTagSet.has(l); - })) - .reverse() - }) - ) - .subscribe(issues => { - let spnIssues: _Issue[] = issues - .map(i => { - const existing = this.spnIssues.find(existing => existing.url === i.url); - return { - ...i, - expanded: existing !== undefined ? existing.expanded : false - } - }) - this.spnIssues = spnIssues; - this.cdr.markForCheck(); - }) - } - - /** - * Open a github issue in a new tab/window - * - * @private - template only - */ - openIssue(issue: Issue) { - this.integration.openExternal(issue.url); - } -} diff --git a/desktop/angular/src/app/shared/spn-status/index.ts b/desktop/angular/src/app/shared/spn-status/index.ts deleted file mode 100644 index a996c3cf8..000000000 --- a/desktop/angular/src/app/shared/spn-status/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './spn-status'; diff --git a/desktop/angular/src/app/shared/spn-status/spn-status.html b/desktop/angular/src/app/shared/spn-status/spn-status.html deleted file mode 100644 index 84006d465..000000000 --- a/desktop/angular/src/app/shared/spn-status/spn-status.html +++ /dev/null @@ -1,54 +0,0 @@ -
    - - - -
    -

    SPN

    - - - - Increase privacy protection - - - Failed to connect - - - Connecting to the SPN ... - - - You're protected - - - - - Home: {{ spnStatus?.ConnectedIP }} via {{ spnStatus?.ConnectedTransport}} - - - - - -
    - -
    -
    -
    -
    - Identities - {{ identities }} -
    -
    -
    diff --git a/desktop/angular/src/app/shared/spn-status/spn-status.ts b/desktop/angular/src/app/shared/spn-status/spn-status.ts deleted file mode 100644 index 5cc264783..000000000 --- a/desktop/angular/src/app/shared/spn-status/spn-status.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, OnInit, inject } from "@angular/core"; -import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; -import { ActivatedRoute, Router } from '@angular/router'; -import { BoolSetting, ChartResult, ConfigService, FeatureID, Netquery, SPNService, SPNStatus, UserProfile } from "@safing/portmaster-api"; -import { SfngDialogService } from '@safing/ui'; -import { catchError, forkJoin, interval, of, startWith, switchMap } from "rxjs"; -import { fadeInAnimation, fadeOutAnimation } from "../animations"; -import { SPNAccountDetailsComponent } from '../spn-account-details'; - -@Component({ - selector: 'app-spn-status', - templateUrl: './spn-status.html', - changeDetection: ChangeDetectionStrategy.OnPush, - animations: [ - fadeInAnimation, - fadeOutAnimation, - ] -}) -export class SPNStatusComponent implements OnInit { - private destroyRef = inject(DestroyRef); - - /** Whether or not the SPN is currently enabled */ - spnEnabled = false; - - /** The chart data for the SPN connection chart */ - spnConnChart: ChartResult[] = []; - - /** The current amount of SPN identities used */ - identities: number = 0; - - /** The current SPN user profile */ - profile: UserProfile | null = null; - - /** The current status of the SPN module */ - spnStatus: SPNStatus | null = null; - - /** Returns whether or not the current package has the SPN feature */ - get packageHasSPN() { - return this.profile?.current_plan?.feature_ids?.includes(FeatureID.SPN) - } - - constructor( - private configService: ConfigService, - private spnService: SPNService, - private netquery: Netquery, - private cdr: ChangeDetectorRef, - private router: Router, - private activeRoute: ActivatedRoute, - private dialog: SfngDialogService - ) { } - - ngOnInit(): void { - this.spnService - .profile$ - .pipe( - takeUntilDestroyed(this.destroyRef), - catchError(() => of(null)) - ) - .subscribe(profile => { - this.profile = profile || null; - - this.cdr.markForCheck(); - }); - - this.spnService.status$ - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(status => { - this.spnStatus = status; - - this.cdr.markForCheck(); - }) - - this.configService.watch("spn/enable") - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(value => { - this.spnEnabled = value; - - // If the user disabled the SPN clear the connection chart - // as well. - if (!this.spnEnabled) { - this.spnConnChart = []; - } - - this.cdr.markForCheck(); - }); - - interval(5000) - .pipe( - startWith(-1), - takeUntilDestroyed(this.destroyRef), - switchMap(() => forkJoin({ - chart: this.netquery.activeConnectionChart({ tunneled: { $eq: true } }), - identities: this.netquery.query({ - query: { tunneled: { $eq: true }, exit_node: { $ne: "" } }, - groupBy: ['exit_node'], - select: [ - 'exit_node', - { $count: { field: '*', as: 'totalCount' } } - ] - }, 'spn-status-get-connections-count-per-exit-node') - })) - ) - .subscribe(data => { - this.spnConnChart = data.chart; - this.identities = data.identities.length; - - this.cdr.markForCheck(); - }) - } - - openOrLogin() { - if (this.activeRoute.snapshot.firstChild?.url[0]?.path === "spn") { - this.dialog.create(SPNAccountDetailsComponent, { - autoclose: true, - backdrop: 'light' - }) - - return - } - - this.router.navigate(['/spn']) - } - - setSPNEnabled(v: boolean) { - this.configService.save(`spn/enable`, v) - .subscribe(); - } -} diff --git a/desktop/angular/src/environments/environment.prod.ts b/desktop/angular/src/environments/environment.prod.ts index ecca43425..aa9de9c5c 100644 --- a/desktop/angular/src/environments/environment.prod.ts +++ b/desktop/angular/src/environments/environment.prod.ts @@ -2,5 +2,6 @@ export const environment = { production: true, portAPI: `ws://${window.location.host}/api/database/v1`, httpAPI: `http://${window.location.host}/api`, - supportHub: "https://support.safing.io" + // Issues are opened in the browser on the project repository; nothing is sent to Safing. + issueTracker: "https://github.com/0n113/portmasterpro/issues" }; \ No newline at end of file diff --git a/desktop/angular/src/environments/environment.ts b/desktop/angular/src/environments/environment.ts index 5ef6df251..953bda963 100644 --- a/desktop/angular/src/environments/environment.ts +++ b/desktop/angular/src/environments/environment.ts @@ -6,7 +6,8 @@ export const environment = { production: false, portAPI: "ws://127.0.0.1:817/api/database/v1", httpAPI: "http://127.0.0.1:817/api", - supportHub: "https://support.safing.io" + // Issues are opened in the browser on the project repository; nothing is sent to Safing. + issueTracker: "https://github.com/0n113/portmasterpro/issues" }; /* diff --git a/desktop/angular/src/i18n/helptexts.yaml b/desktop/angular/src/i18n/helptexts.yaml index 5a1e62de8..6485e847c 100644 --- a/desktop/angular/src/i18n/helptexts.yaml +++ b/desktop/angular/src/i18n/helptexts.yaml @@ -14,7 +14,7 @@ myKey: And :rocket: emojis ### :tada: :facepalm: - url: https://docs.safing.io/?source=Portmaster + url: https://docs.safing.io/ urlText: Show me! nextKey: navMonitor @@ -58,7 +58,7 @@ navApps: title: Per-App Settings content: | Configure per-app settings which override the global default. - nextKey: navMap + nextKey: navSettings buttons: - name: Take the tour action: @@ -66,12 +66,6 @@ navApps: Payload: apps nextKey: appsTitle -navMap: - title: SPN Map - content: | - View the SPN map and see how your connections are routed. - nextKey: navSettings - navSettings: title: Global Settings content: | @@ -105,8 +99,6 @@ navPause: title: Pause and Resume content: | Temporarily disable Portmaster's protection and network monitoring. - - Choose to pause SPN only or disable all protection completely. nextKey: navPower navPower: @@ -336,12 +328,6 @@ appSettings-QuickSettings: When other settings might overwrite this, a yellow dot next to the toggle will inform you of possible exceptions. - __SPN__ - - Quickly enable or disable SPN for this app. - - When other settings might overwrite this, a yellow dot next to the toggle will inform you of possible exceptions. - __Keep History__ Save connections in a database (on disk) in order to view and search them later. @@ -361,16 +347,6 @@ support-page-related-issues: ######################### ### Configuration Options -spn: - title: Safing Privacy Network - content: | - The Safing Privacy Network (SPN) is a Portmaster Add-On that protects your identity - and Internet traffic from prying eyes. It spreads your connections over multiple server, - letting you access the Internet from many places at once in order to effectively hide - your tracks. - url: https://safing.io/spn/?source=Portmaster - urlText: Learn More - ########################### # Process Matching and Fingerprints process-tags: diff --git a/desktop/tauri/src-tauri/Cargo.lock b/desktop/tauri/src-tauri/Cargo.lock index c1283bb14..ae2664e8c 100644 --- a/desktop/tauri/src-tauri/Cargo.lock +++ b/desktop/tauri/src-tauri/Cargo.lock @@ -113,25 +113,27 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.97" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "arboard" -version = "3.4.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df099ccb16cd014ff054ac1bf392c67feeef57164b05c42f037cd40f5d4357f4" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" dependencies = [ "clipboard-win", - "core-graphics 0.23.2", "image", "log", - "objc2 0.5.2", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", + "objc2 0.6.0", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.0", "parking_lot", - "windows-sys 0.48.0", + "percent-encoding", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] @@ -572,7 +574,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad8646f98db542e39fc66e68a20b2144f6a732636df7c2354e74645faaa433ce" dependencies = [ "borsh-derive", - "cfg_aliases 0.2.1", + "cfg_aliases", ] [[package]] @@ -674,9 +676,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" -version = "1.10.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" dependencies = [ "serde", ] @@ -823,12 +825,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[package]] -name = "cfg_aliases" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" - [[package]] name = "cfg_aliases" version = "0.2.1" @@ -847,7 +843,7 @@ dependencies = [ "num-traits", "serde", "wasm-bindgen", - "windows-link", + "windows-link 0.1.1", ] [[package]] @@ -960,16 +956,6 @@ dependencies = [ "url", ] -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "core-foundation" version = "0.10.0" @@ -986,19 +972,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "core-graphics" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "core-graphics-types 0.1.3", - "foreign-types 0.5.0", - "libc", -] - [[package]] name = "core-graphics" version = "0.24.0" @@ -1006,20 +979,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" dependencies = [ "bitflags 2.9.0", - "core-foundation 0.10.0", - "core-graphics-types 0.2.0", - "foreign-types 0.5.0", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", + "core-foundation", + "core-graphics-types", + "foreign-types", "libc", ] @@ -1030,7 +992,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.9.0", - "core-foundation 0.10.0", + "core-foundation", "libc", ] @@ -1226,23 +1188,11 @@ dependencies = [ [[package]] name = "deranged" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cfac68e08048ae1883171632c2aef3ebc555621ae56fbccce1cbf22dd7f058" -dependencies = [ - "powerfmt", - "serde", -] - -[[package]] -name = "derive-new" -version = "0.6.0" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d150dea618e920167e5973d70ae6ece4385b7164e0d799fe7c122dd0a5d912ad" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.100", + "serde_core", ] [[package]] @@ -1620,15 +1570,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared 0.1.1", -] - [[package]] name = "foreign-types" version = "0.5.0" @@ -1636,7 +1577,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" dependencies = [ "foreign-types-macros", - "foreign-types-shared 0.3.1", + "foreign-types-shared", ] [[package]] @@ -1650,12 +1591,6 @@ dependencies = [ "syn 2.0.100", ] -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "foreign-types-shared" version = "0.3.1" @@ -2110,25 +2045,6 @@ dependencies = [ "syn 2.0.100", ] -[[package]] -name = "h2" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5017294ff4bb30944501348f6f8e42e6ad28f42c8bbef7a74029aff064a4e3c2" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap 2.8.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "hashbrown" version = "0.12.3" @@ -2259,7 +2175,6 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2", "http", "http-body", "httparse", @@ -2270,39 +2185,6 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-rustls" -version = "0.27.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d191583f3da1305256f22463b9bb0471acad48a4e534a5218b9963e9c1f59b2" -dependencies = [ - "futures-util", - "http", - "hyper", - "hyper-util", - "rustls 0.23.25", - "rustls-pki-types", - "tokio", - "tokio-rustls 0.26.2", - "tower-service", -] - -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" version = "0.1.11" @@ -2925,7 +2807,7 @@ dependencies = [ "gtk", "keyboard-types", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-core-foundation", "objc2-foundation 0.3.0", "once_cell", @@ -2935,23 +2817,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "native-tls" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - [[package]] name = "ndk" version = "0.9.0" @@ -2988,18 +2853,6 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" -[[package]] -name = "nix" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" -dependencies = [ - "bitflags 2.9.0", - "cfg-if", - "cfg_aliases 0.1.1", - "libc", -] - [[package]] name = "nix" version = "0.29.0" @@ -3008,7 +2861,7 @@ checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" dependencies = [ "bitflags 2.9.0", "cfg-if", - "cfg_aliases 0.2.1", + "cfg_aliases", "libc", "memoffset", ] @@ -3031,23 +2884,23 @@ dependencies = [ [[package]] name = "notify-rust" -version = "4.11.6" +version = "4.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4012c5a725bfa4cfd09c2f3abf29fb0b03a528d02787744e485c8014cdf6f1c0" +checksum = "50ff2e74231b72c832d82982193b417f230945be6bdb5575b251d941d31adb00" dependencies = [ "futures-lite", "log", "mac-notification-sys", "serde", - "tauri-winrt-notification 0.2.1", + "tauri-winrt-notification 0.7.3", "zbus", ] [[package]] name = "num-conv" -version = "0.1.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "num-traits" @@ -3073,7 +2926,7 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate 3.3.0", "proc-macro2", "quote", "syn 2.0.100", @@ -3134,22 +2987,6 @@ dependencies = [ "objc2-exception-helper", ] -[[package]] -name = "objc2-app-kit" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" -dependencies = [ - "bitflags 2.9.0", - "block2 0.5.1", - "libc", - "objc2 0.5.2", - "objc2-core-data 0.2.2", - "objc2-core-image 0.2.2", - "objc2-foundation 0.2.2", - "objc2-quartz-core 0.2.2", -] - [[package]] name = "objc2-app-kit" version = "0.3.0" @@ -3161,10 +2998,10 @@ dependencies = [ "libc", "objc2 0.6.0", "objc2-cloud-kit", - "objc2-core-data 0.3.0", + "objc2-core-data", "objc2-core-foundation", "objc2-core-graphics", - "objc2-core-image 0.3.0", + "objc2-core-image", "objc2-foundation 0.3.0", "objc2-quartz-core 0.3.0", ] @@ -3180,18 +3017,6 @@ dependencies = [ "objc2-foundation 0.3.0", ] -[[package]] -name = "objc2-core-data" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" -dependencies = [ - "bitflags 2.9.0", - "block2 0.5.1", - "objc2 0.5.2", - "objc2-foundation 0.2.2", -] - [[package]] name = "objc2-core-data" version = "0.3.0" @@ -3225,18 +3050,6 @@ dependencies = [ "objc2-io-surface", ] -[[package]] -name = "objc2-core-image" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" -dependencies = [ - "block2 0.5.1", - "objc2 0.5.2", - "objc2-foundation 0.2.2", - "objc2-metal", -] - [[package]] name = "objc2-core-image" version = "0.3.0" @@ -3355,7 +3168,7 @@ dependencies = [ "bitflags 2.9.0", "block2 0.6.0", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-core-foundation", "objc2-foundation 0.3.0", ] @@ -3396,50 +3209,6 @@ dependencies = [ "pathdiff", ] -[[package]] -name = "openssl" -version = "0.10.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8505734d46c8ab1e19a1dce3aef597ad87dcb4c37e7188231769bd6bd51cebf8" -dependencies = [ - "bitflags 2.9.0", - "cfg-if", - "foreign-types 0.3.2", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.100", -] - -[[package]] -name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - -[[package]] -name = "openssl-sys" -version = "0.9.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90096e2e47630d78b7d1c20952dc621f957103f8bc2c8359ec81290d75238571" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - [[package]] name = "option-ext" version = "0.2.0" @@ -3773,13 +3542,13 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] name = "plist" -version = "1.7.1" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac26e981c03a6e53e0aee43c113e3202f5581d5360dae7bd2c70e800dd0451d" +checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85" dependencies = [ "base64 0.22.1", "indexmap 2.8.0", - "quick-xml 0.32.0", + "quick-xml", "serde", "time", ] @@ -3814,7 +3583,7 @@ dependencies = [ [[package]] name = "portmaster" -version = "2.2.9" +version = "0.1.0-rc1" dependencies = [ "assert_matches", "bytes", @@ -3856,7 +3625,7 @@ dependencies = [ "tauri-plugin-websocket", "tauri-plugin-window-state", "tauri-runtime-wry", - "tauri-winrt-notification 0.3.1", + "tauri-winrt-notification 0.8.1", "thiserror 1.0.69", "tokio", "tokio-websockets", @@ -3993,27 +3762,9 @@ dependencies = [ [[package]] name = "quick-xml" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1004a344b30a54e2ee58d66a71b32d2db2feb0a31f9a2d302bf0536f15de2a33" -dependencies = [ - "memchr", -] - -[[package]] -name = "quick-xml" -version = "0.32.0" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d3a6e5838b60e0e8fa7a43f22ade549a37d61f8bdbe636d0d7816191de969c2" -dependencies = [ - "memchr", -] - -[[package]] -name = "quick-xml" -version = "0.37.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4ce8c88de324ff838700f36fb6ab86c96df0e3c4ab6ef3a9b2044465cce1369" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" dependencies = [ "memchr", ] @@ -4255,30 +4006,23 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2", "http", "http-body", "http-body-util", "hyper", - "hyper-rustls", - "hyper-tls", "hyper-util", "ipnet", "js-sys", "log", "mime", - "native-tls", "once_cell", "percent-encoding", "pin-project-lite", - "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", - "system-configuration", "tokio", - "tokio-native-tls", "tokio-util", "tower", "tower-service", @@ -4305,7 +4049,7 @@ dependencies = [ "js-sys", "log", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-core-foundation", "objc2-foundation 0.3.0", "raw-window-handle", @@ -4331,9 +4075,9 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.45" +version = "0.7.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9008cd6385b9e161d8229e1f6549dd23c3d022f132a2ea37ac3a10ac4935779b" +checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1" dependencies = [ "bitvec", "bytecheck", @@ -4349,9 +4093,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.45" +version = "0.7.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "503d1d27590a2b0a3a4ca4c94755aa2875657196ecbf401a42eff41d7de532c0" +checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5" dependencies = [ "proc-macro2", "quote", @@ -4452,32 +4196,26 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.25" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "822ee9188ac4ec04a2f0531e55d035fb2de73f18b41a63c70c2712503b6fb13c" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "rustls-pki-types", - "rustls-webpki 0.103.1", + "rustls-webpki 0.103.17", "subtle", "zeroize", ] [[package]] -name = "rustls-pemfile" -version = "2.2.0" +name = "rustls-pki-types" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ - "rustls-pki-types", + "zeroize", ] -[[package]] -name = "rustls-pki-types" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" - [[package]] name = "rustls-webpki" version = "0.102.8" @@ -4491,9 +4229,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.1" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fef8b8769aaccf73098557a87cd1816b4f9c7c16811c9c77142aa695c16f2c03" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -4521,15 +4259,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "schannel" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f29ebaa345f945cec9fbbc532eb307f0fdad8161f281b6369539c8d84876b3d" -dependencies = [ - "windows-sys 0.59.0", -] - [[package]] name = "schemars" version = "0.8.22" @@ -4569,29 +4298,6 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.9.0", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "selectors" version = "0.22.0" @@ -4623,10 +4329,11 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.219" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ + "serde_core", "serde_derive", ] @@ -4641,15 +4348,24 @@ dependencies = [ "typeid", ] +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + [[package]] name = "serde_derive" -version = "1.0.219" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 3.0.10", ] [[package]] @@ -4881,9 +4597,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18051cdd562e792cad055119e0cdb2cfc137e44e3987532e0f9659a77931bb08" dependencies = [ "bytemuck", - "cfg_aliases 0.2.1", - "core-graphics 0.24.0", - "foreign-types 0.5.0", + "cfg_aliases", + "core-graphics", + "foreign-types", "js-sys", "log", "objc2 0.5.2", @@ -5016,6 +4732,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -5045,27 +4772,6 @@ dependencies = [ "libc", ] -[[package]] -name = "system-configuration" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" -dependencies = [ - "bitflags 2.9.0", - "core-foundation 0.9.4", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "system-deps" version = "6.2.2" @@ -5085,8 +4791,8 @@ version = "0.32.8" source = "git+https://github.com/safing/portmaster-tauri-tao-patch?rev=205d3b80f50e577d575e2f79a9d318941cecb254#205d3b80f50e577d575e2f79a9d318941cecb254" dependencies = [ "bitflags 2.9.0", - "core-foundation 0.10.0", - "core-graphics 0.24.0", + "core-foundation", + "core-graphics", "crossbeam-channel", "dispatch", "dlopen2", @@ -5102,7 +4808,7 @@ dependencies = [ "ndk-context", "ndk-sys", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-foundation 0.3.0", "once_cell", "parking_lot", @@ -5174,7 +4880,7 @@ dependencies = [ "mime", "muda", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-foundation 0.3.0", "percent-encoding", "plist", @@ -5497,7 +5203,7 @@ dependencies = [ "jni", "log", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-foundation 0.3.0", "once_cell", "percent-encoding", @@ -5564,23 +5270,23 @@ dependencies = [ [[package]] name = "tauri-winrt-notification" -version = "0.2.1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f89f5fb70d6f62381f5d9b2ba9008196150b40b75f3068eb24faeddf1c686871" +checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade" dependencies = [ - "quick-xml 0.31.0", - "windows 0.56.0", + "thiserror 2.0.12", + "windows 0.61.1", "windows-version", ] [[package]] name = "tauri-winrt-notification" -version = "0.3.1" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36778770f6c7f9a60ec08fcd2d923915a4e9015ea36d4dde80ba573345312f0a" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" dependencies = [ - "quick-xml 0.31.0", - "windows 0.56.0", + "thiserror 2.0.12", + "windows 0.62.2", "windows-version", ] @@ -5676,32 +5382,31 @@ dependencies = [ [[package]] name = "time" -version = "0.3.41" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7619e19bc266e0f9c5e6686659d394bc57973859340060a69221e57dbc0c40" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa 1.0.15", "libc", "num-conv", "num_threads", "powerfmt", - "serde", + "serde_core", "time-core", "time-macros", ] [[package]] name = "time-core" -version = "0.1.4" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "time-macros" -version = "0.2.22" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3526739392ec93fd8b359c8e98514cb3e8e021beb4e5f597b00a0221f8ed8a49" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ "num-conv", "time-core", @@ -5770,16 +5475,6 @@ dependencies = [ "syn 2.0.100", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.25.0" @@ -5797,7 +5492,7 @@ version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" dependencies = [ - "rustls 0.23.25", + "rustls 0.23.46", "tokio", ] @@ -5809,12 +5504,12 @@ checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" dependencies = [ "futures-util", "log", - "rustls 0.23.25", + "rustls 0.23.46", "rustls-pki-types", "tokio", "tokio-rustls 0.26.2", "tungstenite", - "webpki-roots", + "webpki-roots 0.26.11", ] [[package]] @@ -5975,7 +5670,7 @@ dependencies = [ "libappindicator", "muda", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.0", @@ -6017,7 +5712,7 @@ dependencies = [ "httparse", "log", "rand 0.9.0", - "rustls 0.23.25", + "rustls 0.23.46", "rustls-pki-types", "sha1", "thiserror 2.0.12", @@ -6182,12 +5877,6 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "943ce29a8a743eb10d6082545d861b24f9d1b160b7d741e0f2cdf726bec909c5" -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "vec_map" version = "0.8.2" @@ -6352,34 +6041,34 @@ dependencies = [ [[package]] name = "wayland-backend" -version = "0.3.8" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7208998eaa3870dad37ec8836979581506e0c5c64c20c9e79e9d2a10d6f47bf" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 0.38.44", + "rustix 1.0.4", "smallvec", "wayland-sys", ] [[package]] name = "wayland-client" -version = "0.31.8" +version = "0.31.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2120de3d33638aaef5b9f4472bff75f07c56379cf76ea320bd3a3d65ecaf73f" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.9.0", - "rustix 0.38.44", + "rustix 1.0.4", "wayland-backend", "wayland-scanner", ] [[package]] name = "wayland-protocols" -version = "0.31.2" +version = "0.32.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f81f365b8b4a97f422ac0e8737c438024b5951734506b0e1d775c73030561f4" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" dependencies = [ "bitflags 2.9.0", "wayland-backend", @@ -6389,9 +6078,9 @@ dependencies = [ [[package]] name = "wayland-protocols-wlr" -version = "0.2.0" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1f61b76b6c2d8742e10f9ba5c3737f6530b4c243132c2a2ccc8aa96fe25cd6" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" dependencies = [ "bitflags 2.9.0", "wayland-backend", @@ -6402,20 +6091,20 @@ dependencies = [ [[package]] name = "wayland-scanner" -version = "0.31.6" +version = "0.31.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "896fdafd5d28145fce7958917d69f2fd44469b1d4e861cb5961bcbeebc6d1484" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml 0.37.4", + "quick-xml", "quote", ] [[package]] name = "wayland-sys" -version = "0.31.6" +version = "0.31.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbcebb399c77d5aa9fa5db874806ee7b4eba4e73650948e8f93963f128896615" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "pkg-config", ] @@ -6476,9 +6165,18 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "0.26.8" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2210b291f7ea53617fbafcc4939f10914214ec15aace5ba62293a668f322c5c9" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -6494,7 +6192,7 @@ dependencies = [ "windows 0.60.0", "windows-core 0.60.1", "windows-implement 0.59.0", - "windows-interface 0.59.1", + "windows-interface", ] [[package]] @@ -6581,7 +6279,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c" dependencies = [ "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-core-foundation", "objc2-foundation 0.3.0", "raw-window-handle", @@ -6601,25 +6299,40 @@ dependencies = [ [[package]] name = "windows" -version = "0.56.0" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddf874e74c7a99773e62b1c671427abf01a425e77c3d3fb9fb1e4883ea934529" +dependencies = [ + "windows-collections 0.1.1", + "windows-core 0.60.1", + "windows-future 0.1.1", + "windows-link 0.1.1", + "windows-numerics 0.1.1", +] + +[[package]] +name = "windows" +version = "0.61.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1de69df01bdf1ead2f4ac895dc77c9351aefff65b2f3db429a343f9cbf05e132" +checksum = "c5ee8f3d025738cb02bad7868bbb5f8a6327501e870bf51f1b455b0a2454a419" dependencies = [ - "windows-core 0.56.0", - "windows-targets 0.52.6", + "windows-collections 0.2.0", + "windows-core 0.61.0", + "windows-future 0.2.0", + "windows-link 0.1.1", + "windows-numerics 0.2.0", ] [[package]] name = "windows" -version = "0.60.0" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddf874e74c7a99773e62b1c671427abf01a425e77c3d3fb9fb1e4883ea934529" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "windows-collections", - "windows-core 0.60.1", - "windows-future", - "windows-link", - "windows-numerics", + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -6632,23 +6345,29 @@ dependencies = [ ] [[package]] -name = "windows-core" -version = "0.54.0" +name = "windows-collections" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" dependencies = [ - "windows-result 0.1.2", - "windows-targets 0.52.6", + "windows-core 0.61.0", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", ] [[package]] name = "windows-core" -version = "0.56.0" +version = "0.54.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4698e52ed2d08f8658ab0c39512a7c00ee5fe2688c65f8c0a4f06750d729f2a6" +checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" dependencies = [ - "windows-implement 0.56.0", - "windows-interface 0.56.0", "windows-result 0.1.2", "windows-targets 0.52.6", ] @@ -6660,8 +6379,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca21a92a9cae9bf4ccae5cf8368dce0837100ddf6e6d57936749e85f152f6247" dependencies = [ "windows-implement 0.59.0", - "windows-interface 0.59.1", - "windows-link", + "windows-interface", + "windows-link 0.1.1", "windows-result 0.3.2", "windows-strings 0.3.1", ] @@ -6672,13 +6391,26 @@ version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980" dependencies = [ - "windows-implement 0.60.0", - "windows-interface 0.59.1", - "windows-link", + "windows-implement 0.60.2", + "windows-interface", + "windows-link 0.1.1", "windows-result 0.3.2", "windows-strings 0.4.0", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-future" version = "0.1.1" @@ -6686,36 +6418,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a787db4595e7eb80239b74ce8babfb1363d8e343ab072f2ffe901400c03349f0" dependencies = [ "windows-core 0.60.1", - "windows-link", + "windows-link 0.1.1", ] [[package]] -name = "windows-implement" -version = "0.56.0" +name = "windows-future" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6fc35f58ecd95a9b71c4f2329b911016e6bec66b3f2e6a4aad86bd2e99e2f9b" +checksum = "7a1d6bbefcb7b60acd19828e1bc965da6fcf18a7e39490c5f8be71e54a19ba32" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.100", + "windows-core 0.61.0", + "windows-link 0.1.1", ] [[package]] -name = "windows-implement" -version = "0.59.0" +name = "windows-future" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.100", + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading", ] [[package]] name = "windows-implement" -version = "0.60.0" +version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1" dependencies = [ "proc-macro2", "quote", @@ -6723,10 +6454,10 @@ dependencies = [ ] [[package]] -name = "windows-interface" -version = "0.56.0" +name = "windows-implement" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08990546bf4edef8f431fa6326e032865f27138718c587dc21bc0265bbcb57cc" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", @@ -6735,9 +6466,9 @@ dependencies = [ [[package]] name = "windows-interface" -version = "0.59.1" +version = "0.59.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", @@ -6750,6 +6481,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-numerics" version = "0.1.1" @@ -6757,7 +6494,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "005dea54e2f6499f2cee279b8f703b3cf3b5734a2d8d21867c8f44003182eeed" dependencies = [ "windows-core 0.60.1", - "windows-link", + "windows-link 0.1.1", +] + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.0", + "windows-link 0.1.1", +] + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", ] [[package]] @@ -6786,7 +6543,16 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252" dependencies = [ - "windows-link", + "windows-link 0.1.1", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", ] [[package]] @@ -6806,7 +6572,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319" dependencies = [ - "windows-link", + "windows-link 0.1.1", ] [[package]] @@ -6815,7 +6581,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97" dependencies = [ - "windows-link", + "windows-link 0.1.1", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", ] [[package]] @@ -6916,13 +6691,22 @@ dependencies = [ "windows_x86_64_msvc 0.53.0", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-version" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e04a5c6627e310a23ad2358483286c7df260c964eb2d003d8efd6d0f4e79265c" dependencies = [ - "windows-link", + "windows-link 0.1.1", ] [[package]] @@ -7150,17 +6934,15 @@ dependencies = [ [[package]] name = "wl-clipboard-rs" -version = "0.8.1" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b41773911497b18ca8553c3daaf8ec9fe9819caf93d451d3055f69de028adb" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" dependencies = [ - "derive-new", "libc", "log", - "nix 0.28.0", "os_pipe", - "tempfile", - "thiserror 1.0.69", + "rustix 1.0.4", + "thiserror 2.0.12", "tree_magic_mini", "wayland-backend", "wayland-client", @@ -7202,7 +6984,7 @@ dependencies = [ "libc", "ndk", "objc2 0.6.0", - "objc2-app-kit 0.3.0", + "objc2-app-kit", "objc2-core-foundation", "objc2-foundation 0.3.0", "objc2-ui-kit", @@ -7326,7 +7108,7 @@ dependencies = [ "futures-core", "futures-lite", "hex", - "nix 0.29.0", + "nix", "ordered-stream", "serde", "serde_repr", diff --git a/desktop/tauri/src-tauri/Cargo.toml b/desktop/tauri/src-tauri/Cargo.toml index d1a6e6e78..cb56d2e51 100644 --- a/desktop/tauri/src-tauri/Cargo.toml +++ b/desktop/tauri/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "portmaster" -version = "2.2.9" +version = "0.1.0-rc1" description = "Portmaster UI" authors = ["Safing"] license = "" @@ -49,7 +49,9 @@ http = "1.0.0" url = "2.5.0" thiserror = "1.0" log = "0.4.21" -reqwest = { version = "0.12", features = ["cookies", "json"] } +# Only talks to the local API over plain HTTP, so no TLS backend (and no +# libssl dependency on Linux). +reqwest = { version = "0.12", default-features = false, features = ["cookies", "json", "charset"] } rfd = { version = "*", default-features = false, features = [ "tokio", "gtk3", "common-controls-v6" ] } open = "5.1.3" @@ -70,7 +72,7 @@ gio-sys = "0.18.1" [target.'cfg(target_os = "windows")'.dependencies] windows-service = "0.6.0" windows = { version = "0.54.0", features = ["Win32_Foundation", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } -tauri-winrt-notification = "0.3.0" +tauri-winrt-notification = "0.8.1" [dev-dependencies] which = "6.0.0" diff --git a/desktop/tauri/src-tauri/src/main.rs b/desktop/tauri/src-tauri/src/main.rs index e449f3eaa..d9c7f7b57 100644 --- a/desktop/tauri/src-tauri/src/main.rs +++ b/desktop/tauri/src-tauri/src/main.rs @@ -195,7 +195,7 @@ fn main() { // TODO(vladimir): Permission for logs/app2 folder are not guaranteed. Use the default location for now. #[cfg(target_os = "windows")] - let log_target = if let Some(_) = cli_args.data { + let log_target = if cli_args.data.is_some() { tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::LogDir { file_name: None }) } else { tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::Stdout) diff --git a/desktop/tauri/src-tauri/src/portapi/client.rs b/desktop/tauri/src-tauri/src/portapi/client.rs index 92688be07..d8459047a 100644 --- a/desktop/tauri/src-tauri/src/portapi/client.rs +++ b/desktop/tauri/src-tauri/src/portapi/client.rs @@ -31,6 +31,12 @@ pub struct PortAPI { dispatch: Sender, } +/// Upper bound for connecting to PortAPI (name resolution, TCP connect and WebSocket +/// handshake). The API is served on localhost, where this normally takes milliseconds; +/// callers retry on error (every 2s in portmaster::websocket), and the same 5s limit is +/// used to declare an established connection dead (pong timeout). +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + /// The map type used to store message subscribers. type SubscriberMap = RwLock>>; @@ -47,7 +53,16 @@ pub async fn connect(uri: &str) -> Result { } }; - let (mut client, _) = ClientBuilder::from_uri(parsed).connect().await?; + // Without a timeout a server that accepts the TCP connection but never answers the + // WebSocket handshake would block the caller's reconnect loop forever. + let builder = ClientBuilder::from_uri(parsed); + let (mut client, _) = match tokio::time::timeout(CONNECT_TIMEOUT, builder.connect()).await { + Ok(result) => result?, + Err(_elapsed) => { + let msg = format!("connecting timed out after {:?}", CONNECT_TIMEOUT); + return Err(Error::Io(std::io::Error::new(std::io::ErrorKind::TimedOut, msg))); + } + }; let (tx, mut dispatch) = channel::(64); tauri::async_runtime::spawn(async move { @@ -114,8 +129,25 @@ pub async fn connect(uri: &str) -> Result { continue; } - let text = unsafe { - std::str::from_utf8_unchecked(msg.as_payload()) + if msg.is_close() { + // tokio-websockets already queued the close acknowledgement; + // the next poll flushes it and yields None, which ends the + // connection above. + debug!("websocket connection closed by server"); + continue; + } + + // The Portmaster API sends binary frames, so their payload + // has to be checked for valid UTF-8 (text frames already are). + let text = match msg.as_text() { + Some(text) => text, + None => match std::str::from_utf8(msg.as_payload()) { + Ok(text) => text, + Err(err) => { + error!("dropping non-UTF-8 websocket frame: {}", err); + continue; + } + }, }; match text.parse::() { diff --git a/desktop/tauri/src-tauri/src/portapi/message.rs b/desktop/tauri/src-tauri/src/portapi/message.rs index 6230bc55c..b0ca0ade2 100644 --- a/desktop/tauri/src-tauri/src/portapi/message.rs +++ b/desktop/tauri/src-tauri/src/portapi/message.rs @@ -137,6 +137,20 @@ impl std::convert::From for String { } } +/// Reports whether messages of type `cmd` have the form `|||`. +/// +/// For the other known types everything after `||` is a single key, +/// query or message, which may contain '|' itself. +fn has_payload(cmd: &str) -> bool { + match cmd { + "del" | "error" | "warning" => false, + "success" | "done" => false, + "get" | "query" | "sub" | "qsub" | "delete" | "cancel" => false, + // "ok", "upd", "new", "create", "update", "insert" and unknown commands. + _ => true, + } +} + /// An implementation for `String::parse()` to convert a wire-format representation /// of a PortAPI message to a Message instance. /// @@ -145,7 +159,14 @@ impl std::str::FromStr for Message { type Err = MessageError; fn from_str(line: &str) -> Result { - let parts = line.split('|').collect::>(); + // Only split on the separators of the wire format: payloads (JSON), + // queries and messages may contain '|' themselves. This mirrors the Go + // side (base/api/database.go), which uses SplitN(msg, "|", 3) and, for + // messages carrying a payload, splits the rest once more into |. + // The command is always the second field. + let cmd = line.split('|').nth(1).unwrap_or(""); + let limit = if has_payload(cmd) { 4 } else { 3 }; + let parts = line.splitn(limit, '|').collect::>(); let id = match parts.first() { Some(s) => match (*s).parse::() { @@ -262,4 +283,111 @@ mod tests { panic!("unexpected error value: {}", m) } } + + fn msg(id: usize, cmd: &str, key: Option<&str>, payload: Option) -> Message { + Message { + id, + cmd: cmd.to_string(), + key: key.map(|k| k.to_string()), + payload, + } + } + + fn json(s: &str) -> Option { + Some(Payload::Json(s.to_string())) + } + + fn unknown(s: &str) -> Option { + Some(Payload::Unknown(s.to_string())) + } + + #[test] + fn parse_payload_containing_separator() { + let data = r#"{"a": 1, "s": "x|y||z|"}"#; + for cmd in ["ok", "upd", "new", "create", "update", "insert"] { + let line = format!("7|{}|some:key|J{}", cmd, data); + let m = line.parse::().expect("Expected message to parse"); + assert_eq!(m, msg(7, cmd, Some("some:key"), json(data)), "{}", line); + + // Marshaling yields the identical wire format again. + assert_eq!(String::from(m), line); + } + + let m = r#"3|ok|k|J{"a": 5, "s": "|"}"#.parse::(); + let p = m.expect("Expected message to parse").payload; + let t: Test = p.unwrap().parse().expect("Expected payload parsing to work"); + let want = Test { + a: 5, + s: "|".to_string(), + }; + assert_eq!(t, want); + } + + #[test] + fn parse_key_or_message_containing_separator() { + let text = "a|b | c|"; + for cmd in ["del", "error", "warning", "get", "query", "sub", "qsub", "delete"] { + let line = format!("9|{}|{}", cmd, text); + let m = line.parse::().expect("Expected message to parse"); + assert_eq!(m, msg(9, cmd, Some(text), None), "{}", line); + + // Marshaling yields the identical wire format again. + assert_eq!(String::from(m), line); + } + } + + #[test] + fn parse_simple_messages_unchanged() { + let k = Some("k"); + let cases = [ + ("1|ok|k|J{}", msg(1, "ok", k, json("{}"))), + ("2|upd|k|J{}", msg(2, "upd", k, json("{}"))), + ("3|new|k|J{}", msg(3, "new", k, json("{}"))), + ("4|del|k", msg(4, "del", k, None)), + ("5|success", msg(5, "success", None, None)), + ("6|error|boom", msg(6, "error", Some("boom"), None)), + ("7|warning|careful", msg(7, "warning", Some("careful"), None)), + ("8|done", msg(8, "done", None, None)), + ("9|get|k", msg(9, "get", k, None)), + ("10|query|q", msg(10, "query", Some("q"), None)), + ("11|sub|q", msg(11, "sub", Some("q"), None)), + ("12|qsub|q", msg(12, "qsub", Some("q"), None)), + ("13|create|k|J{}", msg(13, "create", k, json("{}"))), + ("14|update|k|J{}", msg(14, "update", k, json("{}"))), + ("15|insert|k|J{}", msg(15, "insert", k, json("{}"))), + ("16|delete|k", msg(16, "delete", k, None)), + ("17|cancel", msg(17, "cancel", None, None)), + ("18|ok|k|xraw", msg(18, "ok", k, unknown("xraw"))), + ("19|ok|k|", msg(19, "ok", k, unknown(""))), + ("20|ok|k", msg(20, "ok", k, None)), + ("21|ok", msg(21, "ok", None, None)), + ("22|foo|k|p", msg(22, "foo", k, unknown("p"))), + ("23|", msg(23, "", None, None)), + ]; + + for (line, want) in cases { + let m = line.parse::().expect("Expected message to parse"); + assert_eq!(m, want, "{}", line); + } + + let m = "x|ok|k|J{}".parse::(); + if let Err(MessageError::InvalidID) = m { + } else { + panic!("unexpected result: {:?}", m) + } + } + + #[test] + fn response_with_separator_in_payload_or_message() { + use super::super::types::Response; + + let m = r#"1|upd|core:status|J{"msg":"a|b"}"#.parse::(); + let r: Response = m.unwrap().try_into().unwrap(); + let want = Payload::Json(r#"{"msg":"a|b"}"#.to_string()); + assert_eq!(r, Response::Update("core:status".to_string(), want)); + + let m = "2|error|bad request: x|y".parse::(); + let r: Response = m.unwrap().try_into().unwrap(); + assert_eq!(r, Response::Error("bad request: x|y".to_string())); + } } diff --git a/desktop/tauri/src-tauri/src/portapi/models/config.rs b/desktop/tauri/src-tauri/src/portapi/models/config.rs deleted file mode 100644 index 72b8a1d87..000000000 --- a/desktop/tauri/src-tauri/src/portapi/models/config.rs +++ /dev/null @@ -1,18 +0,0 @@ -use super::super::message::Payload; -use serde::*; - -#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] -pub struct BooleanValue { - #[serde(rename = "Value")] - pub value: Option, -} - -impl TryInto for BooleanValue { - type Error = serde_json::Error; - - fn try_into(self) -> Result { - let str = serde_json::to_string(&self)?; - - Ok(Payload::Json(str)) - } -} diff --git a/desktop/tauri/src-tauri/src/portapi/models/mod.rs b/desktop/tauri/src-tauri/src/portapi/models/mod.rs index 08f5e5554..2cc9f5fd3 100644 --- a/desktop/tauri/src-tauri/src/portapi/models/mod.rs +++ b/desktop/tauri/src-tauri/src/portapi/models/mod.rs @@ -1,4 +1,2 @@ -pub mod config; -pub mod spn; pub mod notification; pub mod system_status_types; \ No newline at end of file diff --git a/desktop/tauri/src-tauri/src/portapi/models/spn.rs b/desktop/tauri/src-tauri/src/portapi/models/spn.rs deleted file mode 100644 index 549c2e27f..000000000 --- a/desktop/tauri/src-tauri/src/portapi/models/spn.rs +++ /dev/null @@ -1,8 +0,0 @@ -use serde::*; - - -#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] -pub struct SPNStatus { - #[serde(rename = "Status")] - pub status: String, -} \ No newline at end of file diff --git a/desktop/tauri/src-tauri/src/portmaster/commands.rs b/desktop/tauri/src-tauri/src/portmaster/commands.rs index fcad32ed0..5f724b125 100644 --- a/desktop/tauri/src-tauri/src/portmaster/commands.rs +++ b/desktop/tauri/src-tauri/src/portmaster/commands.rs @@ -121,7 +121,7 @@ pub fn get_app_info( ) -> Result { let mut id = response_id; - if id == "" { + if id.is_empty() { id = uuid::Uuid::new_v4().to_string() } let cloned = id.clone(); diff --git a/desktop/tauri/src-tauri/src/portmaster/mod.rs b/desktop/tauri/src-tauri/src/portmaster/mod.rs index 7ae74c8c9..f32b9e6e6 100644 --- a/desktop/tauri/src-tauri/src/portmaster/mod.rs +++ b/desktop/tauri/src-tauri/src/portmaster/mod.rs @@ -24,7 +24,7 @@ pub mod websocket; mod notifications; use crate::portapi::{ - client::PortAPI, message::Payload, models::config::BooleanValue, types::Request, + client::PortAPI, }; use std::{ collections::HashMap, @@ -187,23 +187,6 @@ impl PortmasterInterface { } } - /// Enables or disables the SPN. - pub fn set_spn_enabled(&self, enabled: bool) { - if let Some(api) = self.get_api() { - let body: Result = BooleanValue { - value: Some(enabled), - } - .try_into(); - - if let Ok(payload) = body { - tauri::async_runtime::spawn(async move { - _ = api - .request(Request::Update("config:spn/enable".to_string(), payload)) - .await; - }); - } - } - } /// Send Shutdown request to portmaster pub fn trigger_shutdown(&self) { @@ -242,7 +225,6 @@ impl PortmasterInterface { }); } - pub fn set_pause(&self, duration_seconds: u64, spn_only: bool) { tauri::async_runtime::spawn(async move { let client = reqwest::Client::new(); diff --git a/desktop/tauri/src-tauri/src/portmaster/notifications.rs b/desktop/tauri/src-tauri/src/portmaster/notifications.rs index 3860a562f..b56c901a9 100644 --- a/desktop/tauri/src-tauri/src/portmaster/notifications.rs +++ b/desktop/tauri/src-tauri/src/portmaster/notifications.rs @@ -123,7 +123,7 @@ pub async fn show_notification(cli: &PortAPI, key: String, n: Notification) { } { let cli = cli.clone(); - toast = toast.on_activated(move |action| -> windows::core::Result<()> { + toast = toast.on_activated(move |action| { if let Some(value) = action { let cli = cli.clone(); let key = key.clone(); diff --git a/desktop/tauri/src-tauri/src/service/systemd.rs b/desktop/tauri/src-tauri/src/service/systemd.rs index 169070ada..c215476c9 100644 --- a/desktop/tauri/src-tauri/src/service/systemd.rs +++ b/desktop/tauri/src-tauri/src/service/systemd.rs @@ -9,6 +9,7 @@ use std::{ }; static SYSTEMCTL: &str = "systemctl"; +static SERVICE_UNIT: &str = "portmaster.service"; // TODO(ppacher): add support for kdesudo and gksudo enum SudoCommand { @@ -66,11 +67,8 @@ impl SystemdServiceManager { ); } Err(err) => { - error!( - "failed to check systemctl binary at {}: {}", - path, - err - ); + // Most systems have systemctl in only one of the paths. + debug!("no systemctl binary at {}: {}", path, err); continue; } @@ -85,75 +83,25 @@ impl SystemdServiceManager { impl ServiceManager for SystemdServiceManager { fn status(&self) -> super::Result { - let name = "portmaster.service"; - let result = systemctl("is-active", name, false); - - match result { - // If `systemctl is-active` returns without an error code and stdout matches "active" (just to guard againt - // unhandled cases), the service can be considered running. - Ok(stdout) => { - let mut copy = stdout.to_owned(); - trim_newline(&mut copy); - - if copy != "active" { - // make sure the output is as we expected - Err(ServiceManagerError::Other(ExitStatus::default(), stdout)) - } else { - Ok(StatusResult::Running) - } - } - - Err(e) => { - if let ServiceManagerError::Other(_err, ref output) = e { - let mut copy = output.to_owned(); - trim_newline(&mut copy); - - if copy == "inactive" { - return Ok(StatusResult::Stopped); - } - } else { - error!("failed to run 'systemctl is-active': {}", e); - } - - // Failed to check if the unit is running - match systemctl("cat", name, false) { - // "systemctl cat" seems to no have stable exit codes so we need - // to check the output if it looks like "No files found for yyyy.service" - // At least, the exit code are not documented for systemd v255 (newest at the time of writing) - Err(ServiceManagerError::Other(status, msg)) => { - if msg.contains("No files found for") { - Ok(StatusResult::NotFound) - } else { - Err(ServiceManagerError::Other(status, msg)) - } - } - - // Any other error type means something went completely wrong while running systemctl altogether. - Err(e) => Err(e), - - // Fine, systemctl cat worked so if the output is "inactive" we know the service is installed - // but stopped. - Ok(_) => { - // Unit seems to be installed so check the output of result - let mut stderr = e.to_string(); - trim_newline(&mut stderr); - - if stderr == "inactive" { - Ok(StatusResult::Stopped) - } else { - Err(e) - } - } - } - } + // `systemctl show` exits with 0 for units that do not exist, unlike + // `is-active`, which prints "inactive" for them as well. + let output = run( + false, + SYSTEMCTL, + vec!["show", "-p", "LoadState", "-p", "ActiveState", SERVICE_UNIT], + )?; + if !output.status.success() { + return Err(output.into()); } + + let stdout = String::from_utf8(output.stdout)?; + parse_show_status(&stdout) + .ok_or_else(|| ServiceManagerError::Other(ExitStatus::default(), stdout)) } fn start(&self) -> Result { - let name = "portmaster.service"; - // This time we need to run as root through pkexec or similar binaries like kdesudo/gksudo. - systemctl("start", name, true)?; + systemctl("start", SERVICE_UNIT, true)?; // Check the status again to be sure it's started now self.status() @@ -189,23 +137,18 @@ fn run<'a>(root: bool, cmd: &'a str, args: Vec<&'a str>) -> std::io::Result { - match cmd { - SudoCommand::Pkexec => { - // disable the internal text-based prompt agent from pkexec because it won't work anyway. - args.insert(0, "--disable-internal-agent"); - Command::new("/usr/bin/pkexec") - } - SudoCommand::Gksu => { - args.insert(0, "--message=Please enter your password:"); - args.insert(1, "--sudo-mode"); - - Command::new("/usr/bin/gksudo") - } - } + match get_sudo_cmd()? { + SudoCommand::Pkexec => { + // disable the internal text-based prompt agent from pkexec because it won't work anyway. + args.insert(0, "--disable-internal-agent"); + Command::new("/usr/bin/pkexec") + } + SudoCommand::Gksu => { + args.insert(0, "--message=Please enter your password:"); + args.insert(1, "--sudo-mode"); + + Command::new("/usr/bin/gksudo") } - Err(err) => return Err(err), } } false => Command::new(cmd), @@ -221,13 +164,28 @@ fn run<'a>(root: bool, cmd: &'a str, args: Vec<&'a str>) -> std::io::Result Option { + let mut load_state = None; + let mut active_state = None; + for line in output.lines() { + match line.trim().split_once('=') { + Some(("LoadState", value)) => load_state = Some(value), + Some(("ActiveState", value)) => active_state = Some(value), + _ => {} } } + + if load_state? == "not-found" { + return Some(StatusResult::NotFound); + } + match active_state? { + "active" | "reloading" | "refreshing" => Some(StatusResult::Running), + // inactive, failed, activating, deactivating, maintenance: the + // service is installed but not (yet) serving. + _ => Some(StatusResult::Stopped), + } } fn get_sudo_cmd() -> std::result::Result { @@ -244,3 +202,26 @@ fn get_sudo_cmd() -> std::result::Result { "failed to detect sudo command", )) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn show_status() { + let cases = [ + ("LoadState=loaded\nActiveState=active\n", Some(StatusResult::Running)), + ("ActiveState=reloading\nLoadState=loaded\n", Some(StatusResult::Running)), + ("LoadState=loaded\nActiveState=inactive\n", Some(StatusResult::Stopped)), + ("LoadState=loaded\nActiveState=failed\n", Some(StatusResult::Stopped)), + ("LoadState=loaded\nActiveState=activating\n", Some(StatusResult::Stopped)), + ("LoadState=not-found\nActiveState=inactive\n", Some(StatusResult::NotFound)), + ("LoadState=masked\nActiveState=inactive\n", Some(StatusResult::Stopped)), + ("LoadState=loaded\n", None), + ("", None), + ]; + for (output, want) in cases { + assert_eq!(parse_show_status(output), want, "output: {output:?}"); + } + } +} diff --git a/desktop/tauri/src-tauri/src/service/windows_service.rs b/desktop/tauri/src-tauri/src/service/windows_service.rs index 2146cc418..ae6cf69c0 100644 --- a/desktop/tauri/src-tauri/src/service/windows_service.rs +++ b/desktop/tauri/src-tauri/src/service/windows_service.rs @@ -48,7 +48,7 @@ impl WindowsServiceManager { } fn open_service(&mut self) -> super::Result { - if let None = self.manager { + if self.manager.is_none() { self.init_manager()?; } @@ -64,16 +64,16 @@ impl WindowsServiceManager { return Ok(true); } - return Err(super::ServiceManagerError::WindowsError( + Err(super::ServiceManagerError::WindowsError( "failed to initialize manager".to_string(), - )); + )) } } impl super::ServiceManager for Arc> { fn status(&self) -> super::Result { if let Ok(mut manager) = self.lock() { - if let None = manager.service { + if manager.service.is_none() { // Try to open service if !manager.open_service()? { // Service is not installed. @@ -111,8 +111,9 @@ impl super::ServiceManager for Arc> { fn start(&self) -> super::Result { if let Ok(mut service_manager) = self.lock() { // Check if service is installed. - if let None = &service_manager.service { - if let Err(_) = service_manager.open_service() { + if service_manager.service.is_none() { + // Not installed (Ok(false)) or the service manager is unavailable. + if !service_manager.open_service().unwrap_or(false) { return Ok(super::status::StatusResult::NotFound); } } @@ -149,19 +150,19 @@ impl super::ServiceManager for Arc> { // Timeout starting the service. return Ok(super::status::StatusResult::Stopped); } - return Err(super::ServiceManagerError::WindowsError( + Err(super::ServiceManagerError::WindowsError( "failed to start service".to_string(), - )); + )) } } fn windows_to_manager_err(err: windows_service::Error) -> super::ServiceManagerError { if let windows_service::Error::Winapi(_) = err { // Winapi does not contain the full error. Get the actual error from windows. - return super::ServiceManagerError::WindowsError( + super::ServiceManagerError::WindowsError( windows::core::Error::from_win32().to_string(), // Internally will call `GetLastError()` and parse the result. - ); + ) } else { - return super::ServiceManagerError::WindowsError(err.to_string()); + super::ServiceManagerError::WindowsError(err.to_string()) } } diff --git a/desktop/tauri/src-tauri/src/traymenu.rs b/desktop/tauri/src-tauri/src/traymenu.rs index 879da98a6..7219e2a2e 100644 --- a/desktop/tauri/src-tauri/src/traymenu.rs +++ b/desktop/tauri/src-tauri/src/traymenu.rs @@ -1,7 +1,5 @@ use std::ops::Deref; -use std::sync::atomic::AtomicBool; use std::sync::RwLock; -use std::{sync::atomic::Ordering}; use chrono::{DateTime, Local}; use log::{debug, error}; @@ -19,8 +17,6 @@ use crate::{ client::PortAPI, message::{ParseError}, models::{ - config::BooleanValue, - spn::SPNStatus, system_status_types::{self, SystemStatus}, }, types::{Request, Response}, @@ -33,7 +29,6 @@ use tauri_plugin_dialog::{DialogExt, MessageDialogButtons}; pub type AppIcon = TrayIcon; pub type ContextMenu = Menu; -static SPN_STATE: AtomicBool = AtomicBool::new(false); #[derive(Copy, Clone)] enum IconColor { @@ -47,8 +42,6 @@ static CURRENT_ICON_COLOR: RwLock = RwLock::new(IconColor::Red); pub static USER_THEME: RwLock = RwLock::new(dark_light::Mode::Unspecified); const OPEN_KEY: &str = "open"; const EXIT_UI_KEY: &str = "exit_ui"; -const SPN_STATUS_KEY: &str = "spn_status"; -const SPN_BUTTON_KEY: &str = "spn_toggle"; const GLOBAL_STATUS_KEY: &str = "global_status"; const SHUTDOWN_KEY: &str = "shutdown"; const SYSTEM_THEME_KEY: &str = "system_theme"; @@ -60,9 +53,6 @@ const FORCE_SHOW_KEY: &str = "force-show"; const PM_TRAY_ICON_ID: &str = "pm_icon"; const PM_TRAY_MENU_ID: &str = "pm_tray_menu"; -const PAUSE_SPN_5_KEY: &str = "pause_spn_5"; -const PAUSE_SPN_15_KEY: &str = "pause_spn_15"; -const PAUSE_SPN_60_KEY: &str = "pause_spn_60"; const PAUSE_PM_5_KEY: &str = "pause_pm_5"; const PAUSE_PM_15_KEY: &str = "pause_pm_15"; const PAUSE_PM_60_KEY: &str = "pause_pm_60"; @@ -144,7 +134,6 @@ fn get_icon(icon: IconColor) -> &'static [u8] { fn build_tray_menu( app: &tauri::AppHandle, status: &str, - spn_status_text: &str, pause_info: &system_status_types::PauseInfo, ) -> core::result::Result> { load_theme(app); @@ -192,19 +181,7 @@ fn build_tray_menu( (None, None, None) }; - // SPN button - let (spn_enabled, spn_button_text ) = match spn_status_text { - "disabled" => { (false, "Enable SPN") } - _ => { (true, "Disable SPN") }, - }; - - let spn_status = MenuItemBuilder::with_id(SPN_STATUS_KEY, format!("SPN: {}", spn_status_text)) - .enabled(false) - .build(app) - .unwrap(); - let spn_button = MenuItemBuilder::with_id(SPN_BUTTON_KEY, spn_button_text) - .build(app) - .unwrap(); + // portmasterpro: SPN has been removed; no SPN status or toggle in the tray. // Setup Icon theme submenu let system_theme = MenuItemBuilder::with_id(SYSTEM_THEME_KEY, "System") @@ -222,36 +199,17 @@ fn build_tray_menu( // Setup Pause/Resume menu items - let disabled_spn_pause = (!spn_enabled && !pause_info.spn) || pause_info.interception; - let pause_spn_5min_item = MenuItemBuilder::with_id(PAUSE_SPN_5_KEY, "Pause SPN for 5 minutes").enabled(!disabled_spn_pause).build(app)?; - let pause_spn_15min_item = MenuItemBuilder::with_id(PAUSE_SPN_15_KEY, "Pause SPN for 15 minutes").enabled(!disabled_spn_pause).build(app)?; - let pause_spn_1hour_item = MenuItemBuilder::with_id(PAUSE_SPN_60_KEY, "Pause SPN for 1 hour").enabled(!disabled_spn_pause).build(app)?; - let pause_pm_5min_item = MenuItemBuilder::with_id(PAUSE_PM_5_KEY, "Pause for 5 minutes").build(app)?; let pause_pm_15min_item = MenuItemBuilder::with_id(PAUSE_PM_15_KEY, "Pause for 15 minutes").build(app)?; let pause_pm_1hour_item = MenuItemBuilder::with_id(PAUSE_PM_60_KEY, "Pause for 1 hour").build(app)?; - let pause_menu = if !spn_enabled && !pause_info.spn { - SubmenuBuilder::new(app, "Pause") - .items(&[ - &pause_pm_5min_item, - &pause_pm_15min_item, - &pause_pm_1hour_item, - ]) - .build()? - } else { - SubmenuBuilder::new(app, "Pause") - .items(&[ - &pause_spn_5min_item, - &pause_spn_15min_item, - &pause_spn_1hour_item, - &PredefinedMenuItem::separator(app)?, - &pause_pm_5min_item, - &pause_pm_15min_item, - &pause_pm_1hour_item, - ]) - .build()? - }; + let pause_menu = SubmenuBuilder::new(app, "Pause") + .items(&[ + &pause_pm_5min_item, + &pause_pm_15min_item, + &pause_pm_1hour_item, + ]) + .build()?; /* DEV MENU let force_show_window = MenuItemBuilder::with_id(FORCE_SHOW_KEY, "Force Show UI").build(app)?; @@ -282,10 +240,6 @@ fn build_tray_menu( items.push(&pause_menu); items.push(&s); - items.push(&spn_status); - items.push(&spn_button); - items.push(&s); - items.push(&theme_menu); items.push(&s); @@ -306,7 +260,7 @@ fn build_tray_menu( pub fn setup_tray_menu( app: &mut tauri::App, ) -> core::result::Result> { - let menu = build_tray_menu(app.handle(), "unknown", "disabled", &system_status_types::PauseInfo::default())?; + let menu = build_tray_menu(app.handle(), "unknown", &system_status_types::PauseInfo::default())?; let icon = TrayIconBuilder::with_id(PM_TRAY_ICON_ID) .icon(Image::from_bytes(get_red_icon()).unwrap()) @@ -349,13 +303,6 @@ pub fn setup_tray_menu( } }; } - SPN_BUTTON_KEY => { - if SPN_STATE.load(Ordering::Acquire) { - app.portmaster().set_spn_enabled(false); - } else { - app.portmaster().set_spn_enabled(true); - } - } SHUTDOWN_KEY => { app.portmaster().trigger_shutdown(); } @@ -363,9 +310,6 @@ pub fn setup_tray_menu( DARK_THEME_KEY => update_icon_theme(app, dark_light::Mode::Dark), LIGHT_THEME_KEY => update_icon_theme(app, dark_light::Mode::Light), - PAUSE_SPN_5_KEY => app.portmaster().set_pause(60*5, true), - PAUSE_SPN_15_KEY => app.portmaster().set_pause(60*15, true), - PAUSE_SPN_60_KEY => app.portmaster().set_pause(60*60, true), PAUSE_PM_5_KEY => app.portmaster().set_pause(60*5, false), PAUSE_PM_15_KEY => app.portmaster().set_pause(60*15, false), PAUSE_PM_60_KEY => app.portmaster().set_pause(60*60, false), @@ -396,7 +340,7 @@ pub fn setup_tray_menu( Ok(icon) } -pub fn update_icon(icon: AppIcon, system_status: SystemStatus, spn_status: String) { +pub fn update_icon(icon: AppIcon, system_status: SystemStatus) { // Extract the worst state type let worst_state_type = system_status.worst_state .as_ref() @@ -407,13 +351,7 @@ pub fn update_icon(icon: AppIcon, system_status: SystemStatus, spn_status: Strin let (status, icon_color) = match worst_state_type { system_status_types::StateType::Error => ("Insecure", IconColor::Red), system_status_types::StateType::Warning => ("Insecure", IconColor::Yellow), - _ => { - let color = match spn_status.as_str() { - "connected" | "connecting" => IconColor::Blue, - _ => IconColor::Green, - }; - ("Secured", color) - } + _ => ("Secured", IconColor::Green), }; // Extract pause info from system status @@ -424,7 +362,7 @@ pub fn update_icon(icon: AppIcon, system_status: SystemStatus, spn_status: Strin .unwrap_or_default(); // Rebuild and set the tray menu - if let Ok(menu) = build_tray_menu(icon.app_handle(), status, spn_status.as_str(), &pause_info) { + if let Ok(menu) = build_tray_menu(icon.app_handle(), status, &pause_info) { if let Err(err) = icon.set_menu(Some(menu)) { error!("failed to set menu on tray icon: {}", err); } @@ -458,38 +396,6 @@ pub async fn tray_handler(cli: PortAPI, app: tauri::AppHandle) { } }; - let mut spn_status_subscription = match cli - .request(Request::QuerySubscribe( - "query runtime:spn/status".to_string(), - )) - .await - { - Ok(rx) => rx, - Err(err) => { - error!( - "cancel try_handler: failed to subscribe to 'runtime:spn/status': {}", - err - ); - return; - } - }; - - let mut spn_config_subscription = match cli - .request(Request::QuerySubscribe( - "query config:spn/enable".to_string(), - )) - .await - { - Ok(rx) => rx, - Err(err) => { - error!( - "cancel try_handler: failed to subscribe to 'runtime:spn/enable': {}", - err - ); - return; - } - }; - let mut portmaster_shutdown_event_subscription = match cli .request(Request::Subscribe( "query runtime:modules/core/event/shutdown".to_string(), @@ -525,7 +431,6 @@ pub async fn tray_handler(cli: PortAPI, app: tauri::AppHandle) { update_icon_color(&icon, IconColor::Blue); let mut system_status = SystemStatus::default(); - let mut spn_status: String = "".to_string(); loop { tokio::select! { @@ -546,7 +451,7 @@ pub async fn tray_handler(cli: PortAPI, app: tauri::AppHandle) { match payload.parse::() { Ok(system_status_update) => { system_status.clone_from(&system_status_update); - update_icon(icon.clone(), system_status.clone(), spn_status.clone()); + update_icon(icon.clone(), system_status.clone()); }, Err(err) => match err { ParseError::Json(err) => { @@ -559,66 +464,6 @@ pub async fn tray_handler(cli: PortAPI, app: tauri::AppHandle) { } } }, - msg = spn_status_subscription.recv() => { - let msg = match msg { - Some(m) => m, - None => { break } - }; - - let res = match msg { - Response::Ok(key, payload) => Some((key, payload)), - Response::New(key, payload) => Some((key, payload)), - Response::Update(key, payload) => Some((key, payload)), - _ => None, - }; - - if let Some((_, payload)) = res { - match payload.parse::() { - Ok(value) => { - debug!("SPN status update: {}", value.status); - spn_status.clone_from(&value.status); - update_icon(icon.clone(), system_status.clone(), spn_status.clone()); - }, - Err(err) => match err { - ParseError::Json(err) => { - error!("failed to parse spn status value: {}", err) - }, - _ => { - error!("unknown error when parsing spn status value") - } - } - } - } - }, - msg = spn_config_subscription.recv() => { - let msg = match msg { - Some(m) => m, - None => { break } - }; - - let res = match msg { - Response::Ok(key, payload) => Some((key, payload)), - Response::New(key, payload) => Some((key, payload)), - Response::Update(key, payload) => Some((key, payload)), - _ => None, - }; - - if let Some((_, payload)) = res { - match payload.parse::() { - Ok(value) => { - SPN_STATE.store(value.value.unwrap_or(false), Ordering::Release); - }, - Err(err) => match err { - ParseError::Json(err) => { - error!("failed to parse config value: {}", err) - }, - _ => { - error!("unknown error when parsing config value") - } - } - } - } - }, msg = portmaster_shutdown_event_subscription.recv() => { let msg = match msg { Some(m) => m, @@ -659,7 +504,7 @@ pub async fn tray_handler(cli: PortAPI, app: tauri::AppHandle) { pub fn update_icon_nostate(icon: AppIcon) { update_icon_color(&icon, IconColor::Red); - if let Ok(menu) = build_tray_menu(icon.app_handle(), "unknown", "unknown", &system_status_types::PauseInfo::default()) { + if let Ok(menu) = build_tray_menu(icon.app_handle(), "unknown", &system_status_types::PauseInfo::default()) { if let Err(err) = icon.set_menu(Some(menu)) { error!("failed to set menu on tray icon: {}", err); } diff --git a/desktop/tauri/src-tauri/src/xdg/mod.rs b/desktop/tauri/src-tauri/src/xdg/mod.rs index 90f480764..6c74c6801 100644 --- a/desktop/tauri/src-tauri/src/xdg/mod.rs +++ b/desktop/tauri/src-tauri/src/xdg/mod.rs @@ -70,11 +70,26 @@ impl std::fmt::Display for ProcessInfo { } } +/// Returns the key under which the lookup result for a process is cached. +/// +/// The lookup uses the executable path, the command line and the matching path, +/// so all three are part of the key. Keying on the executable path alone made +/// processes that share a launcher, like `/usr/bin/bwrap` for every flatpak, +/// share one result, so all flatpaks got the icon of whichever app was looked +/// up first. +fn cache_key(process_info: &ProcessInfo) -> String { + format!( + "{}\0{}\0{}", + process_info.exec_path, process_info.cmdline, process_info.matching_path + ) +} + pub fn get_app_info(process_info: ProcessInfo) -> Result { + let key = cache_key(&process_info); { let cache = APP_INFO_CACHE.read().unwrap(); - if let Some(value) = cache.get(process_info.exec_path.as_str()) { + if let Some(value) = cache.get(key.as_str()) { match value { Some(app_info) => return Ok(app_info.clone()), None => { @@ -141,12 +156,12 @@ pub fn get_app_info(process_info: ProcessInfo) -> Result { APP_INFO_CACHE .write() .unwrap() - .insert(process_info.exec_path, None); + .insert(key, None); Err(Error::new(ErrorKind::NotFound, "failed to find app info".to_string()).into()) } else { // sort matches by length - matches.sort_by(|a, b| a.1.cmp(&b.1)); + matches.sort_by_key(|m| m.1); for mut info in matches { match get_icon_as_png_dataurl(&info.0.icon_name, 32) { @@ -161,7 +176,7 @@ pub fn get_app_info(process_info: ProcessInfo) -> Result { APP_INFO_CACHE .write() .unwrap() - .insert(process_info.exec_path, Some(info.0.clone())); + .insert(key, Some(info.0.clone())); return Ok(info.0); } @@ -515,6 +530,27 @@ mod tests { gtk::init().expect("failed to initialize GTK for tests") } + #[test] + fn test_cache_key_separates_apps_with_a_shared_launcher() { + let steam = ProcessInfo { + exec_path: "/usr/bin/bwrap".to_string(), + cmdline: "bwrap --args 81 -- /app/bin/steam".to_string(), + pid: 1, + matching_path: "/app/bin/steam".to_string(), + }; + let telegram = ProcessInfo { + exec_path: "/usr/bin/bwrap".to_string(), + cmdline: "bwrap --args 42 -- /app/bin/Telegram".to_string(), + pid: 2, + matching_path: "/app/bin/Telegram".to_string(), + }; + assert_ne!(cache_key(&steam), cache_key(&telegram)); + + // The pid does not take part in the lookup, so it must not split the cache. + let steam_again = ProcessInfo { pid: 3, ..steam.clone() }; + assert_eq!(cache_key(&steam), cache_key(&steam_again)); + } + #[test] fn test_find_info_success() { // we expect at least one of the following binaries to be installed diff --git a/go.mod b/go.mod index 56cde87d2..24bc062fd 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/safing/portmaster go 1.26.0 -toolchain go1.26.3 +toolchain go1.27.4 require ( github.com/VictoriaMetrics/metrics v1.40.2 @@ -14,9 +14,9 @@ require ( github.com/awalterschulze/gographviz v2.0.3+incompatible github.com/bluele/gcache v0.0.2 github.com/brianvoe/gofakeit v3.18.0+incompatible - github.com/cilium/ebpf v0.20.0 + github.com/cilium/ebpf v0.22.0 github.com/coreos/go-iptables v0.8.0 - github.com/davecgh/go-spew v1.1.1 + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc github.com/dgraph-io/badger v1.6.2 github.com/florianl/go-conntrack v0.4.0 github.com/florianl/go-nfqueue v1.3.2 @@ -39,6 +39,7 @@ require ( github.com/maruel/panicparse/v2 v2.5.0 github.com/mattn/go-colorable v0.1.15 github.com/mattn/go-isatty v0.0.24 + github.com/mdlayher/netlink v1.8.0 github.com/miekg/dns v1.1.72 github.com/mitchellh/copystructure v1.2.0 github.com/mitchellh/go-server-timing v1.0.1 @@ -66,7 +67,7 @@ require ( github.com/vincent-petithory/dataurl v1.0.0 go.etcd.io/bbolt v1.4.3 golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297 - golang.org/x/image v0.33.0 + golang.org/x/image v0.41.0 golang.org/x/net v0.58.0 golang.org/x/sync v0.22.0 golang.org/x/sys v0.47.0 @@ -127,7 +128,6 @@ require ( github.com/mattn/go-oci8 v0.1.1 // indirect github.com/mattn/go-runewidth v0.0.9 // indirect github.com/mattn/go-sqlite3 v1.14.19 // indirect - github.com/mdlayher/netlink v1.8.0 // indirect github.com/mdlayher/socket v0.5.1 // indirect github.com/mitchellh/cli v1.1.5 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect @@ -135,7 +135,7 @@ require ( github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/posener/complete v1.2.3 // indirect github.com/qdm12/reprint v0.0.0-20200326205758-722754a53494 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect diff --git a/go.sum b/go.sum index ca3a91eea..688caa9b9 100644 --- a/go.sum +++ b/go.sum @@ -56,8 +56,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cilium/ebpf v0.5.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA= -github.com/cilium/ebpf v0.20.0 h1:atwWj9d3NffHyPZzVlx3hmw1on5CLe9eljR8VuHTwhM= -github.com/cilium/ebpf v0.20.0/go.mod h1:pzLjFymM+uZPLk/IXZUL63xdx5VXEo+enTzxkZXdycw= +github.com/cilium/ebpf v0.22.0 h1:v2ktp0roffpMOj2MMf3idtCQZOsAoC4BJbAJN+ke2bY= +github.com/cilium/ebpf v0.22.0/go.mod h1:CDzZbe2hC5JjlDC+CY3KFCzlYwN4gbxppYM+Z10bQt4= github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo= github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= @@ -81,8 +81,9 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/denisenkom/go-mssqldb v0.9.0 h1:RSohk2RsiZqLZ0zCjtfn3S4Gp4exhpBWHyQ7D0yGjAk= github.com/denisenkom/go-mssqldb v0.9.0/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= github.com/dgraph-io/badger v1.6.2 h1:mNw0qs90GVgGGWylh0umH5iag1j6n/PeJtNvL6KY/x8= @@ -373,8 +374,9 @@ github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/9 github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= @@ -388,8 +390,8 @@ github.com/r3labs/diff/v3 v3.0.2 h1:yVuxAY1V6MeM4+HNur92xkS39kB/N+cFi2hMkY06BbA= github.com/r3labs/diff/v3 v3.0.2/go.mod h1:Cy542hv0BAEmhDYWtGxXRQ4kqRsVIcEjG9gChUlTmkw= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rot256/pblind v0.0.0-20250826112722-8244c3966ed3 h1:ymYWkLrwKuEaatWZboGryvjZnqap+9v0HX4gcozmZOo= github.com/rot256/pblind v0.0.0-20250826112722-8244c3966ed3/go.mod h1:rHhYqxx18ekqo/Y4U7dKP6/H8ZaUDY/pIHGKhq4DKxc= github.com/rubenv/sql-migrate v1.8.1 h1:EPNwCvjAowHI3TnZ+4fQu3a915OpnQoPAjTXCGOy2U0= @@ -420,8 +422,8 @@ github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/simukti/sqldb-logger v0.0.0-20230108155151-646c1a075551 h1:+EXKKt7RC4HyE/iE8zSeFL+7YBL8Z7vpBaEE3c7lCnk= github.com/simukti/sqldb-logger v0.0.0-20230108155151-646c1a075551/go.mod h1:ztTX0ctjRZ1wn9OXrzhonvNmv43yjFUXJYJR95JQAJE= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v0.0.0-20170901052352-ee1bd8ee15a1/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -551,8 +553,8 @@ golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297 h1:YXnL44eJ77R+ji4/ooy8UsXIhz+lbi2Qgdlc8iRN0gY= golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297/go.mod h1:Mkmymgv+uMpSQ/XxJ/7GpdrdYoqm3u72jEbpCLiJmNk= -golang.org/x/image v0.33.0 h1:LXRZRnv1+zGd5XBUVRFmYEphyyKJjQjCRiOuAP3sZfQ= -golang.org/x/image v0.33.0/go.mod h1:DD3OsTYT9chzuzTQt+zMcOlBHgfoKQb1gry8p76Y1sc= +golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo= +golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= diff --git a/packaging/linux/postinst b/packaging/linux/postinst index a54ee8e58..948678d09 100644 --- a/packaging/linux/postinst +++ b/packaging/linux/postinst @@ -63,8 +63,19 @@ if command -V semanage >/dev/null 2>&1; then fi echo "[ ] Initializing binary files" -mv /usr/bin/portmaster /usr/lib/portmaster/portmaster -ln -s /usr/lib/portmaster/portmaster /usr/bin/portmaster +# The package installs the UI to /usr/bin/portmaster. Move it next to the core +# and link it back. Only move a regular file: when this script runs again +# (dpkg --configure after a failed run, dpkg-reconfigure), /usr/bin/portmaster +# is already the link, and moving it would make /usr/lib/portmaster/portmaster +# a link to itself (safing/portmaster#2288). +if [ -f /usr/bin/portmaster ] && [ ! -L /usr/bin/portmaster ]; then + mv -f /usr/bin/portmaster /usr/lib/portmaster/portmaster +fi +if [ -f /usr/lib/portmaster/portmaster ] && [ ! -L /usr/lib/portmaster/portmaster ]; then + ln -sfn /usr/lib/portmaster/portmaster /usr/bin/portmaster +else + echo "[!] /usr/lib/portmaster/portmaster is missing, reinstall the package to repair the UI" >&2 +fi chmod +x /usr/lib/portmaster/portmaster-core diff --git a/packaging/windows/render_nsis_linux.py b/packaging/windows/render_nsis_linux.py new file mode 100755 index 000000000..b3ad20c6e --- /dev/null +++ b/packaging/windows/render_nsis_linux.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Render Tauri's NSIS installer template on Linux and build the Windows installer with makensis. + +The tauri-cli refuses `--bundles nsis` on non-Windows hosts although tauri-bundler itself +supports it. This script reproduces the bundler's data map for Portmaster and runs makensis. + +Prerequisites (Debian/Ubuntu): apt install nsis mingw-w64 lld llvm + - tauri-bundler sources (for installer.nsi/utils.nsh/languages): pass --bundler-src + - nsis_tauri_utils.dll in ~/.cache/tauri/NSIS/Plugins/x86-unicode (downloaded automatically) + - desktop/tauri/src-tauri/binary/ : portmaster-core.exe, portmaster-kext.sys, portmaster-core.dll, + WebView2Loader.dll, portmaster.zip, assets.zip + - desktop/tauri/src-tauri/intel/ : intel data (updatemgr download .../intel.v3.json) + - target/x86_64-pc-windows-gnu/release/portmaster.exe (cargo tauri build --target x86_64-pc-windows-gnu --no-bundle) + +Usage: python3 packaging/windows/render_nsis_linux.py [--bundler-src DIR] [--out FILE] +""" +import re, os, sys, argparse, subprocess, hashlib, urllib.request, shutil +ap=argparse.ArgumentParser() +ap.add_argument('version') +ap.add_argument('--bundler-src', default=os.path.expanduser('~/.cache/tauri-bundler-src'), + help='directory containing tauri-bundler-/ (crate sources, default: auto-download 2.2.4)') +ap.add_argument('--out', default=None, help='output installer path') +args=ap.parse_args() +ROOT=os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..')) +ST=f'{ROOT}/desktop/tauri/src-tauri' +# tauri-bundler sources +if not os.path.isdir(args.bundler_src) or not any(d.startswith('tauri-bundler-') for d in os.listdir(args.bundler_src)): + os.makedirs(args.bundler_src, exist_ok=True) + crate=f'{args.bundler_src}/tb.crate' + urllib.request.urlretrieve('https://crates.io/api/v1/crates/tauri-bundler/2.2.4/download', crate) + subprocess.check_call(['tar','xzf',crate,'-C',args.bundler_src]) +TBROOT=[d for d in os.listdir(args.bundler_src) if d.startswith('tauri-bundler-')][0] +TB=f'{args.bundler_src}/{TBROOT}/src/bundle/windows/nsis' +# plugin +PL=os.path.expanduser('~/.cache/tauri/NSIS/Plugins/x86-unicode'); os.makedirs(PL, exist_ok=True) +dll=f'{PL}/nsis_tauri_utils.dll' +if not os.path.exists(dll): + urllib.request.urlretrieve('https://github.com/tauri-apps/nsis-tauri-utils/releases/download/nsis_tauri_utils-v0.4.2/nsis_tauri_utils.dll', dll) +if hashlib.sha1(open(dll,'rb').read()).hexdigest().upper()!='6532DA4545864C6EC95F62F27F2199BFD668560B': + raise SystemExit('nsis_tauri_utils.dll checksum mismatch') +REL=f'{ST}/target/x86_64-pc-windows-gnu/release' +OUT=f'{ST}/target/release/nsis/x64' # must be exactly 4 levels below src-tauri: install_hooks.nsh uses ..\\..\\..\\.. paths +os.makedirs(OUT, exist_ok=True) +def esc(v): + if isinstance(v,bool): return 'true' if v else 'false' + s=str(v); o='' + for c in s: + o+={'"':'$\\"','$':'$$','`':'$\\`','\n':'$\\n','\t':'$\\t','\r':'$\\r'}.get(c,c) + return o +def bom(path, content): + if isinstance(content,str): content=content.encode() + open(path,'wb').write(b'\xef\xbb\xbf'+content) +lang_file=f'{OUT}/English.nsh'; bom(lang_file, open(f'{TB}/languages/English.nsh','rb').read()) +bom(f'{OUT}/utils.nsh', open(f'{TB}/utils.nsh','rb').read()) +bom(f'{OUT}/FileAssociation.nsh', open(f'{TB}/FileAssociation.nsh','rb').read()) +main_bin=f'{REL}/portmaster.exe' +size_kb=sum(os.path.getsize(os.path.join(d,f)) for d in [f'{ST}/binary',f'{ST}/intel'] for f in os.listdir(d))//1024 + os.path.getsize(main_bin)//1024 +version=args.version +m=re.match(r'(\d+)\.(\d+)\.(\d+)',version) +data=dict( + compression='lzma', installer_hooks=f'{ST}/templates/nsis/install_hooks.nsh', + manufacturer='safing', product_name='Portmaster', version=version, + version_with_build=f'{m.group(1)}.{m.group(2)}.{m.group(3)}.0', homepage='', install_mode='perMachine', + license='', installer_icon=os.path.realpath(f'{ST}/../../../assets/data/icons/pm_light_contrast.ico'), + sidebar_image='', header_image='', main_binary_name='portmaster', main_binary_path=main_bin, + bundle_id='io.safing.portmaster', copyright='Safing Limited Inc', out_file='nsis-output.exe', arch='x64', + additional_plugins_path=os.path.expanduser('~/.cache/tauri/NSIS/Plugins/x86-unicode'), + allow_downgrades=True, display_language_selector=False, install_webview2_mode='downloadBootstrapper', + webview2_installer_args='/silent', webview2_bootstrapper_path='', webview2_installer_path='', + minimum_webview2_version='', uninstaller_sign_cmd='', estimated_size=size_kb, start_menu_folder='', + short_description='Portmaster UI', long_description='', +) +lists=dict(languages=['English'], language_files=[lang_file], resources_dirs=[], resources={}, binaries={}, + resources_ancestors=[], file_associations=[], deep_link_protocols=[]) +t=open(f'{TB}/installer.nsi').read() +# each blocks (non-nested first: nested ones are file_associations which are empty) +def each_sub(mm): + name=mm.group(1); body=mm.group(2); items=lists[name] + out='' + if isinstance(items,dict): + for k,v in items.items(): out+=body.replace('{{@key}}',esc(k)).replace('{{this.[1]}}',esc(v[1]) if isinstance(v,(list,tuple)) else esc(v)).replace('{{this}}',esc(v)) + else: + for v in items: out+=body.replace('{{this}}',esc(v)) + return out +# nested each with "as |x|" -> remove entirely (empty lists); indentation-tolerant +t=re.sub(r'[ \t]*\{\{#each file_associations as \|\w+\| ~\}\}\n.*?\{\{/each\}\}\n[ \t]*\{\{/each\}\}\n','',t,flags=re.S) +t=re.sub(r'[ \t]*\{\{#each deep_link_protocols as \|\w+\| ~\}\}\n.*?\{\{/each\}\}\n','',t,flags=re.S) +assert 'as |' not in t, 'leftover nested each' +t=re.sub(r'[ \t]*\{\{#each (\w+)\}\}\n(.*?)[ \t]*\{\{/each\}\}\n',each_sub,t,flags=re.S) +def if_sub(mm): + return mm.group(2) if data.get(mm.group(1)) else '' +t=re.sub(r'[ \t]*\{\{#if (\w+)\}\}\n(.*?)[ \t]*\{\{/if\}\}\n',if_sub,t,flags=re.S) +def var_sub(mm): + k=mm.group(1) + if k not in data: raise SystemExit('missing var '+k) + return esc(data[k]) +t=re.sub(r'\{\{(\w+)\}\}',var_sub,t) +assert '{{' not in t, [l for l in t.splitlines() if '{{' in l][:3] +bom(f'{OUT}/installer.nsi', t) +print('rendered', f'{OUT}/installer.nsi', 'estimated_size_kb', size_kb) +env={k:v for k,v in os.environ.items() if k not in ('NSISDIR','NSISCONFDIR')} +subprocess.check_call(['makensis','-INPUTCHARSET','UTF8','-V2','installer.nsi'], cwd=OUT, env=env) +out=args.out or f'{ROOT}/dist/windows_amd64/portmasterpro_{version}_x64-setup.exe' +os.makedirs(os.path.dirname(out), exist_ok=True) +shutil.move(f'{OUT}/nsis-output.exe', out) +print('installer:', out, os.path.getsize(out), 'bytes') diff --git a/service/broadcasts/data.go b/service/broadcasts/data.go index b9a1a453f..c586ebf55 100644 --- a/service/broadcasts/data.go +++ b/service/broadcasts/data.go @@ -1,6 +1,7 @@ package broadcasts import ( + "errors" "strconv" "time" @@ -8,9 +9,6 @@ import ( "github.com/safing/portmaster/service/core" "github.com/safing/portmaster/service/intel/geoip" "github.com/safing/portmaster/service/netenv" - "github.com/safing/portmaster/spn/access" - "github.com/safing/portmaster/spn/access/account" - "github.com/safing/portmaster/spn/captain" ) var portmasterStarted = time.Now() @@ -58,27 +56,11 @@ func collectData() interface{} { } } - // Get data about SPN status. - data["SPN"] = captain.GetSPNStatus() + // SPN data has been removed: portmasterpro has no SPN. + data["SPN"] = &DataError{Error: errNoSPN} - // Get data about account. - userRecord, err := access.GetUser() - if err != nil { - data["Account"] = &DataError{ - Error: err, - } - } else { - account := &Account{ - UserRecord: userRecord, - Active: userRecord.MayUse(""), - UpToDate: userRecord.Meta().Modified > time.Now().Add(-7*24*time.Hour).Unix(), - } - // Only add feature IDs when account is active. - if account.Active { - account.FeatureIDs = userRecord.CurrentPlan.FeatureIDs - } - data["Account"] = account - } + // Account data has been removed: portmasterpro has no user accounts. + data["Account"] = &DataError{Error: errNoAccount} // Time running. data["UptimeHours"] = int(time.Since(portmasterStarted).Hours()) @@ -104,13 +86,12 @@ type Location struct { SourceAccuracy int } -// Account holds SPN account matching data. -type Account struct { - *access.UserRecord - Active bool - UpToDate bool - FeatureIDs []account.FeatureID -} +var ( + // errNoAccount is reported in place of the removed SPN account data. + errNoAccount = errors.New("accounts have been removed from portmasterpro") + // errNoSPN is reported in place of the removed SPN status data. + errNoSPN = errors.New("the SPN has been removed from portmasterpro") +) // DataError represents an error getting some matching data. type DataError struct { diff --git a/service/broadcasts/notify.go b/service/broadcasts/notify.go index 73c9f2324..16e356595 100644 --- a/service/broadcasts/notify.go +++ b/service/broadcasts/notify.go @@ -123,6 +123,9 @@ func parseBroadcastSource(yamlData []byte) (*BroadcastNotifications, error) { // Add IDs to struct for easier handling. for id, bn := range broadcasts.Notifications { + if bn == nil { + return nil, fmt.Errorf("%w: %s", errEmptyBroadcast, id) + } bn.id = id // Parse matching query. @@ -151,6 +154,11 @@ func parseBroadcastSource(yamlData []byte) (*BroadcastNotifications, error) { return broadcasts, nil } +var ( + errEmptyBroadcast = errors.New("broadcast notification is empty") + errNoNotificationContent = errors.New("broadcast has no notification content") +) + func handleBroadcast(bn *BroadcastNotification, matchingDataAccessor accessor.Accessor, bss *BroadcastStates) error { // Check if broadcast was already shown. if bss != nil { @@ -182,6 +190,11 @@ func handleBroadcast(bn *BroadcastNotification, matchingDataAccessor accessor.Ac return ErrSkipDoesNotMatch } + // Removals may come without notification, but displaying needs one. + if bn.Notification == nil { + return errNoNotificationContent + } + // Check if there is already an active notification for this. eventID := broadcastNotificationIDPrefix + bn.id n := notifications.Get(eventID) diff --git a/service/broadcasts/notify_test.go b/service/broadcasts/notify_test.go new file mode 100644 index 000000000..8b36beedc --- /dev/null +++ b/service/broadcasts/notify_test.go @@ -0,0 +1,53 @@ +package broadcasts + +import ( + "errors" + "testing" + + "github.com/safing/portmaster/base/database/accessor" +) + +func TestParseBroadcastSourceEmptyEntry(t *testing.T) { + t.Parallel() + + // An entry without any content is decoded as nil. + _, err := parseBroadcastSource([]byte("notifications:\n test1:\n")) + if err == nil { + t.Fatal("expected error for empty broadcast notification") + } +} + +func TestHandleBroadcastWithoutNotification(t *testing.T) { + t.Parallel() + + // An entry without any notification fields has no notification. + broadcasts, err := parseBroadcastSource([]byte("notifications:\n test1:\n permanent: true\n")) + if err != nil { + t.Fatalf("failed to parse: %s", err) + } + err = handleBroadcast(broadcasts.Notifications["test1"], nil, nil) + if err == nil || errors.Is(err, ErrSkip) { + t.Fatalf("expected failure for broadcast without notification, got %v", err) + } +} + +func FuzzParseBroadcastSource(f *testing.F) { + f.Add([]byte("notifications:\n test1:\n title: a\n match: \"NumericVersion > 8000\"\n repeat: 1m\n")) + f.Add([]byte("notifications:\n test1:\n remove: true\n")) + f.Add([]byte(`{"notifications":{"a":{"match":"Version sameas 0.9.0 and Updates.Channel sameas beta"}}}`)) + + matchingJSON := []byte(`{"Version":"1.2.3","NumericVersion":1002003,"Updates":{"Channel":"stable"},"Current":{"UTC":{"NumericDate":20260101}}}`) + matchingDataAccessor := accessor.NewJSONBytesAccessor(&matchingJSON) + + f.Fuzz(func(t *testing.T, data []byte) { + broadcasts, err := parseBroadcastSource(data) + if err != nil { + return + } + for _, bn := range broadcasts.Notifications { + if bn.matchingQuery != nil { + bn.matchingQuery.MatchesAccessor(matchingDataAccessor) + } + } + }) +} diff --git a/service/compat/callbacks.go b/service/compat/callbacks.go index 71fd8b69d..644f10a44 100644 --- a/service/compat/callbacks.go +++ b/service/compat/callbacks.go @@ -37,11 +37,3 @@ func ReportSecureDNSBypassIssue(p *process.Process) { return nil }) } - -// ReportMultiPeerUDPTunnelIssue reports a multi-peer UDP tunnel for the given process. -func ReportMultiPeerUDPTunnelIssue(p *process.Process) { - module.mgr.Go("report multi-peer udp tunnel issue", func(w *mgr.WorkerCtx) error { - multiPeerUDPTunnelIssue.notify(p) - return nil - }) -} diff --git a/service/compat/module.go b/service/compat/module.go index 28d67d481..69c3bdc87 100644 --- a/service/compat/module.go +++ b/service/compat/module.go @@ -53,8 +53,9 @@ var ( selfCheckIsFailing = abool.New() // selfcheckFails counts how often the self check failed successively. - // selfcheckFails is not locked as it is only accessed by the self-check task. - selfcheckFails int + // selfcheckFails is atomic, as it is written by the self-check task and + // reset by stop(). + selfcheckFails atomic.Int32 // selfcheckNetworkChangedFlag is used to track changed to the network for // the self-check. @@ -129,12 +130,11 @@ func selfcheckTaskFunc(wc *mgr.WorkerCtx) error { // The self-check failed. // Set state and increase counter. - selfCheckIsFailing.Set() - selfcheckFails++ + failCount := recordSelfcheckFailure() // Log and notify. tracer.Errorf("compat: %s", err) - if selfcheckFails >= selfcheckFailThreshold { + if failCount >= selfcheckFailThreshold { issue.notify(err) } @@ -150,10 +150,17 @@ func selfcheckTaskFunc(wc *mgr.WorkerCtx) error { return nil } +// recordSelfcheckFailure marks the self-check as failing and returns the +// number of successive failures. +func recordSelfcheckFailure() int32 { + selfCheckIsFailing.Set() + return selfcheckFails.Add(1) +} + func resetSelfCheckState() { selfcheckNetworkChangedFlag.Refresh() selfCheckIsFailing.UnSet() - selfcheckFails = 0 + selfcheckFails.Store(0) resetSystemIssue() } diff --git a/service/compat/module_race_test.go b/service/compat/module_race_test.go new file mode 100644 index 000000000..804b596c9 --- /dev/null +++ b/service/compat/module_race_test.go @@ -0,0 +1,34 @@ +package compat + +import ( + "sync" + "testing" +) + +// TestSelfcheckFailsConcurrentReset checks that resetting the self-check state +// (as stop() does) is safe while the self-check task records failures. +// Run with -race. +func TestSelfcheckFailsConcurrentReset(t *testing.T) { + t.Parallel() + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for range 1000 { + recordSelfcheckFailure() + } + }() + go func() { + defer wg.Done() + for range 1000 { + resetSelfCheckState() + } + }() + wg.Wait() + resetSelfCheckState() + + if n := selfcheckFails.Load(); n != 0 { + t.Fatalf("expected 0 fails after reset, got %d", n) + } +} diff --git a/service/compat/notify.go b/service/compat/notify.go index 86999719c..3e3cda2cd 100644 --- a/service/compat/notify.go +++ b/service/compat/notify.go @@ -16,11 +16,11 @@ import ( ) type baseIssue struct { - id string //nolint:structcheck // Inherited. - title string //nolint:structcheck // Inherited. - message string //nolint:structcheck // Inherited. - level notifications.Type //nolint:structcheck // Inherited. - actions []*notifications.Action //nolint:structcheck // Inherited. + id string + title string + message string + level notifications.Type + actions []*notifications.Action } type systemIssue baseIssue @@ -72,12 +72,6 @@ var ( // , or [find out about other options](link to new docs page) level: notifications.Warning, } - multiPeerUDPTunnelIssue = &appIssue{ - id: "compat:multi-peer-udp-tunnel-%s", - title: "Detected SPN Incompatibility in %s", - message: "Portmaster detected that [APPNAME] is trying to connect to multiple servers via the SPN using a single UDP connection. This is common for technologies such as torrents. Unfortunately, the SPN does not support this feature currently. You can try to change this behavior within the affected app or you could exempt it from using the SPN.", - level: notifications.Warning, - } ) func startNotify() { diff --git a/service/compat/selfcheck.go b/service/compat/selfcheck.go index 0bbef4e4c..787e89fcf 100644 --- a/service/compat/selfcheck.go +++ b/service/compat/selfcheck.go @@ -153,6 +153,8 @@ func selfcheck(ctx context.Context) (issue *systemIssue, err error) { } case <-time.After(dnsCheckWaitDuration): return systemCompatOrManualDNSIssue(), fmt.Errorf("self-check #2: dns integration check failed: did not receive test query after %s", dnsCheckWaitDuration) + case <-ctx.Done(): + return nil, context.Canceled } log.Tracer(ctx).Tracef("compat: self-check #2: dns integration query check passed") diff --git a/service/config.go b/service/config.go index 7ab0af7e7..83c06bbc0 100644 --- a/service/config.go +++ b/service/config.go @@ -135,7 +135,7 @@ func MakeUpdateConfigs(svcCfg *ServiceConfig) (binaryUpdateConfig, intelUpdateCo IndexURLs: svcCfg.BinariesIndexURLs, // May be changed by config during instance startup. IndexFile: "index.json", Verify: svcCfg.VerifyBinaryUpdates, - AutoCheck: true, // May be changed by config during instance startup. + AutoCheck: false, // portmasterpro: upstream binary updates are opt-in; may be changed by config during instance startup. AutoDownload: false, AutoApply: false, NeedsRestart: true, @@ -166,7 +166,7 @@ func MakeUpdateConfigs(svcCfg *ServiceConfig) (binaryUpdateConfig, intelUpdateCo IndexURLs: svcCfg.BinariesIndexURLs, // May be changed by config during instance startup. IndexFile: "index.json", Verify: svcCfg.VerifyBinaryUpdates, - AutoCheck: true, // May be changed by config during instance startup. + AutoCheck: false, // portmasterpro: upstream binary updates are opt-in; may be changed by config during instance startup. AutoDownload: false, AutoApply: false, NeedsRestart: true, diff --git a/service/configure/updates_test.go b/service/configure/updates_test.go index ba3db9ad9..9c49e0b11 100644 --- a/service/configure/updates_test.go +++ b/service/configure/updates_test.go @@ -19,7 +19,8 @@ func TestIntelSigningKeysAreSeparate(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := IntelSigningTrustStore.GetSignet(rcpt.ID, true); err != nil { + _, err = IntelSigningTrustStore.GetSignet(rcpt.ID, true) + if err != nil { t.Errorf("intel key %s missing from the intel trust store: %s", rcpt.ID, err) } } @@ -28,7 +29,8 @@ func TestIntelSigningKeysAreSeparate(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := IntelSigningTrustStore.GetSignet(rcpt.ID, true); err == nil { + _, err = IntelSigningTrustStore.GetSignet(rcpt.ID, true) + if err == nil { t.Errorf("code signing key %s must not be in the intel trust store", rcpt.ID) } } diff --git a/service/control/api.go b/service/control/api.go index cf6564195..38d4a8414 100644 --- a/service/control/api.go +++ b/service/control/api.go @@ -2,6 +2,7 @@ package control import ( "encoding/json" + "errors" "fmt" "net/http" "time" @@ -14,9 +15,16 @@ const ( APIEndpointResume = "control/resume" ) +// errOnlySPNNotSupported is returned when a client asks to pause only the SPN. +// This build has no SPN, so such a request is rejected instead of pausing the +// whole interception, which the client did not ask for. +var errOnlySPNNotSupported = errors.New("pausing only the SPN is not supported: this build has no SPN") + type pauseRequestParams struct { - Duration int `json:"duration"` // Duration in seconds - OnlySPN bool `json:"onlySPN"` // Whether to pause only the SPN service + Duration int `json:"duration"` // Duration in seconds + // OnlySPN is still accepted for compatibility with older clients. A value + // of false is ignored, true is rejected with errOnlySPNNotSupported. + OnlySPN bool `json:"onlySPN"` } func (c *Control) registerAPIEndpoints() error { @@ -32,12 +40,6 @@ func (c *Control) registerAPIEndpoints() error { Method: http.MethodPost, Field: "duration", Description: "Specify the duration to pause the service in seconds.", - }, - { - Method: http.MethodPost, - Field: "onlySPN", - Value: "false", - Description: "Specify whether to pause only the SPN service.", }}, }); err != nil { return err @@ -65,12 +67,13 @@ func (c *Control) handlePause(r *api.Request) (msg string, err error) { } if params.OnlySPN { - c.mgr.Info(fmt.Sprintf("Received SPN Pause(%v) action request ", params.Duration)) - } else { - c.mgr.Info(fmt.Sprintf("Received Pause(%v) action request ", params.Duration)) + return "Bad Request: " + errOnlySPNNotSupported.Error(), errOnlySPNNotSupported } - if err := c.pause(time.Duration(params.Duration)*time.Second, params.OnlySPN); err != nil { + c.mgr.Info(fmt.Sprintf("Received Pause(%v) action request ", params.Duration)) + + err = c.pause(time.Duration(params.Duration) * time.Second) + if err != nil { return "Failed to pause", err } return "Pause initiated", nil diff --git a/service/control/module.go b/service/control/module.go index d04ff7e11..2df2c3ff3 100644 --- a/service/control/module.go +++ b/service/control/module.go @@ -6,14 +6,13 @@ import ( "sync/atomic" "time" - "github.com/safing/portmaster/base/config" "github.com/safing/portmaster/base/notifications" "github.com/safing/portmaster/service/mgr" ) type PauseInfo struct { Interception bool // Whether Portmaster interception is paused - SPN bool // Whether SPN is paused + SPN bool // Always false: this build has no SPN. Kept for clients that expect the field. TillTime time.Time // When the pause will end } @@ -25,13 +24,12 @@ type Control struct { locker sync.Mutex resumeWorker *mgr.WorkerMgr pauseNotification *notifications.Notification + errorNotification *notifications.Notification pauseInfo PauseInfo } type instance interface { - Config() *config.Config InterceptionGroup() *mgr.GroupModule - SPNGroup() *mgr.ExtendedGroup IsShuttingDown() bool } diff --git a/service/control/pause.go b/service/control/pause.go index d66637792..8ff56b66f 100644 --- a/service/control/pause.go +++ b/service/control/pause.go @@ -5,12 +5,11 @@ import ( "fmt" "time" - "github.com/safing/portmaster/base/config" "github.com/safing/portmaster/base/notifications" "github.com/safing/portmaster/service/mgr" ) -func (c *Control) pause(duration time.Duration, onlySPN bool) (retErr error) { +func (c *Control) pause(duration time.Duration) (retErr error) { if c.instance.IsShuttingDown() { c.mgr.Debug("Cannot pause: system is shutting down") return nil @@ -32,18 +31,6 @@ func (c *Control) pause(duration time.Duration, onlySPN bool) (retErr error) { return errors.New("invalid pause duration") } - cfgSpnEnabled := config.GetAsBool("spn/enable", false) - - if onlySPN { - if c.pauseInfo.Interception { - return errors.New("cannot pause SPN separately when core is paused") - } - // If SPN is not running and not already paused, cannot pause it or change pause duration. - if !cfgSpnEnabled() && !c.pauseInfo.SPN { - return errors.New("cannot pause SPN when it is not running") - } - } - // Stop resume worker if running and start a new one later. c.stopResumeWorker() defer func() { @@ -53,32 +40,6 @@ func (c *Control) pause(duration time.Duration, onlySPN bool) (retErr error) { } }() - // Pause SPN if not already paused. - if !c.pauseInfo.SPN { - if cfgSpnEnabled() { - // "spn/access" module is responsible for starting/stopping SPN service. - // Here we just change the config to notify it to stop SPN. - // TODO: the 'pause' state must not make permanent config changes. - // Consider possibility to not store permanent config changes. - // E.g. SPN enabled -> pause SPN -> restart PC/Portmaster -> SPN should be enabled again. - config.SetConfigOption("spn/enable", false) - - // Wait until SPN is fully stopped with timeout 30s. - err := c.waitSPNStopped(time.Second * 30) - if err != nil { - config.SetConfigOption("spn/enable", true) // revert config change on error - return err - } - - c.mgr.Info("SPN paused") - c.pauseInfo.SPN = true - } - } - - if onlySPN { - return nil - } - if !c.pauseInfo.Interception { if err := c.instance.InterceptionGroup().Stop(); err != nil { return err @@ -90,15 +51,27 @@ func (c *Control) pause(duration time.Duration, onlySPN bool) (retErr error) { return nil } -func (c *Control) resume() (retErr error) { +func (c *Control) resume() error { + _, err := c.doResume(nil) + return err +} + +// doResume resumes normal operation. If called from a resume worker (wc is +// set), it does nothing and reports superseded if that worker was stopped +// (e.g. replaced by a new pause request) while waiting for the lock. +func (c *Control) doResume(wc *mgr.WorkerCtx) (superseded bool, retErr error) { if c.instance.IsShuttingDown() { c.mgr.Debug("Cannot resume: system is shutting down") - return nil + return false, nil } c.locker.Lock() defer c.locker.Unlock() + if wc != nil && wc.IsDone() { + return true, nil + } + defer func() { if retErr != nil { c.updateStatesAndNotifyError("Resume operation failed", retErr) @@ -112,24 +85,13 @@ func (c *Control) resume() (retErr error) { if c.pauseInfo.Interception { if err := c.instance.InterceptionGroup().Start(); err != nil { - return err + return false, err } c.mgr.Info("interception resumed") c.pauseInfo.Interception = false } - if c.pauseInfo.SPN { - cfgSpnEnabled := config.GetAsBool("spn/enable", false) - // "spn/access" module is responsible for starting/stopping SPN service. - // Here we just change the config to notify it to start SPN. - if !cfgSpnEnabled() { - config.SetConfigOption("spn/enable", true) - c.mgr.Info("SPN resumed") - } - c.pauseInfo.SPN = false - } - - return nil + return false, nil } // stopResumeWorker stops any existing resume worker. @@ -154,10 +116,6 @@ func (c *Control) startResumeWorker(duration time.Duration) { resumerWorkerFunc := func(wc *mgr.WorkerCtx) error { wc.Info(fmt.Sprintf("Scheduling resume in %v", duration)) - // Subscribe to config changes to detect SPN enable. - cfgChangeEvt := c.instance.Config().EventConfigChange.Subscribe("control: spn enable check", 10) - defer cfgChangeEvt.Cancel() - // Timer for the deadline. timer := time.NewTimer(time.Until(deadline)) defer timer.Stop() @@ -165,20 +123,12 @@ func (c *Control) startResumeWorker(duration time.Duration) { ticker := time.NewTicker(15 * time.Second) defer ticker.Stop() - cfgSpnEnabled := config.GetAsBool("spn/enable", false) - - // Wait until duration elapses or SPN is enabled by user. + // Wait until duration elapses. needToAutoResume := false for !needToAutoResume { select { case <-wc.Ctx().Done(): return nil - case <-cfgChangeEvt.Events(): - if cfgSpnEnabled() { - cfgChangeEvt.Cancel() // we do not need it anymore (no problem to cancel multiple times) - wc.Info("SPN enabled by user. Auto-resume initiated.") - needToAutoResume = true - } case <-ticker.C: // Check wall-clock time. if time.Now().Round(0).After(deadline) { @@ -191,7 +141,11 @@ func (c *Control) startResumeWorker(duration time.Duration) { // Time to resume wc.Info("Resuming...") - err := c.resume() + superseded, err := c.doResume(wc) + if superseded { + wc.Info("Resume canceled, pause was changed meanwhile.") + return nil + } if err == nil { n := ¬ifications.Notification{ EventID: "control:resumed", @@ -219,7 +173,10 @@ func (c *Control) startResumeWorker(duration time.Duration) { // updateStatesAndNotify updates the paused states and sends notifications accordingly. // No thread safety, caller must hold c.locker. func (c *Control) updateStatesAndNotify() { - if !c.pauseInfo.Interception && !c.pauseInfo.SPN { + // A new pause/resume attempt supersedes the error of a previous one. + c.deleteErrorNotification() + + if !c.pauseInfo.Interception { if c.pauseNotification != nil { c.pauseNotification.Delete() c.pauseNotification = nil @@ -227,21 +184,12 @@ func (c *Control) updateStatesAndNotify() { return } - title := "" - nType := notifications.Warning - if c.pauseInfo.Interception && c.pauseInfo.SPN { - title = "Portmaster and SPN paused" - } else if c.pauseInfo.Interception { - title = "Portmaster paused" - } else if c.pauseInfo.SPN { - title = "SPN paused" - nType = notifications.Info // less severe notification for SPN-only pause - } + title := "Portmaster paused" message := fmt.Sprintf("%s until %v", title, c.pauseInfo.TillTime.Format(time.TimeOnly)) c.pauseNotification = ¬ifications.Notification{ EventID: "control:paused", - Type: nType, + Type: notifications.Warning, Title: title, Message: message, ShowOnSystem: false, // TODO: Before enabling, ensure that UI client (Tauri implementation) supports ActionTypeWebhook. @@ -273,16 +221,28 @@ func (c *Control) updateStatesAndNotifyError(errDescription string, err error) { errDescription = "Error" } - // Error notification - c.pauseNotification = ¬ifications.Notification{ + // Error notification. It is tracked separately so that it does not replace + // (and thereby orphan) the pause notification, which stays valid while the + // pause state is unchanged. + c.deleteErrorNotification() + c.errorNotification = ¬ifications.Notification{ EventID: "control:error", Type: notifications.Error, Title: errDescription, Message: err.Error(), EventData: &c.pauseInfo, } - notifications.Notify(c.pauseNotification) - c.pauseNotification.SyncWithState(c.states) + notifications.Notify(c.errorNotification) + c.errorNotification.SyncWithState(c.states) +} + +// deleteErrorNotification deletes the error notification, if any. +// No thread safety, caller must hold c.locker. +func (c *Control) deleteErrorNotification() { + if c.errorNotification != nil { + c.errorNotification.Delete() + c.errorNotification = nil + } } func (c *Control) showNotification(title, message string) *notifications.Notification { @@ -295,40 +255,3 @@ func (c *Control) showNotification(title, message string) *notifications.Notific notifications.Notify(n) return n } - -func (c *Control) waitSPNStopped(stopTimeout time.Duration) error { - var notification *notifications.Notification - defer func() { - if notification != nil { - notification.Delete() - } - }() - - cfgSpnEnabled := config.GetAsBool("spn/enable", false) - startTime := time.Now() - isStopped, _ := c.instance.SPNGroup().IsStopped() - for !isStopped { - var err error - - time.Sleep(200 * time.Millisecond) - - if c.mgr.IsDone() || c.instance.IsShuttingDown() { - return errors.New("shutting down") - } - - isStopped, err = c.instance.SPNGroup().IsStopped() - if err != nil { - return fmt.Errorf("failed to stop SPN: %w", err) - } - if time.Since(startTime) > stopTimeout { - return errors.New("timeout waiting for SPN to stop") - } - if notification == nil && time.Since(startTime) > time.Second { - notification = c.showNotification("Waiting for SPN to stop...", "") - } - if cfgSpnEnabled() { - return errors.New("SPN enabled again") - } - } - return nil -} diff --git a/service/control/pause_test.go b/service/control/pause_test.go new file mode 100644 index 000000000..4680314a8 --- /dev/null +++ b/service/control/pause_test.go @@ -0,0 +1,198 @@ +package control + +import ( + "errors" + "sync" + "testing" + "time" + + "github.com/safing/portmaster/base/api" + "github.com/safing/portmaster/base/notifications" + "github.com/safing/portmaster/service/mgr" +) + +const ( + pausedEventID = "control:paused" + errorEventID = "control:error" +) + +var ( + errTestResume = errors.New("test error") + notificationsSetupOnce sync.Once +) + +func newTestControl(t *testing.T) *Control { + t.Helper() + + notificationsSetupOnce.Do(func() { + _, err := notifications.New(struct{}{}) + if err != nil { + t.Fatalf("failed to create notifications module: %s", err) + } + }) + + m := mgr.New("Control") + return &Control{ + mgr: m, + states: mgr.NewStateMgr(m), + } +} + +func assertNoPauseLeftovers(t *testing.T, c *Control) { + t.Helper() + + for _, id := range []string{pausedEventID, errorEventID} { + if n := notifications.Get(id); n != nil { + t.Errorf("notification %q still shown after successful resume", id) + } + } + if states := c.states.Export().States; len(states) != 0 { + t.Errorf("module states left after successful resume: %+v", states) + } +} + +// TestPauseNotificationsClearedAfterFailedResume checks that a failed resume +// (error notification) followed by a successful resume does not leave the +// "paused" or the error notification, nor their module states, behind. +// +//nolint:paralleltest // Uses the global notification storage. +func TestPauseNotificationsClearedAfterFailedResume(t *testing.T) { + c := newTestControl(t) + + // Paused. + c.pauseInfo.Interception = true + c.updateStatesAndNotify() + if notifications.Get(pausedEventID) == nil { + t.Fatal("pause notification was not shown") + } + + // Resume fails: still paused, error is shown. + c.updateStatesAndNotifyError("Resume operation failed", errTestResume) + if notifications.Get(errorEventID) == nil { + t.Fatal("error notification was not shown") + } + + // Resume succeeds. + c.pauseInfo.Interception = false + c.updateStatesAndNotify() + + assertNoPauseLeftovers(t, c) +} + +// TestErrorNotificationClearedByNextPause checks that the error notification +// of a failed resume is removed by the next pause/resume attempt instead of +// being orphaned when the pause notification is shown again. +// +//nolint:paralleltest // Uses the global notification storage. +func TestErrorNotificationClearedByNextPause(t *testing.T) { + c := newTestControl(t) + + c.pauseInfo.Interception = true + c.updateStatesAndNotify() + c.updateStatesAndNotifyError("Resume operation failed", errTestResume) + + // Pause again (e.g. with a new duration), then resume successfully. + c.updateStatesAndNotify() + c.pauseInfo.Interception = false + c.updateStatesAndNotify() + + assertNoPauseLeftovers(t, c) +} + +type controlTestInstance struct { + interception *mgr.GroupModule +} + +func (i *controlTestInstance) InterceptionGroup() *mgr.GroupModule { return i.interception } +func (i *controlTestInstance) IsShuttingDown() bool { return false } + +func newTestControlWithInstance(t *testing.T) *Control { + t.Helper() + + c := newTestControl(t) + c.instance = &controlTestInstance{ + interception: mgr.NewGroupModule("Interception"), + } + return c +} + +// TestSupersededResumeWorkerDoesNotResume checks that a resume worker whose +// timer fired while another pause request held the lock and replaced it does +// not resume afterwards, undoing the new pause. +// +//nolint:paralleltest // Uses the global notification storage. +func TestSupersededResumeWorkerDoesNotResume(t *testing.T) { + c := newTestControlWithInstance(t) + defer c.mgr.Cancel() + + // Pause for a short time. + err := c.pause(20 * time.Millisecond) + if err != nil { + t.Fatalf("pause failed: %s", err) + } + + // Simulate a second pause request that holds the lock while the first + // resume timer fires, and then replaces the resume worker. + c.locker.Lock() + time.Sleep(100 * time.Millisecond) // Let the old resume worker block on the lock. + c.stopResumeWorker() + c.startResumeWorker(time.Hour) + c.locker.Unlock() + + // Give the old resume worker the chance to (wrongly) resume. + time.Sleep(50 * time.Millisecond) + + c.locker.Lock() + paused := c.pauseInfo.Interception + c.stopResumeWorker() + c.pauseInfo.Interception = false + c.updateStatesAndNotify() + c.locker.Unlock() + + if !paused { + t.Fatal("superseded resume worker resumed although a new pause was requested") + } +} + +// TestResumeWorkerResumesAfterDuration checks that a pause still ends +// automatically after its duration. +// +//nolint:paralleltest // Uses the global notification storage. +func TestResumeWorkerResumesAfterDuration(t *testing.T) { + c := newTestControlWithInstance(t) + defer c.mgr.Cancel() + + err := c.pause(20 * time.Millisecond) + if err != nil { + t.Fatalf("pause failed: %s", err) + } + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + c.locker.Lock() + paused := c.pauseInfo.Interception + c.locker.Unlock() + if !paused { + return + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("pause did not end after its duration") +} + +// TestPauseOnlySPNRejected checks that a request to pause only the SPN, as +// sent by older clients, is rejected and does not pause the interception. +// +//nolint:paralleltest // Uses the global notification storage. +func TestPauseOnlySPNRejected(t *testing.T) { + c := newTestControlWithInstance(t) + defer c.mgr.Cancel() + + _, err := c.handlePause(&api.Request{InputData: []byte(`{"duration":60,"onlySPN":true}`)}) + if !errors.Is(err, errOnlySPNNotSupported) { + t.Fatalf("expected %v, got %v", errOnlySPNNotSupported, err) + } + if c.pauseInfo.Interception || c.pauseInfo.SPN { + t.Fatalf("pause state changed by rejected request: %+v", c.pauseInfo) + } +} diff --git a/service/core/api.go b/service/core/api.go index 7eabf0e83..1b5513eca 100644 --- a/service/core/api.go +++ b/service/core/api.go @@ -27,10 +27,21 @@ import ( "github.com/safing/portmaster/service/process" "github.com/safing/portmaster/service/resolver" "github.com/safing/portmaster/service/status" - "github.com/safing/portmaster/spn/captain" ) -var errInvalidReadPermission = errors.New("invalid read permission") +var ( + errInvalidReadPermission = errors.New("invalid read permission") + errInvalidWritePermission = errors.New("invalid write permission") + errInvalidTTL = errors.New("ttl must be positive and at most 30 days") + errAppAccessDenied = errors.New("access denied") + errAppAuthTimeout = errors.New("timeout") +) + +// maxAppAuthTTL is the longest lifetime an app may request for its API key. +const maxAppAuthTTL = 30 * 24 * time.Hour + +// appAuthAllowActionID is the notification action ID to authorize an app. +const appAuthAllowActionID = "allow" func registerAPIEndpoints() error { if err := api.RegisterEndpoint(api.Endpoint{ @@ -104,22 +115,24 @@ func registerAPIEndpoints() error { return err } - if err := api.RegisterEndpoint(api.Endpoint{ + err := api.RegisterEndpoint(api.Endpoint{ Path: "app/profile", Read: api.PermitUser, StructFunc: getMyProfile, Name: "Get the ID of the calling profile", - }); err != nil { + }) + if err != nil { return err } - if err := api.RegisterEndpoint(api.Endpoint{ + err = api.RegisterEndpoint(api.Endpoint{ Path: "core/paths", Read: api.PermitUser, StructFunc: getPaths, Name: "Get Directories", Description: "Returns the directories used by Portmaster: binaries (bin), variable data (data) and log files (logs).", - }); err != nil { + }) + if err != nil { return err } @@ -312,7 +325,6 @@ func debugInfo(ar *api.Request) (data []byte, err error) { // Status Information from various modules. status.AddToDebugInfo(di) - captain.AddToDebugInfo(di) resolver.AddToDebugInfo(di) config.AddToDebugInfo(di) @@ -340,7 +352,7 @@ func getSavePermission(p string) api.Permission { } } -func getPaths(_ *api.Request) (interface{}, error) { +func getPaths(_ *api.Request) (any, error) { return map[string]string{ "bin": module.instance.BinDir(), "data": module.instance.DataDir(), @@ -383,7 +395,10 @@ func authorizeApp(ar *api.Request) (interface{}, error) { return nil, errInvalidReadPermission } if getSavePermission(writePermStr) <= api.NotSupported { - return nil, errInvalidReadPermission + return nil, errInvalidWritePermission + } + if ttl <= 0 || ttl > maxAppAuthTTL { + return nil, errInvalidTTL } proc, err := process.GetProcessByRequestOrigin(ar) @@ -392,15 +407,18 @@ func authorizeApp(ar *api.Request) (interface{}, error) { } n := notifications.Notification{ - Type: notifications.Prompt, - EventID: "core:authorize-app-" + time.Now().String(), - Title: "An app requests access to the Portmaster", - Message: "Allow " + appName + " (" + proc.Profile().LocalProfile().Name + ") to query and modify the Portmaster?\n\nBinary: " + proc.Path, + Type: notifications.Prompt, + EventID: "core:authorize-app-" + time.Now().String(), + Title: "An app requests access to the Portmaster", + Message: fmt.Sprintf( + "Allow %q (%s) to access the Portmaster with %s read and %s write permission for %s?\n\nBinary: %s", + appName, proc.Profile().LocalProfile().Name, readPermStr, writePermStr, ttl, proc.Path, + ), ShowOnSystem: true, Expires: time.Now().Add(time.Minute).Unix(), AvailableActions: []*notifications.Action{ { - ID: "allow", + ID: appAuthAllowActionID, Text: "Authorize", }, { @@ -410,15 +428,43 @@ func authorizeApp(ar *api.Request) (interface{}, error) { }, } - ch := make(chan string) - validUntil := time.Now().Add(ttl) - n.SetActionFunction(func(ctx context.Context, n *notifications.Notification) error { + ch, actionFn := newAppAuthorization(readPermStr, writePermStr, validUntil) + n.SetActionFunction(actionFn) + + n.Save() + + select { + case key := <-ch: + if len(key) == 0 { + return nil, errAppAccessDenied + } + + return map[string]any{ + "key": key, + "validUntil": validUntil, + }, nil + case <-ar.Context().Done(): + return nil, errAppAuthTimeout + } +} + +// newAppAuthorization returns the notification action function for an app +// authorization prompt and the channel on which it reports the result: the new +// API key if the user allowed access, or a closed channel otherwise. +func newAppAuthorization(readPermStr, writePermStr string, validUntil time.Time) (<-chan string, notifications.NotificationActionFn) { + // The channel is buffered, as the requester may have gone away (request + // canceled or timed out) by the time the user responds. An unbuffered send + // would then block the action function forever while it holds the + // notification lock, which also blocks the notification cleaner. + ch := make(chan string, 1) + + return ch, func(ctx context.Context, n *notifications.Notification) error { n.Lock() defer n.Unlock() - if n.SelectedActionID != "allow" { + if n.SelectedActionID != appAuthAllowActionID { close(ch) return nil } @@ -447,21 +493,5 @@ func authorizeApp(ar *api.Request) (interface{}, error) { ch <- newKeyHex return nil - }) - - n.Save() - - select { - case key := <-ch: - if len(key) == 0 { - return nil, errors.New("access denied") - } - - return map[string]interface{}{ - "key": key, - "validUntil": validUntil, - }, nil - case <-ar.Context().Done(): - return nil, errors.New("timeout") } } diff --git a/service/core/api_test.go b/service/core/api_test.go new file mode 100644 index 000000000..8d0389eeb --- /dev/null +++ b/service/core/api_test.go @@ -0,0 +1,89 @@ +package core + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/safing/portmaster/base/api" + "github.com/safing/portmaster/base/config" + "github.com/safing/portmaster/base/notifications" + "github.com/safing/portmaster/base/rng" +) + +type configTestInstance struct { + dataDir string +} + +func (i *configTestInstance) DataDir() string { return i.dataDir } +func (i *configTestInstance) SetCmdLineOperation(func() error) {} + +var appAuthorizationTestSetup sync.Once + +func setupAppAuthorizationTest(t *testing.T) { + t.Helper() + + appAuthorizationTestSetup.Do(func() { + r, err := rng.New(struct{}{}) + if err != nil { + t.Fatalf("failed to create rng module: %s", err) + } + err = r.Start() + if err != nil { + t.Fatalf("failed to start rng module: %s", err) + } + + _, err = config.New(&configTestInstance{dataDir: t.TempDir()}) + if err != nil { + t.Fatalf("failed to create config module: %s", err) + } + err = config.Register(&config.Option{ + Name: "API Keys", + Key: api.CfgAPIKeys, + Description: "test option", + OptType: config.OptTypeStringArray, + DefaultValue: []string{}, + }) + if err != nil { + t.Fatalf("failed to register option: %s", err) + } + }) +} + +// TestAppAuthorizationAllowWithoutWaiter checks that the action function of an +// app authorization prompt does not block when the user allows access after +// the requesting API call has already returned (nobody reads the result). +// A blocked action function holds the notification lock forever, which also +// blocks the notification cleaner. +// +//nolint:paralleltest // Uses the global config. +func TestAppAuthorizationAllowWithoutWaiter(t *testing.T) { + setupAppAuthorizationTest(t) + + ch, actionFn := newAppAuthorization("user", "user", time.Now().Add(time.Hour)) + n := ¬ifications.Notification{SelectedActionID: appAuthAllowActionID} + + done := make(chan error, 1) + go func() { + done <- actionFn(context.Background(), n) + }() + + select { + case err := <-done: + if err != nil { + t.Fatalf("action function failed: %s", err) + } + case <-time.After(2 * time.Second): + t.Fatal("action function blocked because nobody waits for the result") + } + + // The notification must not stay locked. + n.Lock() + n.Unlock() //nolint:staticcheck // Only checks that the lock is free. + + // A late reader still gets the key. + if key := <-ch; key == "" { + t.Fatal("expected API key on result channel") + } +} diff --git a/service/core/update_config.go b/service/core/update_config.go index 10fdb84ca..ac11c9546 100644 --- a/service/core/update_config.go +++ b/service/core/update_config.go @@ -78,12 +78,12 @@ func registerUpdateConfig() error { err = config.Register(&config.Option{ Name: "Automatic Software Updates", Key: enableSoftwareUpdatesKey, - Description: "Automatically check for and download software updates. This does not include intelligence data updates.", + Description: "Automatically check for and download software updates from the upstream Portmaster update server. Disabled by default in portmasterpro: upstream binaries would replace this build and re-introduce SPN and account features. This does not include intelligence data updates.", OptType: config.OptTypeBool, ExpertiseLevel: config.ExpertiseLevelExpert, ReleaseLevel: config.ReleaseLevelStable, RequiresRestart: false, - DefaultValue: true, + DefaultValue: false, Annotations: config.Annotations{ config.DisplayOrderAnnotation: -12, config.CategoryAnnotation: "Updates", @@ -116,7 +116,7 @@ func registerUpdateConfig() error { func initUpdateConfig() { releaseChannel = config.Concurrent.GetAsString(ReleaseChannelKey, ReleaseChannelStable) - enableSoftwareUpdates = config.Concurrent.GetAsBool(enableSoftwareUpdatesKey, true) + enableSoftwareUpdates = config.Concurrent.GetAsBool(enableSoftwareUpdatesKey, false) enableIntelUpdates = config.Concurrent.GetAsBool(enableIntelUpdatesKey, true) initialReleaseChannel = releaseChannel() diff --git a/service/core/update_config_test.go b/service/core/update_config_test.go new file mode 100644 index 000000000..c356e70b2 --- /dev/null +++ b/service/core/update_config_test.go @@ -0,0 +1,35 @@ +package core + +import ( + "testing" + + "github.com/safing/portmaster/base/config" +) + +// TestSoftwareUpdatesDefaultOff guards the portmasterpro contract that +// upstream binary updates are opt-in: applying them would replace this build +// with stock Portmaster and re-introduce SPN and account features. +func TestSoftwareUpdatesDefaultOff(t *testing.T) { + t.Parallel() + + err := registerUpdateConfig() + if err != nil { + t.Fatalf("registerUpdateConfig: %v", err) + } + + opt, err := config.GetOption(enableSoftwareUpdatesKey) + if err != nil { + t.Fatalf("option %q not registered: %v", enableSoftwareUpdatesKey, err) + } + if v, ok := opt.DefaultValue.(bool); !ok || v { + t.Fatalf("%q default = %v, want false", enableSoftwareUpdatesKey, opt.DefaultValue) + } + + intel, err := config.GetOption(enableIntelUpdatesKey) + if err != nil { + t.Fatalf("option %q not registered: %v", enableIntelUpdatesKey, err) + } + if v, ok := intel.DefaultValue.(bool); !ok || !v { + t.Fatalf("%q default = %v, want true (filter lists and geoip stay updated)", enableIntelUpdatesKey, intel.DefaultValue) + } +} diff --git a/service/debug.go b/service/debug.go index f1a25c7bb..df13e6e2a 100644 --- a/service/debug.go +++ b/service/debug.go @@ -33,18 +33,6 @@ func (i *Instance) GetWorkerInfo() (*mgr.WorkerInfo, error) { } } } - for _, m := range i.SpnGroup.Modules() { - wi, _ := m.Manager().WorkerInfo(snapshot) // Does not fail when we provide a snapshot. - infos = append(infos, wi) - - // Check if module is a nested modules group - if gm, ok := m.(*mgr.GroupModule); ok { - for _, sm := range gm.Modules() { - wi, _ := sm.Manager().WorkerInfo(snapshot) // Does not fail when we provide a snapshot. - infos = append(infos, wi) - } - } - } return mgr.MergeWorkerInfo(infos...), nil } diff --git a/service/debug_test.go b/service/debug_test.go index 7e2ee495a..b2e06b28e 100644 --- a/service/debug_test.go +++ b/service/debug_test.go @@ -18,7 +18,6 @@ func TestDebug(t *testing.T) { t.Fatal(err) } i.serviceGroup = mgr.NewGroup(n) - i.SpnGroup = mgr.NewExtendedGroup() err = i.Start() if err != nil { t.Fatal(err) diff --git a/service/firewall/api.go b/service/firewall/api.go index 071532630..f40fa1ce7 100644 --- a/service/firewall/api.go +++ b/service/firewall/api.go @@ -129,12 +129,12 @@ func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bo // Get authenticated path. authenticatedPath := module.instance.BinaryUpdates().GetMainDir() if authenticatedPath == "" { - return false, fmt.Errorf(deniedMsgMisconfigured, api.ErrAPIAccessDeniedMessage) //nolint:stylecheck // message for user + return false, fmt.Errorf(deniedMsgMisconfigured, api.ErrAPIAccessDeniedMessage) //nolint:staticcheck // message for user } // Get real path. authenticatedPath, err = filepath.EvalSymlinks(authenticatedPath) if err != nil { - return false, fmt.Errorf(deniedMsgUnidentified, api.ErrAPIAccessDeniedMessage) //nolint:stylecheck // message for user + return false, fmt.Errorf(deniedMsgUnidentified, api.ErrAPIAccessDeniedMessage) //nolint:staticcheck // message for user } // Add filepath separator to confine to directory. authenticatedPath += string(filepath.Separator) @@ -142,7 +142,7 @@ func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bo // Get process of request. pid, _, _ := process.GetPidOfConnection(ctx, pktInfo) if pid < 0 { - return false, fmt.Errorf(deniedMsgUnidentified, api.ErrAPIAccessDeniedMessage) //nolint:stylecheck // message for user + return false, fmt.Errorf(deniedMsgUnidentified, api.ErrAPIAccessDeniedMessage) //nolint:staticcheck // message for user } proc, err := process.GetOrFindProcess(ctx, pid) if err != nil { @@ -178,6 +178,13 @@ func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bo // Add checked path to list. procsChecked = append(procsChecked, proc.Path) + // Only the webview of the app inherits the trust of its parent. + // Any other process started from the app, like a browser opened + // by a link, must not get access to the API through its parent. + if !isEmbeddedWebViewProcess(proc.Path) { + break checkLevelsLoop + } + // Get the parent process. if i < checkLevels { // save previous PID @@ -202,15 +209,15 @@ func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bo switch originalPid { case process.UnidentifiedProcessID: log.Tracer(ctx).Warningf("filter: denying api access: failed to identify process") - return true, fmt.Errorf(deniedMsgUnidentified, api.ErrAPIAccessDeniedMessage) //nolint:stylecheck // message for user + return true, fmt.Errorf(deniedMsgUnidentified, api.ErrAPIAccessDeniedMessage) //nolint:staticcheck // message for user case process.SystemProcessID: log.Tracer(ctx).Warningf("filter: denying api access: request by system") - return false, fmt.Errorf(deniedMsgSystem, api.ErrAPIAccessDeniedMessage) //nolint:stylecheck // message for user + return false, fmt.Errorf(deniedMsgSystem, api.ErrAPIAccessDeniedMessage) //nolint:staticcheck // message for user default: // normal process log.Tracer(ctx).Warningf("filter: denying api access to %s - also checked %s (trusted root is %s)", procsChecked[0], strings.Join(procsChecked[1:], " "), module.instance.BinDir()) - return false, fmt.Errorf( //nolint:stylecheck // message for user + return false, fmt.Errorf( //nolint:staticcheck // message for user deniedMsgUnauthorized, api.ErrAPIAccessDeniedMessage, strings.Join(procsChecked, "\n"), @@ -218,3 +225,22 @@ func authenticateAPIRequest(ctx context.Context, pktInfo *packet.Info) (retry bo ) } } + +// embeddedWebViewProcesses are the executables of the webview runtimes that +// the app uses to render its UI: WebView2 on Windows and WebKitGTK on Linux. +var embeddedWebViewProcesses = []string{ + "msedgewebview2.exe", + "webkitwebprocess", + "webkitnetworkprocess", +} + +// isEmbeddedWebViewProcess returns whether the given executable is a process +// of a webview runtime. +func isEmbeddedWebViewProcess(binPath string) bool { + // The path may come from another OS than the one running the check in tests. + name := binPath + if i := strings.LastIndexAny(name, `/\`); i >= 0 { + name = name[i+1:] + } + return slices.Contains(embeddedWebViewProcesses, strings.ToLower(name)) +} diff --git a/service/firewall/api_webview_test.go b/service/firewall/api_webview_test.go new file mode 100644 index 000000000..67155a4c8 --- /dev/null +++ b/service/firewall/api_webview_test.go @@ -0,0 +1,23 @@ +package firewall + +import "testing" + +func TestIsEmbeddedWebViewProcess(t *testing.T) { + t.Parallel() + + for path, want := range map[string]bool{ + `C:\Program Files (x86)\Microsoft\EdgeWebView\Application\157.0.4341.60\msedgewebview2.exe`: true, + `C:\Program Files (x86)\Microsoft\EdgeWebView\Application\157.0.4341.60\MSEDGEWEBVIEW2.EXE`: true, + "/usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/WebKitNetworkProcess": true, + "/usr/libexec/webkit2gtk-4.1/WebKitWebProcess": true, + `C:\Program Files\Mozilla Firefox\firefox.exe`: false, + `C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`: false, + "/usr/bin/firefox": false, + "/usr/bin/msedgewebview2.exe.sh": false, + "": false, + } { + if got := isEmbeddedWebViewProcess(path); got != want { + t.Errorf("isEmbeddedWebViewProcess(%q) = %v, want %v", path, got, want) + } + } +} diff --git a/service/firewall/bandwidth_pending.go b/service/firewall/bandwidth_pending.go new file mode 100644 index 000000000..aabf03f22 --- /dev/null +++ b/service/firewall/bandwidth_pending.go @@ -0,0 +1,148 @@ +package firewall + +import ( + "math" + "time" + + "github.com/safing/portmaster/service/network/packet" +) + +const ( + // pendingBandwidthTTL is how long additive bandwidth updates of an unknown + // connection are held for it. The integrations report every second, so + // this covers several reports while keeping bytes of predecessors with the + // same 5-tuple from being credited to a successor connection. + pendingBandwidthTTL = 10 * time.Second + + // pendingBandwidthMaxEntries is the maximum number of connection IDs + // that bandwidth is held for. Updates of further connection IDs are + // dropped, as they were before pending bandwidth was kept. + pendingBandwidthMaxEntries = 4096 + + // pendingBandwidthSweepInterval is the minimum interval between removals + // of expired entries. + pendingBandwidthSweepInterval = time.Second +) + +// pendingBandwidthEntry holds the bytes of additive bandwidth updates that +// could not be attributed to a connection. +type pendingBandwidthEntry struct { + bytesReceived uint64 + bytesSent uint64 + // firstHeld is when the first held update arrived. The whole entry + // expires after pendingBandwidthTTL from then. + firstHeld time.Time +} + +// pendingBandwidth holds additive bandwidth updates for connections that are +// not known (yet) and adds them to the next update of the connection. +// +// Additive updates only hold the bytes counted since the previous update. +// When no connection is found for an update, eg. because the integration +// counted bytes before the connection was registered, these bytes would be +// lost for good. They are kept for a short time only, so that bytes of long +// gone connections with the same connection ID are dropped instead of being +// credited to a successor connection. +// +// Absolute updates are not held, as the next update includes their bytes. +// +// It is not safe for concurrent use. It is owned by the bandwidth update +// handler. +type pendingBandwidth struct { + entries map[string]*pendingBandwidthEntry + lastSweep time.Time +} + +func newPendingBandwidth() *pendingBandwidth { + return &pendingBandwidth{ + entries: make(map[string]*pendingBandwidthEntry), + } +} + +// resolve handles the held bytes for the given bandwidth update. +// If connFound is false, the bytes of an additive update are held and nil is +// returned. If connFound is true, the held bytes of the connection are removed +// and returned together with the update, if they did not expire. +func (p *pendingBandwidth) resolve(bwUpdate *packet.BandwidthUpdate, connFound bool, now time.Time) *packet.BandwidthUpdate { + if now.Sub(p.lastSweep) >= pendingBandwidthSweepInterval || now.Before(p.lastSweep) { + p.sweep(now) + } + + if bwUpdate.Method != packet.Additive { + if !connFound { + return nil + } + return bwUpdate + } + + if !connFound { + p.hold(bwUpdate, now) + return nil + } + + entry, ok := p.entries[bwUpdate.ConnID] + if !ok { + return bwUpdate + } + delete(p.entries, bwUpdate.ConnID) + if p.expired(entry, now) { + return bwUpdate + } + + return &packet.BandwidthUpdate{ + ConnID: bwUpdate.ConnID, + BytesReceived: saturatingAdd(bwUpdate.BytesReceived, entry.bytesReceived), + BytesSent: saturatingAdd(bwUpdate.BytesSent, entry.bytesSent), + Method: bwUpdate.Method, + } +} + +// hold adds the bytes of the additive update to the held bytes of its +// connection ID. +func (p *pendingBandwidth) hold(bwUpdate *packet.BandwidthUpdate, now time.Time) { + entry, ok := p.entries[bwUpdate.ConnID] + if ok && p.expired(entry, now) { + // Do not extend the lifetime of expired bytes. + delete(p.entries, bwUpdate.ConnID) + ok = false + } + if !ok { + if len(p.entries) >= pendingBandwidthMaxEntries { + p.sweep(now) + if len(p.entries) >= pendingBandwidthMaxEntries { + // Drop the update rather than evicting entries that are still + // valid. + return + } + } + entry = &pendingBandwidthEntry{firstHeld: now} + p.entries[bwUpdate.ConnID] = entry + } + + entry.bytesReceived = saturatingAdd(entry.bytesReceived, bwUpdate.BytesReceived) + entry.bytesSent = saturatingAdd(entry.bytesSent, bwUpdate.BytesSent) +} + +// sweep removes expired entries. +func (p *pendingBandwidth) sweep(now time.Time) { + p.lastSweep = now + for connID, entry := range p.entries { + if p.expired(entry, now) { + delete(p.entries, connID) + } + } +} + +// expired returns whether the held bytes of the entry are too old to be +// credited to a connection. +func (p *pendingBandwidth) expired(entry *pendingBandwidthEntry, now time.Time) bool { + return now.Sub(entry.firstHeld) > pendingBandwidthTTL +} + +// saturatingAdd returns a+b, or the maximum value if that overflows. +func saturatingAdd(a, b uint64) uint64 { + if a > math.MaxUint64-b { + return math.MaxUint64 + } + return a + b +} diff --git a/service/firewall/bandwidth_pending_test.go b/service/firewall/bandwidth_pending_test.go new file mode 100644 index 000000000..e4cf683a4 --- /dev/null +++ b/service/firewall/bandwidth_pending_test.go @@ -0,0 +1,244 @@ +package firewall + +import ( + "fmt" + "math" + "testing" + "time" + + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/packet" +) + +// deliverBandwidth handles the update like updateBandwidth does, with conn +// being the connection found for it, or nil if none is found. +// It returns the bytes applied to the connection. +func deliverBandwidth(t *testing.T, p *pendingBandwidth, conn *network.Connection, bwUpdate *packet.BandwidthUpdate, now time.Time) (bytesIn, bytesOut uint64, applied bool) { + t.Helper() + + bwUpdate = p.resolve(bwUpdate, conn != nil, now) + if conn == nil { + if bwUpdate != nil { + t.Fatal("update of an unknown connection must not be returned") + } + return 0, 0, false + } + bytesIn, bytesOut, applied = applyBandwidthUpdate(conn, bwUpdate) + if applied { + conn.Unlock() + } + return bytesIn, bytesOut, applied +} + +func additiveUpdate(connID string, received, sent uint64) *packet.BandwidthUpdate { + return &packet.BandwidthUpdate{ + ConnID: connID, + BytesReceived: received, + BytesSent: sent, + Method: packet.Additive, + } +} + +func expectApplied(t *testing.T, gotIn, gotOut uint64, applied bool, wantIn, wantOut uint64) { + t.Helper() + + if !applied { + t.Fatal("update was not applied") + } + if gotIn != wantIn || gotOut != wantOut { + t.Errorf("applied %d/%d bytes, want %d/%d", gotIn, gotOut, wantIn, wantOut) + } +} + +// testConnID is a connection ID as the bandwidth integrations create it. +var testConnID = packet.CreateConnectionID( + packet.UDP, + []byte{127, 0, 0, 1}, 1000, + []byte{8, 8, 8, 8}, 53, + false, +) + +// TestPendingBandwidthCreditedOnce checks that the bytes of additive updates +// that arrive before their connection is known are credited to the connection +// once it is found, and only once. +func TestPendingBandwidthCreditedOnce(t *testing.T) { + t.Parallel() + + p := newPendingBandwidth() + conn := &network.Connection{} + start := time.Unix(1_000_000, 0) + + // The connection is not known yet. + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 100, 10), start) + + // The connection is found with the next update. + bytesIn, bytesOut, applied := deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 5, 1), start.Add(time.Second)) + expectApplied(t, bytesIn, bytesOut, applied, 105, 11) + + // The held bytes are not credited again. + bytesIn, bytesOut, applied = deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 5, 1), start.Add(2*time.Second)) + expectApplied(t, bytesIn, bytesOut, applied, 5, 1) + if conn.BytesReceived != 110 || conn.BytesSent != 12 { + t.Errorf("connection has %d/%d bytes, want 110/12", conn.BytesReceived, conn.BytesSent) + } + if len(p.entries) != 0 { + t.Errorf("%d entries are still held", len(p.entries)) + } +} + +// TestPendingBandwidthAccumulates checks that several updates of an unknown +// connection are added up. +func TestPendingBandwidthAccumulates(t *testing.T) { + t.Parallel() + + p := newPendingBandwidth() + conn := &network.Connection{} + start := time.Unix(1_000_000, 0) + + for i := range 5 { + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 100, 10), start.Add(time.Duration(i)*time.Second)) + } + bytesIn, bytesOut, applied := deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 1, 1), start.Add(5*time.Second)) + expectApplied(t, bytesIn, bytesOut, applied, 501, 51) + + // Held bytes do not wrap around. + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, math.MaxUint64-1, 0), start) + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 2, 0), start) + bwUpdate := p.resolve(additiveUpdate(testConnID, 1, 0), true, start) + if bwUpdate.BytesReceived != math.MaxUint64 { + t.Errorf("got %d received bytes, want %d", bwUpdate.BytesReceived, uint64(math.MaxUint64)) + } +} + +// TestPendingBandwidthExpires checks that held bytes older than the TTL are +// dropped instead of being credited to a connection, as they may belong to a +// predecessor with the same connection ID. +func TestPendingBandwidthExpires(t *testing.T) { + t.Parallel() + + start := time.Unix(1_000_000, 0) + afterTTL := start.Add(pendingBandwidthTTL + time.Second) + + // Expired when the connection is found. + p := newPendingBandwidth() + conn := &network.Connection{} + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 100, 10), start) + bytesIn, bytesOut, applied := deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 5, 1), afterTTL) + expectApplied(t, bytesIn, bytesOut, applied, 5, 1) + if len(p.entries) != 0 { + t.Errorf("%d entries are still held", len(p.entries)) + } + + // Removed by the sweep, triggered by any update. + p = newPendingBandwidth() + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 100, 10), start) + deliverBandwidth(t, p, nil, additiveUpdate("other", 1, 1), afterTTL) + if _, ok := p.entries[testConnID]; ok { + t.Error("expired entry was not removed") + } + + // Further updates do not extend the lifetime of held bytes: Only what was + // held within the TTL is credited. + p = newPendingBandwidth() + conn = &network.Connection{} + for i := range 2 * int(pendingBandwidthTTL/time.Second) { + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 100, 0), start.Add(time.Duration(i)*time.Second)) + } + bytesIn, bytesOut, applied = deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 1, 0), start.Add(2*pendingBandwidthTTL)) + if !applied || bytesIn > 1+100*uint64(pendingBandwidthTTL/time.Second) || bytesOut != 0 { + t.Errorf("applied %d/%d bytes, want at most %d/0", bytesIn, bytesOut, 1+100*uint64(pendingBandwidthTTL/time.Second)) + } +} + +// TestPendingBandwidthLimit checks that the held updates do not grow beyond +// the limit. +func TestPendingBandwidthLimit(t *testing.T) { + t.Parallel() + + p := newPendingBandwidth() + start := time.Unix(1_000_000, 0) + + for i := range pendingBandwidthMaxEntries + 100 { + deliverBandwidth(t, p, nil, additiveUpdate(fmt.Sprintf("conn-%d", i), 100, 10), start) + } + if len(p.entries) != pendingBandwidthMaxEntries { + t.Errorf("%d entries are held, want %d", len(p.entries), pendingBandwidthMaxEntries) + } + + // Held connections still accumulate, the dropped ones were not held. + deliverBandwidth(t, p, nil, additiveUpdate("conn-0", 100, 10), start) + conn := &network.Connection{} + bytesIn, bytesOut, applied := deliverBandwidth(t, p, conn, additiveUpdate("conn-0", 0, 0), start) + expectApplied(t, bytesIn, bytesOut, applied, 200, 20) + conn = &network.Connection{} + bytesIn, bytesOut, applied = deliverBandwidth(t, p, conn, additiveUpdate(fmt.Sprintf("conn-%d", pendingBandwidthMaxEntries+50), 1, 1), start) + expectApplied(t, bytesIn, bytesOut, applied, 1, 1) + + // Expired entries make room. + deliverBandwidth(t, p, nil, additiveUpdate("new", 1, 1), start.Add(pendingBandwidthTTL+time.Second)) + if len(p.entries) != 1 { + t.Errorf("%d entries are held, want 1", len(p.entries)) + } +} + +// TestPendingBandwidthAbsolute checks that absolute updates are not held. +func TestPendingBandwidthAbsolute(t *testing.T) { + t.Parallel() + + p := newPendingBandwidth() + start := time.Unix(1_000_000, 0) + absolute := &packet.BandwidthUpdate{ + ConnID: testConnID, + BytesReceived: 1000, + BytesSent: 100, + Method: packet.Absolute, + } + + if p.resolve(absolute, false, start) != nil { + t.Error("update of an unknown connection must not be returned") + } + if len(p.entries) != 0 { + t.Errorf("%d entries are held, want 0", len(p.entries)) + } + if p.resolve(absolute, true, start) != absolute { + t.Error("absolute update was changed") + } + + // Held additive bytes are not added to absolute updates. + p.resolve(additiveUpdate(testConnID, 1, 1), false, start) + if got := p.resolve(absolute, true, start); got != absolute { + t.Errorf("absolute update was changed: %s", got) + } +} + +// TestPendingBandwidthLockedConnection checks that held bytes that are added +// to an update for a locked connection are deferred with the update and +// credited once. +func TestPendingBandwidthLockedConnection(t *testing.T) { + t.Parallel() + + p := newPendingBandwidth() + conn := &network.Connection{} + start := time.Unix(1_000_000, 0) + + deliverBandwidth(t, p, nil, additiveUpdate(testConnID, 100, 10), start) + + // The connection is found, but locked: The update is deferred. + conn.Lock() + if _, _, applied := deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 5, 1), start.Add(time.Second)); applied { + t.Fatal("update must not be applied to a locked connection") + } + conn.Unlock() + if len(p.entries) != 0 { + t.Errorf("%d entries are still held", len(p.entries)) + } + + // The next update includes the deferred and the held bytes, once. + bytesIn, bytesOut, applied := deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 1, 1), start.Add(2*time.Second)) + expectApplied(t, bytesIn, bytesOut, applied, 106, 12) + bytesIn, bytesOut, applied = deliverBandwidth(t, p, conn, additiveUpdate(testConnID, 1, 1), start.Add(3*time.Second)) + expectApplied(t, bytesIn, bytesOut, applied, 1, 1) + if conn.BytesReceived != 107 || conn.BytesSent != 13 { + t.Errorf("connection has %d/%d bytes, want 107/13", conn.BytesReceived, conn.BytesSent) + } +} diff --git a/service/firewall/config.go b/service/firewall/config.go index 34cbe4e83..812992134 100644 --- a/service/firewall/config.go +++ b/service/firewall/config.go @@ -7,7 +7,6 @@ import ( "github.com/safing/portmaster/base/config" "github.com/safing/portmaster/base/notifications" "github.com/safing/portmaster/service/core" - "github.com/safing/portmaster/spn/captain" ) // Configuration Keys. @@ -136,9 +135,6 @@ var ( devMode config.BoolOption apiListenAddress config.StringOption - tunnelEnabled config.BoolOption - useCommunityNodes config.BoolOption - configReady = abool.New() ) @@ -146,8 +142,5 @@ func getConfig() { devMode = config.Concurrent.GetAsBool(core.CfgDevModeKey, false) apiListenAddress = config.GetAsString(api.CfgDefaultListenAddressKey, "") - tunnelEnabled = config.Concurrent.GetAsBool(captain.CfgOptionEnableSPNKey, false) - useCommunityNodes = config.Concurrent.GetAsBool(captain.CfgOptionUseCommunityNodesKey, true) - configReady.Set() } diff --git a/service/firewall/decide_bench_test.go b/service/firewall/decide_bench_test.go new file mode 100644 index 000000000..c58ff386c --- /dev/null +++ b/service/firewall/decide_bench_test.go @@ -0,0 +1,222 @@ +package firewall + +import ( + "context" + "net" + "reflect" + "sync" + "sync/atomic" + "testing" + "unsafe" + + "github.com/tevino/abool" + + "github.com/safing/portmaster/base/config" + "github.com/safing/portmaster/base/log" + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/netutils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/process" + "github.com/safing/portmaster/service/profile" + "github.com/safing/portmaster/service/resolver" +) + +type benchProfileInstance struct { + dataDir string +} + +func (i benchProfileInstance) DataDir() string { return i.dataDir } +func (i benchProfileInstance) Config() *config.Config { return nil } + +// benchInstance provides the modules the deciders use. +type benchInstance struct { + instance + + resolver *resolver.ResolverModule +} + +func (i benchInstance) Resolver() *resolver.ResolverModule { return i.resolver } + +// unexportedFieldOffset returns the offset of an unexported field of a struct +// from another package. Complete connections and processes with a profile can +// otherwise only be created by the packet path with all modules running. +func unexportedFieldOffset(tb testing.TB, structType reflect.Type, name string) uintptr { + tb.Helper() + + field, ok := structType.FieldByName(name) + if !ok { + tb.Fatalf("field %s not found", name) + } + return field.Offset +} + +// fieldAt returns a pointer to the field of type T at the given offset. +func fieldAt[T any](structPtr unsafe.Pointer, offset uintptr) *T { + return (*T)(unsafe.Add(structPtr, offset)) //nolint:gosec // Test-only access to an unexported field. +} + +var ( + benchSetup sync.Once + errBenchSetup error +) + +// BenchmarkDecideOnConnection measures the firewall decision for the first +// packet of an outbound connection of a process with a profile that has +// endpoint rules, none of which match: all deciders run and the default +// action is applied. +func BenchmarkDecideOnConnection(b *testing.B) { + runDecideBench(b, nil, nil, network.VerdictAccept) +} + +// benchFilterListIDs are the source IDs of the filter lists that are active in +// the profile of BenchmarkDecideOnConnectionWithLists. The default categories +// resolve to about this many sources. +var benchFilterListIDs = []string{ + "TRAC-1", "TRAC-2", "TRAC-3", "TRAC-4", "TRAC-5", + "MAL-1", "MAL-2", "MAL-3", + "BAD-1", "BAD-2", + "UNBREAK-1", "UNBREAK-2", +} + +// BenchmarkDecideOnConnectionWithLists is BenchmarkDecideOnConnection with +// filter lists active in the profile, so that the filter list decider matches +// the list occurrences of the entity against them. +// +// The filter list lookup itself is not set up: it needs the bloom filter and +// the cache database of the filterlists module. The entity looks up its +// domains like with lists that are not loaded yet, and the list occurrences +// that the lookup would have found are set on the entity before the decision. +func BenchmarkDecideOnConnectionWithLists(b *testing.B) { + b.Run("unlisted", func(b *testing.B) { + // The entity is in no filter list, like almost all entities. + runDecideBench(b, benchFilterListIDs, nil, network.VerdictAccept) + }) + b.Run("inactive", func(b *testing.B) { + // The entity is only in filter lists that are not active. + runDecideBench(b, benchFilterListIDs, map[string][]string{ + "example.com.": {"SOC-1", "SOC-2"}, + "15133": {"ASN-1"}, + }, network.VerdictAccept) + }) + b.Run("listed", func(b *testing.B) { + // A parent domain of the entity and its CNAME are in active filter lists. + runDecideBench(b, benchFilterListIDs, map[string][]string{ + "example.com.": {"MAL-2", "SOC-1", "TRAC-3"}, + "e1.example.net.": {"CDN-1", "TRAC-4"}, + "15133": {"ASN-1"}, + }, network.VerdictBlock) + }) +} + +// runDecideBench runs the decision benchmark with the given active filter +// lists in the profile and the given list occurrences of the entity. +func runDecideBench(b *testing.B, filterListIDs []string, listOccurrences map[string][]string, wantVerdict network.Verdict) { + b.Helper() + + // The profile module registers the profile config options, which may only + // be done once. Start logging, as log lines are otherwise kept in waiting + // goroutines, and only log critical errors. + benchSetup.Do(func() { + _, errBenchSetup = profile.NewModule(benchProfileInstance{dataDir: b.TempDir()}) + if errBenchSetup == nil { + errBenchSetup = registerConfig() + } + if errBenchSetup == nil { + errBenchSetup = log.Start("critical", true, "") + } + }) + if errBenchSetup != nil { + b.Fatal(errBenchSetup) + } + prevModule := module + module = &Firewall{instance: benchInstance{resolver: &resolver.ResolverModule{}}} + b.Cleanup(func() { module = prevModule }) + + profileConfig := map[string]any{ + profile.CfgOptionDefaultActionKey: profile.DefaultActionPermitValue, + profile.CfgOptionEndpointsKey: []any{ + "- *.ads.example.org", + "- tracker.example.net", + "- AS64496", + "- 203.0.113.0/24", + "+ *.example.com TCP/80", + "- 198.51.100.7", + "- * */9999", + }, + } + // profile.New only logs an invalid config. + _, err := config.NewPerspective(config.Expand(profileConfig)) + if err != nil { + b.Fatal(err) + } + localProfile := profile.New(&profile.Profile{ + ID: "bench", + Source: profile.SourceLocal, + Name: "Bench", + Config: profileConfig, + }) + if filterListIDs != nil { + // Resolving the filter list IDs of the config needs the list index of + // the filterlists module: Set the resolved IDs directly. + profileType := reflect.TypeFor[profile.Profile]() + *fieldAt[[]string](unsafe.Pointer(localProfile), unexportedFieldOffset(b, profileType, "filterListIDs")) = filterListIDs //nolint:gosec + *fieldAt[bool](unsafe.Pointer(localProfile), unexportedFieldOffset(b, profileType, "filterListsSet")) = true //nolint:gosec + } + layeredProfile := profile.NewLayeredProfile(localProfile) + // A new layered profile needs an update for the global config, which + // would reset the list occurrences of the first entity. + layeredProfile.Update(nil, nil) + proc := &process.Process{Pid: 1234, Path: "/usr/lib/firefox/firefox"} + fieldAt[atomic.Pointer[profile.LayeredProfile]]( + unsafe.Pointer(proc), //nolint:gosec // Test-only access to an unexported field. + unexportedFieldOffset(b, reflect.TypeFor[process.Process](), "profile"), + ).Store(layeredProfile) + + connProcess := unexportedFieldOffset(b, reflect.TypeFor[network.Connection](), "process") + connDataComplete := unexportedFieldOffset(b, reflect.TypeFor[network.Connection](), "dataComplete") + entityLocationOnce := unexportedFieldOffset(b, reflect.TypeFor[intel.Entity](), "fetchLocationOnce") + + pkt := newVerdictTestPacket(packet.TCP, false) + ctx := context.Background() + dataComplete := abool.NewBool(true) + + b.ReportAllocs() + for b.Loop() { + conn := &network.Connection{ + ID: "bench", + Type: network.IPConnection, + IPVersion: packet.IPv4, + IPProtocol: packet.TCP, + LocalIP: net.IPv4(192, 168, 1, 10), + LocalPort: 40000, + PID: 1234, + Entity: (&intel.Entity{ + IP: net.IPv4(93, 184, 216, 34), + IPScope: netutils.Global, + Protocol: 6, + Port: 443, + Domain: "www.example.com.", + CNAME: []string{"e1.example.net."}, + Country: "US", + ASN: 15133, + ASOrg: "Edgecast Inc.", + // Set the list occurrences the filter list lookup would find. + ListOccurences: listOccurrences, + }).Init(443), + } + // The location was already looked up when the entity was created; the + // geoip database is not available here. + fieldAt[sync.Once](unsafe.Pointer(conn.Entity), entityLocationOnce).Do(func() {}) //nolint:gosec + *fieldAt[*process.Process](unsafe.Pointer(conn), connProcess) = proc //nolint:gosec + *fieldAt[*abool.AtomicBool](unsafe.Pointer(conn), connDataComplete) = dataComplete //nolint:gosec + + conn.Lock() + decideOnConnection(ctx, conn, pkt) + verdict := conn.Verdict + conn.Unlock() + if verdict != wantVerdict { + b.Fatalf("unexpected verdict %s: %+v", verdict, conn.Reason) + } + } +} diff --git a/service/firewall/default_handler_test.go b/service/firewall/default_handler_test.go new file mode 100644 index 000000000..2e13a6aac --- /dev/null +++ b/service/firewall/default_handler_test.go @@ -0,0 +1,386 @@ +package firewall + +import ( + "net" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" + + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/packet" +) + +// verdictTestPacket is a real (not info-only) packet that counts the verdicts +// that are applied to it. +type verdictTestPacket struct { + packet.Base + + accepted, blocked, dropped atomic.Uint64 + permAccepted, permBlocked, permDropped atomic.Uint64 + rerouted atomic.Uint64 + + // layers is returned by Layers, if set. LoadPacketData succeeds then. + layers gopacket.Packet +} + +func newVerdictTestPacket(protocol packet.IPProtocol, inbound bool) *verdictTestPacket { + pkt := &verdictTestPacket{} + pkt.SetPacketInfo(packet.Info{ + Inbound: inbound, + Version: packet.IPv4, + Protocol: protocol, + Src: net.IPv4(192, 168, 1, 10), + SrcPort: 40000, + Dst: net.IPv4(1, 1, 1, 1), + DstPort: 443, + SeenAt: time.Now(), + }) + return pkt +} + +func (pkt *verdictTestPacket) Accept() error { pkt.accepted.Add(1); return nil } +func (pkt *verdictTestPacket) Block() error { pkt.blocked.Add(1); return nil } +func (pkt *verdictTestPacket) Drop() error { pkt.dropped.Add(1); return nil } +func (pkt *verdictTestPacket) PermanentAccept() error { pkt.permAccepted.Add(1); return nil } +func (pkt *verdictTestPacket) PermanentBlock() error { pkt.permBlocked.Add(1); return nil } +func (pkt *verdictTestPacket) PermanentDrop() error { pkt.permDropped.Add(1); return nil } +func (pkt *verdictTestPacket) RerouteToNameserver() error { pkt.rerouted.Add(1); return nil } +func (pkt *verdictTestPacket) RerouteToSplitTun() error { pkt.rerouted.Add(1); return nil } + +func (pkt *verdictTestPacket) LoadPacketData() error { + if pkt.layers == nil { + return packet.ErrFailedToLoadPayload + } + return nil +} + +func (pkt *verdictTestPacket) Layers() gopacket.Packet { return pkt.layers } + +func (pkt *verdictTestPacket) total() uint64 { + return pkt.accepted.Load() + pkt.blocked.Load() + pkt.dropped.Load() + + pkt.permAccepted.Load() + pkt.permBlocked.Load() + pkt.permDropped.Load() + + pkt.rerouted.Load() +} + +// setupDefaultHandlerTest prepares the globals that the default firewall +// handler depends on. +func setupDefaultHandlerTest(tb testing.TB, permanent bool) { + tb.Helper() + + network.SetDefaultFirewallHandler(defaultFirewallHandler, defaultLockFreeFirewallHandler) + + prevPermanentVerdicts := permanentVerdicts + permanentVerdicts = func() bool { return permanent } + tb.Cleanup(func() { + permanentVerdicts = prevPermanentVerdicts + }) +} + +// newDecidedConnection returns a connection that is fully decided and has no +// firewall handler, so that its packets are handled by the default handler +// directly on the dispatching goroutine. +func newDecidedConnection(verdict network.Verdict) *network.Connection { + conn := &network.Connection{ + ID: "default-handler-test", + Type: network.IPConnection, + IPVersion: packet.IPv4, + IPProtocol: packet.TCP, + } + conn.Lock() + conn.SetVerdictDirectly(verdict) + conn.Unlock() + return conn +} + +// TestDefaultHandlerRacesWithVerdictUpdate checks that packets of decided +// connections, which are handled on the packet dispatching goroutine without +// locking the connection, do not race with a re-evaluation of the connection, +// which changes the verdict state while holding the connection lock. +func TestDefaultHandlerRacesWithVerdictUpdate(t *testing.T) { //nolint:paralleltest // Modifies package globals. + setupDefaultHandlerTest(t, true) + + const rounds = 2000 + conn := newDecidedConnection(network.VerdictAccept) + pkt := newVerdictTestPacket(packet.TCP, false) + + var wg sync.WaitGroup + + // Packet dispatcher. + wg.Go(func() { + for range rounds { + conn.HandlePacket(pkt) + } + }) + + // Verdict re-evaluation, as done by resetConnectionVerdict. + wg.Go(func() { + for i := range rounds { + conn.Lock() + if i%2 == 0 { + conn.SetVerdict(network.VerdictBlock, "test", "", nil) + } else { + conn.SetVerdict(network.VerdictAccept, "test", "", nil) + } + // Also check the lock order: connection lock, then packet queue lock. + conn.StopFirewallHandler() + conn.Unlock() + } + }) + + wg.Wait() + + // Every packet must have received exactly one verdict. + if pkt.total() != rounds { + t.Errorf("expected %d verdicts, got %d", rounds, pkt.total()) + } + if pkt.dropped.Load() != 0 || pkt.permDropped.Load() != 0 || pkt.rerouted.Load() != 0 { + t.Errorf("unexpected verdicts: %d dropped, %d permanently dropped, %d rerouted", + pkt.dropped.Load(), pkt.permDropped.Load(), pkt.rerouted.Load()) + } +} + +// newICMPEchoTestPacket returns an ICMP echo request packet. +func newICMPEchoTestPacket(t *testing.T, inbound bool) *verdictTestPacket { + t.Helper() + + buf := gopacket.NewSerializeBuffer() + err := gopacket.SerializeLayers(buf, + gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}, + &layers.IPv4{ + Version: 4, + IHL: 5, + TTL: 64, + Protocol: layers.IPProtocolICMPv4, + SrcIP: net.IPv4(192, 168, 1, 10), + DstIP: net.IPv4(1, 1, 1, 1), + }, + &layers.ICMPv4{ + TypeCode: layers.CreateICMPv4TypeCode(layers.ICMPv4TypeEchoRequest, 0), + Id: 1, + Seq: 1, + }, + gopacket.Payload([]byte("ping")), + ) + if err != nil { + t.Fatal(err) + } + + pkt := newVerdictTestPacket(packet.ICMP, inbound) + pkt.layers = gopacket.NewPacket(buf.Bytes(), layers.LayerTypeIPv4, gopacket.Default) + if pkt.layers.ErrorLayer() != nil { + t.Fatal(pkt.layers.ErrorLayer().Error()) + } + return pkt +} + +// handlePacketWithTimeout handles the packet like the packet dispatcher and +// fails the test if that blocks. +func handlePacketWithTimeout(t *testing.T, conn *network.Connection, pkt packet.Packet) { + t.Helper() + + done := make(chan struct{}) + go func() { + defer close(done) + conn.HandlePacket(pkt) + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("packet dispatching is blocked by the locked connection") + } +} + +// TestDefaultHandlerDoesNotWaitForConnectionLock checks that the packet +// dispatcher is never blocked by a connection that is locked, eg. because it +// is being re-evaluated, and applies the last published verdict instead. +func TestDefaultHandlerDoesNotWaitForConnectionLock(t *testing.T) { //nolint:paralleltest // Modifies package globals. + setupDefaultHandlerTest(t, false) + + conn := newDecidedConnection(network.VerdictAccept) + pkt := newVerdictTestPacket(packet.TCP, false) + + // Change the verdict, but keep the connection locked. + conn.Lock() + conn.SetVerdictDirectly(network.VerdictBlock) + + handlePacketWithTimeout(t, conn, pkt) + if pkt.accepted.Load() != 1 || pkt.total() != 1 { + t.Errorf("expected the published verdict to be applied while the connection is locked, got %d accepted of %d", pkt.accepted.Load(), pkt.total()) + } + + // The new verdict applies as soon as the connection is unlocked. + conn.Unlock() + handlePacketWithTimeout(t, conn, pkt) + if pkt.blocked.Load() != 1 || pkt.total() != 2 { + t.Errorf("expected the new verdict to be applied after unlocking, got %d blocked of %d", pkt.blocked.Load(), pkt.total()) + } + + // Stopping the firewall handler publishes the verdict state right away, + // as packets are handled without the lock from then on. + conn.Lock() + conn.SetVerdictDirectly(network.VerdictDrop) + conn.StopFirewallHandler() + handlePacketWithTimeout(t, conn, pkt) + conn.Unlock() + if pkt.dropped.Load() != 1 || pkt.total() != 3 { + t.Errorf("expected the verdict at the time the handler was stopped, got %d dropped of %d", pkt.dropped.Load(), pkt.total()) + } +} + +// TestDefaultHandlerEnablesPermanentVerdict checks that the default handler +// makes the verdict permanent without locking the connection and that the +// connection adopts this. +func TestDefaultHandlerEnablesPermanentVerdict(t *testing.T) { //nolint:paralleltest // Modifies package globals. + setupDefaultHandlerTest(t, true) + + conn := newDecidedConnection(network.VerdictBlock) + pkt := newVerdictTestPacket(packet.TCP, false) + + // Handle a packet while the connection is locked and changed. + conn.Lock() + conn.SetVerdictDirectly(network.VerdictAccept) + handlePacketWithTimeout(t, conn, pkt) + if pkt.permBlocked.Load() != 1 || pkt.total() != 1 { + t.Errorf("expected a permanent block, got %d of %d", pkt.permBlocked.Load(), pkt.total()) + } + conn.Unlock() + + // Neither the permanent flag nor the changed verdict may be lost. + state := conn.VerdictState() + if !state.VerdictPermanent || state.Verdict != network.VerdictAccept { + t.Errorf("unexpected verdict state after unlocking: %+v", state) + } + conn.Lock() + if !conn.VerdictPermanent { + t.Error("connection did not adopt the permanent verdict") + } + conn.Unlock() + + handlePacketWithTimeout(t, conn, pkt) + if pkt.permAccepted.Load() != 1 || pkt.total() != 2 { + t.Errorf("expected a permanent accept, got %d of %d", pkt.permAccepted.Load(), pkt.total()) + } + + // Info-only packets never get a verdict. + handlePacketWithTimeout(t, conn, packet.NewInfoPacket(*pkt.Info())) + if pkt.total() != 2 { + t.Errorf("unexpected verdict count %d", pkt.total()) + } +} + +// TestDefaultHandlerICMP checks the handling of ICMP packets of connections +// without a firewall handler. +func TestDefaultHandlerICMP(t *testing.T) { //nolint:paralleltest // Modifies package globals. + setupDefaultHandlerTest(t, true) + + // Create an inbound ICMP connection that was accepted, eg. by fast-tracking. + inboundPkt := newICMPEchoTestPacket(t, true) + conn := network.NewIncompleteConnection(inboundPkt) + conn.Lock() + conn.SetVerdictDirectly(network.VerdictAccept) + conn.StopFirewallHandler() + conn.Unlock() + if !conn.VerdictState().Inbound { + t.Fatal("connection must be inbound") + } + + // Packets that cannot be loaded are dropped. + brokenPkt := newVerdictTestPacket(packet.ICMP, true) + handlePacketWithTimeout(t, conn, brokenPkt) + if brokenPkt.dropped.Load() != 1 || brokenPkt.total() != 1 { + t.Errorf("expected broken packet to be dropped, got %d of %d", brokenPkt.dropped.Load(), brokenPkt.total()) + } + + // Inbound packets get the verdict of the connection, never a permanent one. + handlePacketWithTimeout(t, conn, inboundPkt) + if inboundPkt.accepted.Load() != 1 || inboundPkt.total() != 1 { + t.Errorf("expected inbound packet to be accepted, got %d of %d", inboundPkt.accepted.Load(), inboundPkt.total()) + } + + // An outbound packet changes the direction of the connection. This needs + // the connection lock, so it is skipped while the connection is locked. + outboundPkt := newICMPEchoTestPacket(t, false) + conn.Lock() + handlePacketWithTimeout(t, conn, outboundPkt) + conn.Unlock() + if outboundPkt.accepted.Load() != 1 || outboundPkt.total() != 1 { + t.Errorf("expected outbound packet to be accepted, got %d of %d", outboundPkt.accepted.Load(), outboundPkt.total()) + } + if !conn.VerdictState().Inbound { + t.Error("direction must not change while the connection is locked") + } + + // The next outbound packet changes the direction. + handlePacketWithTimeout(t, conn, outboundPkt) + if outboundPkt.accepted.Load() != 2 || outboundPkt.total() != 2 { + t.Errorf("expected outbound packet to be accepted, got %d of %d", outboundPkt.accepted.Load(), outboundPkt.total()) + } + if conn.VerdictState().Inbound { + t.Error("direction did not change to outbound") + } + conn.Lock() + if conn.Inbound || conn.VerdictPermanent { + t.Errorf("unexpected connection state: inbound=%v permanent=%v", conn.Inbound, conn.VerdictPermanent) + } + conn.Unlock() +} + +// TestDefaultHandlerICMPRacesWithConnectionUpdate checks that ICMP packets +// handled by the default handler do not race with users of the connection. +func TestDefaultHandlerICMPRacesWithConnectionUpdate(t *testing.T) { //nolint:paralleltest // Modifies package globals. + setupDefaultHandlerTest(t, true) + + const rounds = 2000 + inboundPkt := newICMPEchoTestPacket(t, true) + inboundPkt.Info().SrcPort = 1 // Use a distinct connection ID. + outboundPkt := newICMPEchoTestPacket(t, false) + conn := network.NewIncompleteConnection(inboundPkt) + conn.Lock() + conn.SetVerdictDirectly(network.VerdictAccept) + conn.StopFirewallHandler() + conn.Unlock() + + var wg sync.WaitGroup + wg.Go(func() { + for range rounds { + conn.HandlePacket(outboundPkt) + } + }) + wg.Go(func() { + for i := range rounds { + conn.Lock() + // Flip the direction back and re-evaluate. + conn.Inbound = true + if i%2 == 0 { + conn.SetVerdict(network.VerdictBlock, "test", "", nil) + } else { + conn.SetVerdict(network.VerdictAccept, "test", "", nil) + } + conn.Unlock() + } + }) + wg.Wait() + + if outboundPkt.total() != rounds { + t.Errorf("expected %d verdicts, got %d", rounds, outboundPkt.total()) + } +} + +func BenchmarkDefaultHandlerPacketPath(b *testing.B) { + setupDefaultHandlerTest(b, true) + + conn := newDecidedConnection(network.VerdictAccept) + pkt := newVerdictTestPacket(packet.TCP, false) + conn.HandlePacket(pkt) + + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + conn.HandlePacket(pkt) + } +} diff --git a/service/firewall/dns.go b/service/firewall/dns.go index e34347089..806c4348d 100644 --- a/service/firewall/dns.go +++ b/service/firewall/dns.go @@ -313,8 +313,7 @@ func formatRR(rr dns.RR) string { func SaveIPsInCache(ips []net.IP, profileID string, record resolver.ResolvedDomain) { // Package IPs and CNAMEs into IPInfo structs. for _, ip := range ips { - // Never save domain attributions for localhost IPs. - if netutils.GetIPScope(ip) == netutils.HostLocal { + if !resolver.RecordDomainsFor(ip) { continue } diff --git a/service/firewall/inspection/inspection.go b/service/firewall/inspection/inspection.go index a8a2448fa..72c0af8b4 100644 --- a/service/firewall/inspection/inspection.go +++ b/service/firewall/inspection/inspection.go @@ -7,7 +7,6 @@ import ( "github.com/safing/portmaster/service/network/packet" ) -//nolint:golint,stylecheck const ( DO_NOTHING uint8 = iota BLOCK_PACKET diff --git a/service/firewall/interception/dnscache_linux.go b/service/firewall/interception/dnscache_linux.go new file mode 100644 index 000000000..cd229ff4b --- /dev/null +++ b/service/firewall/interception/dnscache_linux.go @@ -0,0 +1,41 @@ +package interception + +import ( + "context" + "errors" + "time" + + "github.com/godbus/dbus/v5" + + "github.com/safing/portmaster/base/log" +) + +// flushSystemDNSCache clears the cache of systemd-resolved, like +// "resolvectl flush-caches". Names resolved before the interception started +// are cached there, so apps would reach their IPs without a DNS query that +// Portmaster sees: the connections would miss the requested domain and its +// CNAMEs, and domain rules would not apply to them until the entries expire. +func flushSystemDNSCache() { + conn, err := dbus.ConnectSystemBus() + if err != nil { + log.Debugf("interception: cannot connect to the system bus to flush the systemd-resolved cache: %s", err) + return + } + defer func() { _ = conn.Close() }() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + err = conn.Object("org.freedesktop.resolve1", "/org/freedesktop/resolve1"). + CallWithContext(ctx, "org.freedesktop.resolve1.Manager.FlushCaches", 0).Err + if err != nil { + dbusErr, ok := errors.AsType[dbus.Error](err) + if ok && dbusErr.Name == "org.freedesktop.DBus.Error.ServiceUnknown" { + // systemd-resolved is not in use. + return + } + log.Warningf("interception: failed to flush the systemd-resolved cache: %s", err) + return + } + log.Info("interception: flushed the systemd-resolved cache") +} diff --git a/service/firewall/interception/dnscache_windows.go b/service/firewall/interception/dnscache_windows.go new file mode 100644 index 000000000..c8c153767 --- /dev/null +++ b/service/firewall/interception/dnscache_windows.go @@ -0,0 +1,28 @@ +package interception + +import ( + "golang.org/x/sys/windows" + + "github.com/safing/portmaster/base/log" +) + +var procDnsFlushResolverCache = windows.NewLazySystemDLL("dnsapi.dll").NewProc("DnsFlushResolverCache") + +// flushSystemDNSCache clears the cache of the Windows DNS Client service, like +// "ipconfig /flushdns". Names resolved before the interception started are +// cached there, so apps would reach their IPs without a DNS query that +// Portmaster sees: the connections would have no domain, and domain rules +// would not apply to them until the cache entries expire. +func flushSystemDNSCache() { + err := procDnsFlushResolverCache.Find() + if err != nil { + log.Warningf("interception: cannot flush the DNS Client cache: %s", err) + return + } + ok, _, callErr := procDnsFlushResolverCache.Call() + if ok == 0 { + log.Warningf("interception: failed to flush the DNS Client cache: %s", callErr) + return + } + log.Info("interception: flushed the DNS Client cache") +} diff --git a/service/firewall/interception/dnsmonitor/eventlistener_windows.go b/service/firewall/interception/dnsmonitor/eventlistener_windows.go index d71c3c432..b0f106cac 100644 --- a/service/firewall/interception/dnsmonitor/eventlistener_windows.go +++ b/service/firewall/interception/dnsmonitor/eventlistener_windows.go @@ -9,6 +9,7 @@ import ( "net" "strconv" "strings" + "sync/atomic" "github.com/miekg/dns" "github.com/safing/portmaster/service/mgr" @@ -17,7 +18,9 @@ import ( ) type Listener struct { - etw *ETWSession + // etw is set once the integration DLL is loaded, which may happen after + // the module started, from another goroutine. + etw atomic.Pointer[ETWSession] } func newListener(module *DNSMonitor) (*Listener, error) { @@ -41,35 +44,39 @@ func newListener(module *DNSMonitor) (*Listener, error) { } func initializeSessions(module *DNSMonitor, listener *Listener) error { - var err error - listener.etw, err = NewSession(module.instance.OSIntegration().GetETWInterface(), listener.processEvent) + etw, err := NewSession(module.instance.OSIntegration().GetETWInterface(), listener.processEvent) if err != nil { return err } + listener.etw.Store(etw) // Start listener module.mgr.Go("etw-dns-event-listener", func(w *mgr.WorkerCtx) error { - return listener.etw.StartTrace() + return etw.StartTrace() }) return nil } func (l *Listener) flush() error { - if l.etw == nil { + etw := l.etw.Load() + if etw == nil { return fmt.Errorf("etw not initialized") } - return l.etw.FlushTrace() + return etw.FlushTrace() } func (l *Listener) stop() error { if l == nil { return fmt.Errorf("listener is nil") } - if l.etw == nil { - return fmt.Errorf("invalid etw session") + etw := l.etw.Load() + if etw == nil { + // The session was never started, eg. because the integration DLL could + // not be loaded. There is nothing to stop. + return nil } // Stop and destroy trace. Destroy should be called even if stop fails for some reason. - err := l.etw.StopTrace() - err2 := l.etw.DestroySession() + err := etw.StopTrace() + err2 := etw.DestroySession() if err != nil { return fmt.Errorf("StopTrace failed: %w", err) diff --git a/service/firewall/interception/dnsmonitor/module.go b/service/firewall/interception/dnsmonitor/module.go index 918d1e888..7b7a69dd6 100644 --- a/service/firewall/interception/dnsmonitor/module.go +++ b/service/firewall/interception/dnsmonitor/module.go @@ -12,7 +12,6 @@ import ( "github.com/safing/portmaster/service/compat" "github.com/safing/portmaster/service/integration" "github.com/safing/portmaster/service/mgr" - "github.com/safing/portmaster/service/network/netutils" "github.com/safing/portmaster/service/resolver" ) @@ -110,8 +109,7 @@ func processIfSelfCheckDomain(fqdn string) bool { func saveIPsInCache(ips []net.IP, profileID string, record resolver.ResolvedDomain) { // Package IPs and CNAMEs into IPInfo structs. for _, ip := range ips { - // Never save domain attributions for localhost IPs. - if netutils.GetIPScope(ip) == netutils.HostLocal { + if !resolver.RecordDomainsFor(ip) { continue } diff --git a/service/firewall/interception/ebpf/bandwidth/interface.go b/service/firewall/interception/ebpf/bandwidth/interface.go index e27989775..62a420883 100644 --- a/service/firewall/interception/ebpf/bandwidth/interface.go +++ b/service/firewall/interception/ebpf/bandwidth/interface.go @@ -1,8 +1,11 @@ +//go:build linux + package ebpf import ( "context" "encoding/binary" + "errors" "fmt" "net" "path/filepath" @@ -104,36 +107,119 @@ func BandwidthStatsWorker(ctx context.Context, collectInterval time.Duration, ba defer ticker.Stop() // Collect bandwidth at every tick. + reporter := newBandwidthReporter() + source := &bandwidthMapSource{bpfMap: objs.PmBandwidthMap} for { select { case <-ticker.C: - reportBandwidth(ctx, objs, bandwidthUpdates) + reporter.report(ctx, source, bandwidthUpdates) case <-ctx.Done(): return nil } } } -// reportBandwidth reports the bandwidth to the given updates channel. -func reportBandwidth(ctx context.Context, objs bpfObjects, bandwidthUpdates chan *packet.BandwidthUpdate) { +// bandwidthSource provides access to the absolute byte counters that the +// eBPF programs keep per connection. +type bandwidthSource interface { + // forEach calls fn for every entry until fn returns false. + // The returned error tells that the iteration did not see all entries. + forEach(fn func(key bpfSkKey, info bpfSkInfo) (proceed bool)) error + // lookup returns the entry with the given key, if it exists. + lookup(key bpfSkKey) (info bpfSkInfo, exists bool, err error) +} + +// bandwidthMapSource is the bandwidthSource of the eBPF bandwidth map. +type bandwidthMapSource struct { + bpfMap *ebpf.Map +} + +func (s *bandwidthMapSource) forEach(fn func(key bpfSkKey, info bpfSkInfo) (proceed bool)) error { + var ( + skKey bpfSkKey + skInfo bpfSkInfo + ) + iter := s.bpfMap.Iterate() + for iter.Next(&skKey, &skInfo) { + if !fn(skKey, skInfo) { + return nil + } + } + return iter.Err() +} + +func (s *bandwidthMapSource) lookup(key bpfSkKey) (info bpfSkInfo, exists bool, err error) { + err = s.bpfMap.Lookup(&key, &info) + switch { + case err == nil: + return info, true, nil + case errors.Is(err, ebpf.ErrKeyNotExist): + return info, false, nil + default: + return info, false, err + } +} + +// reportedBandwidth holds the counter values of a connection that were +// reported already. +type reportedBandwidth struct { + rx uint64 + tx uint64 + // seenInRound is the last report round the connection was seen in. + seenInRound uint64 +} + +// bandwidthReporter turns the absolute byte counters of the eBPF bandwidth +// map into additive bandwidth updates. +// +// The counters in the map are kept per connection 5-tuple and outlive the +// connections of Portmaster: The entry of a UDP socket keeps counting when a +// connection ended and a new one with the same 5-tuple was started. Reporting +// the counters as absolute values attributed all previous bytes to the new +// connection. Instead, remember what was reported for every entry and only +// report what was added since. +// +// The reporter only reads from the map. It previously marked reported entries +// in the map, but writing the whole entry back replaced the counters with the +// values read before, which lost the bytes that were counted in between. +type bandwidthReporter struct { + reported map[bpfSkKey]*reportedBandwidth + round uint64 +} + +func newBandwidthReporter() *bandwidthReporter { + return &bandwidthReporter{ + reported: make(map[bpfSkKey]*reportedBandwidth), + } +} + +// report reports the bandwidth added since the last report to the given +// updates channel. +func (r *bandwidthReporter) report(ctx context.Context, source bandwidthSource, bandwidthUpdates chan *packet.BandwidthUpdate) { var ( - skKey bpfSkKey - skInfo bpfSkInfo updated int skipped int + aborted bool ) + r.round++ - iter := objs.bpfMaps.PmBandwidthMap.Iterate() - for iter.Next(&skKey, &skInfo) { - // Check if already reported. - if skInfo.Reported >= 1 { - skipped++ - continue + // reportEntry reports a single entry and returns whether to continue. + reportEntry := func(skKey bpfSkKey, skInfo bpfSkInfo) (proceed bool) { + previous := r.reported[skKey] + + // Calculate what was added since the last report. + var rx, tx uint64 + if previous != nil { + previous.seenInRound = r.round + rx = bandwidthCounterDelta(previous.rx, skInfo.Rx) + tx = bandwidthCounterDelta(previous.tx, skInfo.Tx) + } else { + rx = skInfo.Rx + tx = skInfo.Tx } - // Mark as reported and update the map. - skInfo.Reported = 1 - if err := objs.bpfMaps.PmBandwidthMap.Update(&skKey, &skInfo, ebpf.UpdateExist); err != nil { - log.Debugf("ebpf: failed to mark bandwidth map entry as reported: %s", err) + if rx == 0 && tx == 0 { + skipped++ + return true } connID := packet.CreateConnectionID( @@ -144,22 +230,74 @@ func reportBandwidth(ctx context.Context, objs bpfObjects, bandwidthUpdates chan ) update := &packet.BandwidthUpdate{ ConnID: connID, - BytesReceived: skInfo.Rx, - BytesSent: skInfo.Tx, - Method: packet.Absolute, + BytesReceived: rx, + BytesSent: tx, + Method: packet.Additive, } select { case bandwidthUpdates <- update: updated++ case <-ctx.Done(): - return + aborted = true + return false default: + // The reported values are not updated for the remaining entries, + // so their bytes are included in the next report. log.Warningf("ebpf: bandwidth update queue is full (updated=%d, skipped=%d), ignoring rest of batch", updated, skipped) + aborted = true + return false + } + + // Remember what was reported, now that the update is on its way. + if previous == nil { + previous = &reportedBandwidth{seenInRound: r.round} + r.reported[skKey] = previous + } + previous.rx = skInfo.Rx + previous.tx = skInfo.Tx + return true + } + + err := source.forEach(reportEntry) + if err != nil { + log.Debugf("ebpf: failed to iterate the bandwidth map: %s", err) + return + } + if aborted { + return + } + + // Forget entries that are gone from the map. + // The iteration may miss entries while the map is changed, so look up + // every entry that was not seen: Forgetting an entry that still exists + // would report all of its bytes again. + for skKey, previous := range r.reported { + if previous.seenInRound == r.round { + continue + } + skInfo, exists, err := source.lookup(skKey) + switch { + case err != nil: + // Keep the entry and check again next time. + case !exists: + delete(r.reported, skKey) + case !reportEntry(skKey, skInfo): return } } } +// bandwidthCounterDelta returns what was added to an absolute byte counter +// between the previous and the current value. A counter that went backwards +// was reset, eg. because the entry was replaced for a new socket with the same +// 5-tuple. It then holds what was counted since the reset. +func bandwidthCounterDelta(previous, current uint64) uint64 { + if current < previous { + return current + } + return current - previous +} + // findCgroupPath returns the default unified path of the cgroup. func findCgroupPath() (string, error) { cgroupPath := "/sys/fs/cgroup" diff --git a/service/firewall/interception/ebpf/bandwidth/interface_test.go b/service/firewall/interception/ebpf/bandwidth/interface_test.go new file mode 100644 index 000000000..05f5c5922 --- /dev/null +++ b/service/firewall/interception/ebpf/bandwidth/interface_test.go @@ -0,0 +1,190 @@ +//go:build linux + +package ebpf + +import ( + "context" + "testing" + + "github.com/cilium/ebpf" + + "github.com/safing/portmaster/service/network/packet" +) + +// testBandwidthSource is a bandwidthSource backed by a Go map. +type testBandwidthSource struct { + entries map[bpfSkKey]bpfSkInfo + // hidden entries are skipped by forEach, as may happen for entries of an + // eBPF map that is changed while it is iterated. + hidden map[bpfSkKey]struct{} + iterateErr error +} + +func (s *testBandwidthSource) forEach(fn func(key bpfSkKey, info bpfSkInfo) bool) error { + for key, info := range s.entries { + if _, ok := s.hidden[key]; ok { + continue + } + if !fn(key, info) { + return nil + } + } + return s.iterateErr +} + +func (s *testBandwidthSource) lookup(key bpfSkKey) (bpfSkInfo, bool, error) { + info, ok := s.entries[key] + return info, ok, nil +} + +func testSkKey(srcPort uint16) bpfSkKey { + return bpfSkKey{ + SrcIp: [4]uint32{0x0100007f}, + DstIp: [4]uint32{0x08080808}, + SrcPort: srcPort, + DstPort: 53, + Protocol: 17, + } +} + +// collectBandwidth runs one report and returns the reported bytes per +// connection ID. +func collectBandwidth(t *testing.T, r *bandwidthReporter, source bandwidthSource, queueSize int) map[string][2]uint64 { + t.Helper() + + updates := make(chan *packet.BandwidthUpdate, queueSize) + r.report(context.Background(), source, updates) + close(updates) + + result := make(map[string][2]uint64) + for update := range updates { + if update.Method != packet.Additive { + t.Errorf("update %s is not additive", update) + } + if _, ok := result[update.ConnID]; ok { + t.Errorf("connection %s was reported twice in one report", update.ConnID) + } + result[update.ConnID] = [2]uint64{update.BytesReceived, update.BytesSent} + } + return result +} + +func connIDOf(key bpfSkKey) string { + return packet.CreateConnectionID( + packet.IPProtocol(key.Protocol), + convertArrayToIP(key.SrcIp, false), key.SrcPort, + convertArrayToIP(key.DstIp, false), key.DstPort, + false, + ) +} + +func expectBandwidth(t *testing.T, got map[string][2]uint64, want map[bpfSkKey][2]uint64) { + t.Helper() + + if len(got) != len(want) { + t.Errorf("got %d updates, expected %d: %v", len(got), len(want), got) + } + for key, bytes := range want { + if got[connIDOf(key)] != bytes { + t.Errorf("connection %s: got rx/tx %v, expected %v", connIDOf(key), got[connIDOf(key)], bytes) + } + } +} + +func TestBandwidthReporterDeltas(t *testing.T) { + t.Parallel() + + a, b := testSkKey(1000), testSkKey(2000) + source := &testBandwidthSource{entries: map[bpfSkKey]bpfSkInfo{ + a: {Rx: 100, Tx: 10}, + b: {Rx: 0, Tx: 0}, + }} + r := newBandwidthReporter() + + // The first report holds everything counted so far. + expectBandwidth(t, collectBandwidth(t, r, source, 10), map[bpfSkKey][2]uint64{a: {100, 10}}) + + // Nothing changed: nothing to report. The entry in the source is not + // marked or changed in any way. + expectBandwidth(t, collectBandwidth(t, r, source, 10), nil) + if source.entries[a] != (bpfSkInfo{Rx: 100, Tx: 10}) { + t.Errorf("source entry was changed: %+v", source.entries[a]) + } + + // Only the added bytes are reported. This is what a successor connection + // with the same 5-tuple gets, instead of all bytes of its predecessors. + source.entries[a] = bpfSkInfo{Rx: 150, Tx: 10} + source.entries[b] = bpfSkInfo{Rx: 0, Tx: 7} + expectBandwidth(t, collectBandwidth(t, r, source, 10), map[bpfSkKey][2]uint64{a: {50, 0}, b: {0, 7}}) + + // A counter that went backwards was reset and holds the bytes since. + source.entries[a] = bpfSkInfo{Rx: 20, Tx: 15} + expectBandwidth(t, collectBandwidth(t, r, source, 10), map[bpfSkKey][2]uint64{a: {20, 5}}) + source.entries[a] = bpfSkInfo{Rx: 25, Tx: 15} + expectBandwidth(t, collectBandwidth(t, r, source, 10), map[bpfSkKey][2]uint64{a: {5, 0}}) +} + +func TestBandwidthReporterFullQueue(t *testing.T) { + t.Parallel() + + source := &testBandwidthSource{entries: make(map[bpfSkKey]bpfSkInfo)} + want := make(map[bpfSkKey][2]uint64) + for port := uint16(1); port <= 10; port++ { + source.entries[testSkKey(port)] = bpfSkInfo{Rx: uint64(port), Tx: 1} + want[testSkKey(port)] = [2]uint64{uint64(port), 1} + } + r := newBandwidthReporter() + + // Report with a queue that only fits some updates at a time: Every byte + // must be reported exactly once in the end. + total := make(map[string][2]uint64) + for range 4 { + for connID, bytes := range collectBandwidth(t, r, source, 3) { + sum := total[connID] + total[connID] = [2]uint64{sum[0] + bytes[0], sum[1] + bytes[1]} + } + } + expectBandwidth(t, total, want) + expectBandwidth(t, collectBandwidth(t, r, source, 3), nil) +} + +func TestBandwidthReporterForgetsGoneEntries(t *testing.T) { + t.Parallel() + + a, b := testSkKey(1000), testSkKey(2000) + source := &testBandwidthSource{entries: map[bpfSkKey]bpfSkInfo{ + a: {Rx: 100, Tx: 10}, + b: {Rx: 200, Tx: 20}, + }} + r := newBandwidthReporter() + collectBandwidth(t, r, source, 10) + + // An entry that the iteration missed, but that still exists, is not + // forgotten and its new bytes are reported. + source.hidden = map[bpfSkKey]struct{}{a: {}} + source.entries[a] = bpfSkInfo{Rx: 101, Tx: 10} + expectBandwidth(t, collectBandwidth(t, r, source, 10), map[bpfSkKey][2]uint64{a: {1, 0}}) + expectBandwidth(t, collectBandwidth(t, r, source, 10), nil) + source.hidden = nil + expectBandwidth(t, collectBandwidth(t, r, source, 10), nil) + + // Nothing is forgotten when the iteration failed. + source.hidden = map[bpfSkKey]struct{}{a: {}, b: {}} + source.iterateErr = ebpf.ErrIterationAborted + expectBandwidth(t, collectBandwidth(t, r, source, 10), nil) + if len(r.reported) != 2 { + t.Errorf("%d entries are remembered after a failed iteration, expected 2", len(r.reported)) + } + source.hidden, source.iterateErr = nil, nil + + // An entry that was evicted from the map is forgotten. + delete(source.entries, a) + expectBandwidth(t, collectBandwidth(t, r, source, 10), nil) + if len(r.reported) != 1 { + t.Errorf("%d entries are remembered, expected 1", len(r.reported)) + } + + // When it shows up again, it is a new entry. + source.entries[a] = bpfSkInfo{Rx: 500, Tx: 0} + expectBandwidth(t, collectBandwidth(t, r, source, 10), map[bpfSkKey][2]uint64{a: {500, 0}}) +} diff --git a/service/firewall/interception/ebpf/connection_listener/worker.go b/service/firewall/interception/ebpf/connection_listener/worker.go index b52c168b9..5c16a9d47 100644 --- a/service/firewall/interception/ebpf/connection_listener/worker.go +++ b/service/firewall/interception/ebpf/connection_listener/worker.go @@ -1,3 +1,5 @@ +//go:build linux + package ebpf import ( diff --git a/service/firewall/interception/ebpf/exec/exec.go b/service/firewall/interception/ebpf/exec/exec.go index d09fc1302..49e9e5edd 100644 --- a/service/firewall/interception/ebpf/exec/exec.go +++ b/service/firewall/interception/ebpf/exec/exec.go @@ -1,3 +1,5 @@ +//go:build linux + package ebpf import ( diff --git a/service/firewall/interception/interception_default.go b/service/firewall/interception/interception_default.go index 8755f225b..43f851edb 100644 --- a/service/firewall/interception/interception_default.go +++ b/service/firewall/interception/interception_default.go @@ -3,6 +3,8 @@ package interception import ( + "net" + "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/network" "github.com/safing/portmaster/service/network/packet" @@ -24,6 +26,11 @@ func ResetVerdictOfAllConnections() error { return nil } +// ClearFlow does nothing on this platform. +func ClearFlow(_ uint8, _ net.IP, _ uint16, _ net.IP, _ uint16) (cleared bool, err error) { + return false, nil +} + // UpdateVerdictOfConnection updates the verdict of the given connection in the OS integration. func UpdateVerdictOfConnection(conn *network.Connection) error { return nil diff --git a/service/firewall/interception/interception_linux.go b/service/firewall/interception/interception_linux.go index 24109f48b..dd340447e 100644 --- a/service/firewall/interception/interception_linux.go +++ b/service/firewall/interception/interception_linux.go @@ -1,6 +1,7 @@ package interception import ( + "net" "time" bandwidth "github.com/safing/portmaster/service/firewall/interception/ebpf/bandwidth" @@ -29,6 +30,9 @@ func startInterception(packets chan packet.Packet) error { return bandwidth.BandwidthStatsWorker(wc.Ctx(), 1*time.Second, BandwidthUpdates) }) + // Make apps resolve names again, so that Portmaster sees the queries. + flushSystemDNSCache() + return nil } @@ -42,6 +46,13 @@ func ResetVerdictOfAllConnections() error { return nfq.DeleteAllMarkedConnection() } +// ClearFlow deletes the conntrack entry of an earlier flow with the given +// original addresses, so that a new socket with the same addresses is not +// handled like it, e.g. redirected. +func ClearFlow(protocol uint8, localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16) (cleared bool, err error) { + return nfq.DeleteFlow(protocol, localIP, localPort, remoteIP, remotePort) +} + // UpdateVerdictOfConnection deletes the verdict of the given connection so it can be initialized again with the next packet. func UpdateVerdictOfConnection(conn *network.Connection) error { return nfq.DeleteMarkedConnection(conn) diff --git a/service/firewall/interception/interception_windows.go b/service/firewall/interception/interception_windows.go index 3f9df6f8b..0cd31aedd 100644 --- a/service/firewall/interception/interception_windows.go +++ b/service/firewall/interception/interception_windows.go @@ -2,6 +2,7 @@ package interception import ( "fmt" + "net" "time" "github.com/safing/portmaster/base/log" @@ -113,6 +114,9 @@ func startInterception(packets chan packet.Packet) error { }) } + // Names resolved before the start must be resolved again through Portmaster. + flushSystemDNSCache() + return nil } @@ -132,6 +136,13 @@ func ResetVerdictOfAllConnections() error { return kext2.ClearCache() } +// ClearFlow does nothing on Windows. Stale state for a reused address tuple +// was only observed with Linux conntrack; the kernel extension has no call to +// drop a single flow by address. +func ClearFlow(_ uint8, _ net.IP, _ uint16, _ net.IP, _ uint16) (cleared bool, err error) { + return false, nil +} + // UpdateVerdictOfConnection updates the verdict of the given connection in the kernel extension. func UpdateVerdictOfConnection(conn *network.Connection) error { if useOldKext { diff --git a/service/firewall/interception/nfq/conntrack.go b/service/firewall/interception/nfq/conntrack.go index 51612b43d..596b6d66c 100644 --- a/service/firewall/interception/nfq/conntrack.go +++ b/service/firewall/interception/nfq/conntrack.go @@ -6,8 +6,12 @@ import ( "encoding/binary" "errors" "fmt" + "net" + "sync" + "syscall" ct "github.com/florianl/go-conntrack" + "github.com/mdlayher/netlink" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/netenv" @@ -15,23 +19,223 @@ import ( pmpacket "github.com/safing/portmaster/service/network/packet" ) -var nfct *ct.Nfct // Conntrack handler. NFCT: Network Filter Connection Tracking. +// conntrackHandle is the part of *ct.Nfct used by this package. It allows +// tests to substitute a fake handle. +type conntrackHandle interface { + Query(t ct.Table, f ct.Family, filter ct.FilterAttr) ([]ct.Con, error) + Delete(t ct.Table, f ct.Family, attributes ct.Con) error + Close() error +} + +// openConntrack opens a new conntrack handle. It is replaced in tests. +var openConntrack = func() (conntrackHandle, error) { + h, err := ct.Open(&ct.Config{}) + if err != nil { + // Do not return a typed nil pointer as a non-nil interface. + return nil, err + } + return h, nil +} + +var ( + errNFCTNotInitialized = errors.New("nfq: nfct not initialized") + errConnectionIncomplete = errors.New("local or remote address unknown") +) + +var ( + // nfct is the conntrack handler. NFCT: Network Filter Connection Tracking. + // It is nil before InitNFCT, after TeardownNFCT, and after it was closed + // because it desynchronized and could not be reopened yet (see nfctReopen). + nfct conntrackHandle + // nfctReopen is set when nfct was closed because it desynchronized. The + // next operation tries to reopen it. + nfctReopen bool + // nfctLock guards nfct and nfctReopen. It is held for the whole of every + // exported function in this file, so that each request/reply exchange on + // the handle (including complete query+delete loops) is exclusive and + // Close, reopen and reassignment never overlap a request in flight. + // The handle is not safe for concurrent use: go-conntrack's Query sends + // the request and reads the reply in two separately locked netlink calls + // (Conn.Send, then Conn.Receive) without matching the reply to the + // request, so concurrent callers could receive each other's replies. + // nfctLock is a leaf lock: nothing called while holding it may acquire + // other Portmaster locks (callers hold connection locks). + nfctLock sync.Mutex +) // InitNFCT initializes the network filter conntrack library. func InitNFCT() error { - var err error - nfct, err = ct.Open(&ct.Config{}) + nfctLock.Lock() + defer nfctLock.Unlock() + + // Do not leak the netlink socket of a handle that is still open. + if nfct != nil { + _ = nfct.Close() + nfct = nil + } + nfctReopen = false + h, err := openConntrack() if err != nil { return err } + nfct = h return nil } // TeardownNFCT deinitializes the network filter conntrack library. func TeardownNFCT() { + nfctLock.Lock() + defer nfctLock.Unlock() + + if nfct != nil { + _ = nfct.Close() + nfct = nil + } + nfctReopen = false +} + +// nfctHandleLocked returns the conntrack handle, reopening it first if it was +// closed because it desynchronized. nfctLock must be held. +func nfctHandleLocked() (conntrackHandle, error) { + if nfct != nil { + return nfct, nil + } + if !nfctReopen { + return nil, errNFCTNotInitialized + } + + h, err := openConntrack() + if err != nil { + return nil, fmt.Errorf("nfq: failed to reopen conntrack handle: %w", err) + } + nfct = h + nfctReopen = false + log.Infof("nfq: reopened conntrack handle") + return h, nil +} + +// invalidateNFCTLocked closes the desynchronized conntrack handle, so that the +// next operation opens a new one. nfctLock must be held. +func invalidateNFCTLocked(cause error) { + log.Warningf("nfq: conntrack handle is out of sync, reopening it: %s", cause) if nfct != nil { _ = nfct.Close() + nfct = nil + } + nfctReopen = true +} + +// Op values of *netlink.OpError (github.com/mdlayher/netlink v1.8.0). +const ( + netlinkOpReceive = "receive" + netlinkOpValidate = "validate" +) + +// isDesyncError reports whether err from a request on the conntrack handle +// means that replies may be left unread on (or lost from) its socket, so that +// later requests would read replies that do not belong to them. +// +// Errors of github.com/mdlayher/netlink v1.8.0 (used by go-conntrack v0.4.0): +// - Op "validate": Conn.Execute (used by Delete) read a reply with another +// sequence number or PID, i.e. a stale reply of an earlier request, and +// the reply to this request is still queued. +// - Op "receive" with a bare syscall.Errno: the kernel answered with an +// NLMSG_ERROR (e.g. ENOENT for a missing entry). It is the last message of +// the reply, so the handle is still in sync. A truncated datagram +// (syscall.ParseNetlinkMessage) would also yield a bare EINVAL, but +// Receive sizes its buffer with MSG_PEEK first, so that cannot happen +// with a single reader. +// - Op "receive" with any other error (an *os.SyscallError from recvmsg, +// e.g. ENOBUFS after the receive buffer overran and the kernel dropped +// replies, or a malformed error message): the read was aborted, possibly +// in the middle of a multi-part dump reply. +// - Op "send": the request did not reach the kernel, no reply is queued. +// +// ENOBUFS is always treated as a desync, also when the kernel reports it in +// an error message, as replies may have been dropped. +// Errors that are not a *netlink.OpError come from go-conntrack itself while +// encoding a request (before sending) or decoding a reply that was read +// completely; they do not affect the socket. +func isDesyncError(err error) bool { + if err == nil { + return false + } + if errors.Is(err, syscall.ENOBUFS) { + return true + } + + var opErr *netlink.OpError + if !errors.As(err, &opErr) { + return false + } + switch opErr.Op { + case netlinkOpValidate: + return true + case netlinkOpReceive: + // The exact type distinguishes kernel error replies from socket errors. + _, kernelErrno := opErr.Err.(syscall.Errno) //nolint:errorlint + return !kernelErrno + default: + return false + } +} + +// withNFCTLocked runs op on the conntrack handle. If op fails because the +// handle desynchronized, the handle is closed and reopened and op is retried +// once. op must be safe to retry. nfctLock must be held. +func withNFCTLocked(op func(h conntrackHandle) error) error { + h, err := nfctHandleLocked() + if err != nil { + return err + } + + err = op(h) + if !isDesyncError(err) { + return err + } + + invalidateNFCTLocked(err) + h, reopenErr := nfctHandleLocked() + if reopenErr != nil { + return errors.Join(err, reopenErr) } + err = op(h) + if isDesyncError(err) { + invalidateNFCTLocked(err) + } + return err +} + +// queryLocked runs a conntrack dump query. A dump can be restarted, so it is +// retried once on a desynchronized handle. nfctLock must be held. +func queryLocked(f ct.Family, filter ct.FilterAttr) ([]ct.Con, error) { + var connections []ct.Con + err := withNFCTLocked(func(h conntrackHandle) error { + var err error + connections, err = h.Query(ct.Conntrack, f, filter) + return err + }) + return connections, err +} + +// deleteLocked deletes a conntrack entry. Deleting is idempotent, so it is +// retried once on a desynchronized handle. nfctLock must be held. +// +// The kernel may have executed the first attempt before its reply was lost +// (ENOBUFS) or left unread (mismatched sequence), so ENOENT on the retry +// cannot be told apart from an entry that did not exist. Either way the entry +// is gone, so ENOENT on the retry counts as success. ENOENT on the first +// attempt is still returned. +func deleteLocked(f ct.Family, connection ct.Con) error { + retry := false + return withNFCTLocked(func(h conntrackHandle) error { + err := h.Delete(ct.Conntrack, f, connection) + if retry && errors.Is(err, syscall.ENOENT) { + return nil + } + retry = true + return err + }) } // DeleteUnmarkedConnections deletes all conntrack entries with connmark=0, @@ -54,27 +258,31 @@ func TeardownNFCT() { // Connections already processed by Portmaster carry a non-zero connmark and // are handled via CONNMARK --restore-mark; they are unaffected. func DeleteUnmarkedConnections() error { - if nfct == nil { - return errors.New("nfq: nfct not initialized") + nfctLock.Lock() + defer nfctLock.Unlock() + + _, err := nfctHandleLocked() + if err != nil { + return err } - deleted := deleteUnmarkedConnections(nfct, ct.IPv4) + deleted := deleteUnmarkedConnections(ct.IPv4) if netenv.IPv6Enabled() { - deleted += deleteUnmarkedConnections(nfct, ct.IPv6) + deleted += deleteUnmarkedConnections(ct.IPv6) } log.Infof("nfq: deleted %d unmarked conntrack entries to force re-evaluation on firewall activation", deleted) return nil } -func deleteUnmarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { +func deleteUnmarkedConnections(f ct.Family) (deleted int) { filter := ct.FilterAttr{ Mark: []byte{0x00, 0x00, 0x00, 0x00}, MarkMask: []byte{0xFF, 0xFF, 0xFF, 0xFF}, } - connections, err := nfct.Query(ct.Conntrack, f, filter) + connections, err := queryLocked(f, filter) if err != nil { log.Warningf("nfq: error querying unmarked conntrack entries: %s", err) return 0 @@ -85,7 +293,8 @@ func deleteUnmarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { if isLoopbackConnection(connection) { continue } - if err := nfct.Delete(ct.Conntrack, f, connection); err != nil { + err := deleteLocked(f, connection) + if err != nil { lastErr = err } else { deleted++ @@ -121,23 +330,27 @@ func isLoopbackConnection(c ct.Con) bool { // DeleteAllMarkedConnection deletes all marked entries from the conntrack table. func DeleteAllMarkedConnection() error { - if nfct == nil { - return errors.New("nfq: nfct not initialized") + nfctLock.Lock() + defer nfctLock.Unlock() + + _, err := nfctHandleLocked() + if err != nil { + return err } // Delete all ipv4 marked connections - deleted := deleteMarkedConnections(nfct, ct.IPv4) + deleted := deleteMarkedConnections(ct.IPv4) if netenv.IPv6Enabled() { // Delete all ipv6 marked connections - deleted += deleteMarkedConnections(nfct, ct.IPv6) + deleted += deleteMarkedConnections(ct.IPv6) } log.Infof("nfq: deleted %d conntrack entries to reset permanent connection verdicts", deleted) return nil } -func deleteMarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { +func deleteMarkedConnections(f ct.Family) (deleted int) { // initialize variables permanentFlags := []uint32{MarkAcceptAlways, MarkBlockAlways, MarkDropAlways, MarkRerouteNS, MarkRerouteSPN, MarkRerouteSplitTun} filter := ct.FilterAttr{} @@ -149,14 +362,14 @@ func deleteMarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { // Get all connections from the specified family (ipv4 or ipv6) for _, mark := range permanentFlags { binary.BigEndian.PutUint32(filter.Mark, mark) // Little endian is in reverse not sure why. BigEndian makes it in correct order. - currentConnections, err := nfct.Query(ct.Conntrack, f, filter) + currentConnections, err := queryLocked(f, filter) if err != nil { log.Warningf("nfq: error on conntrack query: %s", err) continue } for _, connection := range currentConnections { - deleteError = nfct.Delete(ct.Conntrack, f, connection) + deleteError = deleteLocked(f, connection) if deleteError != nil { numberOfErrors++ } else { @@ -173,8 +386,17 @@ func deleteMarkedConnections(nfct *ct.Nfct, f ct.Family) (deleted int) { // DeleteMarkedConnection removes a specific connection from the conntrack table. func DeleteMarkedConnection(conn *network.Connection) error { - if nfct == nil { - return errors.New("nfq: nfct not initialized") + // Incomplete connections have no remote entity (and no local address) yet. + if conn.Entity == nil || conn.Entity.IP == nil || conn.LocalIP == nil { + return fmt.Errorf("nfq: cannot delete conntrack entry for connection %s: %w", conn.ID, errConnectionIncomplete) + } + + nfctLock.Lock() + defer nfctLock.Unlock() + + _, err := nfctHandleLocked() + if err != nil { + return err } con := ct.Con{ @@ -194,25 +416,63 @@ func DeleteMarkedConnection(conn *network.Connection) error { family = ct.IPv6 } - connections, err := nfct.Get(ct.Conntrack, family, con) + // Delete by original tuple directly instead of Get followed by Delete: + // go-conntrack v0.4.0 sends Get with NLM_F_ACK but reads only the entry + // message, leaving the kernel's ACK queued on the shared socket. The next + // request on the handle then read that stale ACK ("mismatched sequence") + // and left its own reply behind, desynchronizing the handle for all later + // requests. The kernel answers a Delete with exactly one message (ACK or + // error), which Delete reads. A missing entry is reported as ENOENT. + err = deleteLocked(family, con) if err != nil { - return fmt.Errorf("nfq: failed to find entry for connection %s: %w", conn.String(), err) + return fmt.Errorf("nfq: failed to delete conntrack entry for connection %s: %w", conn.String(), err) } - if len(connections) > 1 { - log.Warningf("nfq: multiple entries found for single connection: %s -> %d", conn.String(), len(connections)) - } + return nil +} - for _, connection := range connections { - deleteErr := nfct.Delete(ct.Conntrack, family, connection) - if err == nil { - err = deleteErr - } +// DeleteFlow removes the conntrack entry whose original direction matches the +// given addresses, if there is one, and reports whether it did. A missing +// entry is not an error. +func DeleteFlow(protocol uint8, localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16) (deleted bool, err error) { + // Go often holds IPv4 addresses in 16 byte form, which conntrack would + // not match against an IPv4 entry. + family := ct.IPv4 + if ip4 := localIP.To4(); ip4 != nil { + localIP = ip4 + remoteIP = remoteIP.To4() + } else { + family = ct.IPv6 + } + if remoteIP == nil { + return false, fmt.Errorf("nfq: %w: mixed IP versions", errConnectionIncomplete) } + nfctLock.Lock() + defer nfctLock.Unlock() + + _, err = nfctHandleLocked() if err != nil { - log.Warningf("nfq: error while deleting conntrack entries for connection %s: %s", conn.String(), err) + return false, err } - return nil + err = deleteLocked(family, ct.Con{ + Origin: &ct.IPTuple{ + Src: &localIP, + Dst: &remoteIP, + Proto: &ct.ProtoTuple{ + Number: &protocol, + SrcPort: &localPort, + DstPort: &remotePort, + }, + }, + }) + switch { + case errors.Is(err, syscall.ENOENT): + return false, nil + case err != nil: + return false, err + default: + return true, nil + } } diff --git a/service/firewall/interception/nfq/conntrack_framing_test.go b/service/firewall/interception/nfq/conntrack_framing_test.go new file mode 100644 index 000000000..01a70f10d --- /dev/null +++ b/service/firewall/interception/nfq/conntrack_framing_test.go @@ -0,0 +1,323 @@ +//go:build linux + +package nfq + +import ( + "encoding/binary" + "errors" + "net" + "strings" + "testing" + + ct "github.com/florianl/go-conntrack" + "github.com/mdlayher/netlink" + "golang.org/x/sys/unix" +) + +// Conntrack netlink constants (include/uapi/linux/netfilter/nfnetlink_conntrack.h). +const ( + fakeCtMsgNew = 0 // IPCTNL_MSG_CT_NEW + fakeCtMsgGet = 1 // IPCTNL_MSG_CT_GET + fakeCtMsgDelete = 2 // IPCTNL_MSG_CT_DELETE + + fakeCtaTupleOrig = 1 // CTA_TUPLE_ORIG + fakeCtaTupleIP = 1 // CTA_TUPLE_IP + fakeCtaTupleProt = 2 // CTA_TUPLE_PROTO + fakeCtaIPv4Src = 1 // CTA_IP_V4_SRC + fakeCtaIPv4Dst = 2 // CTA_IP_V4_DST + fakeCtaProtoNum = 1 // CTA_PROTO_NUM + fakeCtaSrcPort = 2 // CTA_PROTO_SRC_PORT + fakeCtaDstPort = 3 // CTA_PROTO_DST_PORT + + fakeNetlinkPID = 4242 +) + +var errFakeWouldBlock = errors.New("fake netlink socket: no pending datagram (would block)") + +// fakeKernelSocket is a netlink.Socket that models how the kernel frames +// ctnetlink replies: every message the kernel unicasts is its own skb and +// therefore its own datagram, and one recvmsg returns exactly one datagram. +// +// For a request, netlink_rcv_skb (net/netlink/af_netlink.c) runs the +// nfnetlink handler and then calls netlink_ack() if NLM_F_ACK is set or the +// handler returned an error. ctnetlink_get_conntrack unicasts the entry as a +// separate skb before that, so a successful GET with NLM_F_ACK yields two +// datagrams (entry, then ACK), while a failed GET/DELETE yields one error. +// +// nltest.Dial cannot be used here: its socket returns all replies to a +// request in one Receive call and discards unread replies on the next Send, +// which hides exactly the framing problem under test. +type fakeKernelSocket struct { + entries map[string]bool + datagrams [][]netlink.Message +} + +func newFakeKernelSocket() *fakeKernelSocket { + return &fakeKernelSocket{entries: make(map[string]bool)} +} + +func (s *fakeKernelSocket) Close() error { return nil } + +func (s *fakeKernelSocket) SendMessages(msgs []netlink.Message) error { + for _, m := range msgs { + err := s.Send(m) + if err != nil { + return err + } + } + return nil +} + +func (s *fakeKernelSocket) Send(req netlink.Message) error { + key, err := fakeTupleKey(req.Data) + if err != nil { + return err + } + + var errno fakeErrno + switch int(req.Header.Type) & 0xff { + case fakeCtMsgGet: + if s.entries[key] { + s.datagrams = append(s.datagrams, []netlink.Message{fakeEntryMessage(req, key)}) + } else { + errno = fakeErrno(unix.ENOENT) + } + case fakeCtMsgDelete: + if s.entries[key] { + delete(s.entries, key) + } else { + errno = fakeErrno(unix.ENOENT) + } + default: + errno = fakeErrno(unix.EOPNOTSUPP) + } + + if req.Header.Flags&netlink.Acknowledge != 0 || errno != 0 { + s.datagrams = append(s.datagrams, []netlink.Message{fakeAckMessage(req, errno)}) + } + return nil +} + +func (s *fakeKernelSocket) Receive() ([]netlink.Message, error) { + if len(s.datagrams) == 0 { + // A real socket would block here. + return nil, errFakeWouldBlock + } + d := s.datagrams[0] + s.datagrams = s.datagrams[1:] + return d, nil +} + +type fakeErrno int32 + +// fakeAckMessage builds an NLMSG_ERROR reply as built by netlink_ack(). +func fakeAckMessage(req netlink.Message, errno fakeErrno) netlink.Message { + data := make([]byte, 4+16) + binary.NativeEndian.PutUint32(data[0:4], uint32(-int32(errno))) //nolint:gosec // Two's complement errno. + binary.NativeEndian.PutUint32(data[4:8], req.Header.Length) + binary.NativeEndian.PutUint16(data[8:10], uint16(req.Header.Type)) + binary.NativeEndian.PutUint16(data[10:12], uint16(req.Header.Flags)) + binary.NativeEndian.PutUint32(data[12:16], req.Header.Sequence) + binary.NativeEndian.PutUint32(data[16:20], req.Header.PID) + return netlink.Message{ + Header: netlink.Header{ + Type: netlink.Error, + Sequence: req.Header.Sequence, + PID: req.Header.PID, + }, + Data: data, + } +} + +// fakeEntryMessage builds an IPCTNL_MSG_CT_NEW message describing the entry. +func fakeEntryMessage(req netlink.Message, key string) netlink.Message { + parts := strings.Split(key, "|") + src := net.ParseIP(parts[0]).To4() + dst := net.ParseIP(parts[1]).To4() + + ip := netlink.NewAttributeEncoder() + ip.Bytes(fakeCtaIPv4Src, src) + ip.Bytes(fakeCtaIPv4Dst, dst) + ipb, _ := ip.Encode() + + proto := netlink.NewAttributeEncoder() + proto.ByteOrder = binary.BigEndian + proto.Uint8(fakeCtaProtoNum, unix.IPPROTO_TCP) + proto.Uint16(fakeCtaSrcPort, 40000) + proto.Uint16(fakeCtaDstPort, 443) + protob, _ := proto.Encode() + + tuple := netlink.NewAttributeEncoder() + tuple.Bytes(unix.NLA_F_NESTED|fakeCtaTupleIP, ipb) + tuple.Bytes(unix.NLA_F_NESTED|fakeCtaTupleProt, protob) + tupleb, _ := tuple.Encode() + + top := netlink.NewAttributeEncoder() + top.Bytes(unix.NLA_F_NESTED|fakeCtaTupleOrig, tupleb) + topb, _ := top.Encode() + + return netlink.Message{ + Header: netlink.Header{ + Type: netlink.HeaderType(unix.NFNL_SUBSYS_CTNETLINK<<8 | fakeCtMsgNew), + Sequence: req.Header.Sequence, + PID: req.Header.PID, + }, + Data: append([]byte{unix.AF_INET, unix.NFNETLINK_V0, 0, 0}, topb...), + } +} + +// fakeTupleKey extracts "src|dst" of the original tuple from a ctnetlink request. +func fakeTupleKey(data []byte) (string, error) { + var src, dst net.IP + top, err := netlink.NewAttributeDecoder(data[4:]) + if err != nil { + return "", err + } + for top.Next() { + if top.Type() != fakeCtaTupleOrig { + continue + } + tuple, err := netlink.NewAttributeDecoder(top.Bytes()) + if err != nil { + return "", err + } + for tuple.Next() { + if tuple.Type() != fakeCtaTupleIP { + continue + } + ip, err := netlink.NewAttributeDecoder(tuple.Bytes()) + if err != nil { + return "", err + } + for ip.Next() { + switch ip.Type() { + case fakeCtaIPv4Src: + src = net.IP(ip.Bytes()) + case fakeCtaIPv4Dst: + dst = net.IP(ip.Bytes()) + } + } + } + } + return src.String() + "|" + dst.String(), nil +} + +// newFakeNfct returns a go-conntrack handle whose netlink connection talks to +// a fakeKernelSocket. go-conntrack has no constructor accepting a connection, +// and Nfct's other fields are unexported, so a real handle is opened (this +// needs no privileges) and its exported Con is swapped for the fake. +func newFakeNfct(t *testing.T) (*ct.Nfct, *fakeKernelSocket) { + t.Helper() + + h, err := ct.Open(&ct.Config{}) + if err != nil { + t.Skipf("cannot open netfilter netlink socket: %s", err) + } + _ = h.Con.Close() + + sock := newFakeKernelSocket() + h.Con = netlink.NewConn(sock, fakeNetlinkPID) + t.Cleanup(func() { _ = h.Close() }) + return h, sock +} + +func fakeCon(src, dst net.IP) ct.Con { + proto := uint8(unix.IPPROTO_TCP) + srcPort := uint16(40000) + dstPort := uint16(443) + return ct.Con{ + Origin: &ct.IPTuple{ + Src: &src, + Dst: &dst, + Proto: &ct.ProtoTuple{ + Number: &proto, + SrcPort: &srcPort, + DstPort: &dstPort, + }, + }, + } +} + +// TestGoConntrackGetLeavesAckUnread documents the go-conntrack v0.4.0 +// behaviour that caused the bug: Get sends NLM_F_ACK but reads only one +// datagram, so the ACK stays queued and the next request on the handle reads +// it and fails with a sequence mismatch. If this test starts failing after a +// go-conntrack upgrade, the library has been fixed. +func TestGoConntrackGetLeavesAckUnread(t *testing.T) { + t.Parallel() + + h, sock := newFakeNfct(t) + sock.entries["10.0.0.1|10.0.0.2"] = true + sock.entries["10.0.0.3|10.0.0.4"] = true + + got, err := h.Get(ct.Conntrack, ct.IPv4, fakeCon(net.IPv4(10, 0, 0, 1), net.IPv4(10, 0, 0, 2))) + if err != nil { + t.Fatalf("Get: %s", err) + } + if len(got) != 1 { + t.Fatalf("Get: expected 1 entry, got %d", len(got)) + } + if len(sock.datagrams) != 1 { + t.Fatalf("expected the ACK of Get to be left unread, %d datagrams pending", len(sock.datagrams)) + } + + // The next, unrelated request reads the stale ACK. + err = h.Delete(ct.Conntrack, ct.IPv4, fakeCon(net.IPv4(10, 0, 0, 3), net.IPv4(10, 0, 0, 4))) + if err == nil || !strings.Contains(err.Error(), "mismatched sequence") { + t.Fatalf("Delete after Get: expected mismatched sequence error, got %v", err) + } + // The kernel did delete the entry, and its ACK is now the stale one. + if sock.entries["10.0.0.3|10.0.0.4"] { + t.Error("expected entry to be deleted by the fake kernel") + } + if len(sock.datagrams) != 1 { + t.Errorf("expected the handle to stay desynchronized, %d datagrams pending", len(sock.datagrams)) + } +} + +// TestDeleteMarkedConnectionFraming checks that DeleteMarkedConnection leaves +// no unread replies on the shared handle, so later requests still work. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestDeleteMarkedConnectionFraming(t *testing.T) { + h, sock := newFakeNfct(t) + sock.entries["10.0.0.1|10.0.0.2"] = true + sock.entries["10.0.0.3|10.0.0.4"] = true + + nfctLock.Lock() + prev := nfct + nfct = h + nfctLock.Unlock() + t.Cleanup(func() { + nfctLock.Lock() + nfct = prev + nfctLock.Unlock() + }) + + // testConnection is 10.0.0.1:40000 -> 10.0.0.2:443/TCP. + err := DeleteMarkedConnection(testConnection()) + if err != nil { + t.Fatalf("DeleteMarkedConnection: %s", err) + } + if sock.entries["10.0.0.1|10.0.0.2"] { + t.Error("DeleteMarkedConnection: entry was not deleted") + } + if len(sock.datagrams) != 0 { + t.Fatalf("DeleteMarkedConnection left %d unread datagrams on the handle", len(sock.datagrams)) + } + + // A missing entry is reported as an error and leaves nothing behind. + err = DeleteMarkedConnection(testConnection()) + if !errors.Is(err, unix.ENOENT) { + t.Errorf("DeleteMarkedConnection on missing entry: expected ENOENT, got %v", err) + } + if len(sock.datagrams) != 0 { + t.Fatalf("DeleteMarkedConnection (missing) left %d unread datagrams", len(sock.datagrams)) + } + + // The next request on the shared handle must still be in sync. + err = h.Delete(ct.Conntrack, ct.IPv4, fakeCon(net.IPv4(10, 0, 0, 3), net.IPv4(10, 0, 0, 4))) + if err != nil { + t.Fatalf("Delete after DeleteMarkedConnection: %s", err) + } +} diff --git a/service/firewall/interception/nfq/conntrack_recovery_test.go b/service/firewall/interception/nfq/conntrack_recovery_test.go new file mode 100644 index 000000000..7bb5bd03f --- /dev/null +++ b/service/firewall/interception/nfq/conntrack_recovery_test.go @@ -0,0 +1,442 @@ +//go:build linux + +package nfq + +import ( + "errors" + "fmt" + "net" + "os" + "sync" + "syscall" + "testing" + + ct "github.com/florianl/go-conntrack" + "github.com/mdlayher/netlink" +) + +var ( + errFakeMismatchedSeq = errors.New("mismatched sequence in netlink reply") + errFakeNoHandleLeft = errors.New("fake open: no handle left") + errFakeOpenFailed = errors.New("fake open: failed") + errFakeOther = errors.New("other error") +) + +// Errors as returned by github.com/mdlayher/netlink v1.8.0. +var ( + // recvmsg failed with ENOBUFS: the socket receive buffer overran. + errFakeENOBUFS = &netlink.OpError{Op: netlinkOpReceive, Err: os.NewSyscallError("recvmsg", syscall.ENOBUFS)} + // Conn.Execute read a reply of an earlier request. + errFakeSeqMismatch = &netlink.OpError{Op: netlinkOpValidate, Err: errFakeMismatchedSeq} + // The kernel answered with an NLMSG_ERROR carrying ENOENT. + errFakeENOENT = &netlink.OpError{Op: netlinkOpReceive, Err: syscall.ENOENT} +) + +// fakeHandle is a conntrackHandle with scripted errors. +type fakeHandle struct { + mu sync.Mutex + queryErr error // returned by every Query, if set + deleteErr error // returned by every Delete, if set + entries []ct.Con + deleted []ct.Con // attributes of every Delete call + queries int + deletes int + closed bool +} + +func (h *fakeHandle) Query(_ ct.Table, _ ct.Family, _ ct.FilterAttr) ([]ct.Con, error) { + h.mu.Lock() + defer h.mu.Unlock() + + h.queries++ + if h.queryErr != nil { + return nil, h.queryErr + } + return append([]ct.Con(nil), h.entries...), nil +} + +func (h *fakeHandle) Delete(_ ct.Table, _ ct.Family, attributes ct.Con) error { + h.mu.Lock() + defer h.mu.Unlock() + + h.deletes++ + h.deleted = append(h.deleted, attributes) + if h.deleteErr != nil { + return h.deleteErr + } + if len(h.entries) == 0 { + return errFakeENOENT + } + h.entries = h.entries[1:] + return nil +} + +func (h *fakeHandle) Close() error { + h.mu.Lock() + defer h.mu.Unlock() + + h.closed = true + return nil +} + +func (h *fakeHandle) isClosed() bool { + h.mu.Lock() + defer h.mu.Unlock() + + return h.closed +} + +// fakeOpener replaces openConntrack and hands out the given handles in order. +// A nil handle makes the open fail. +type fakeOpener struct { + mu sync.Mutex + handles []conntrackHandle + opens int +} + +func (o *fakeOpener) open() (conntrackHandle, error) { + o.mu.Lock() + defer o.mu.Unlock() + + o.opens++ + if len(o.handles) == 0 { + return nil, errFakeNoHandleLeft + } + h := o.handles[0] + o.handles = o.handles[1:] + if h == nil { + return nil, errFakeOpenFailed + } + return h, nil +} + +func (o *fakeOpener) count() int { + o.mu.Lock() + defer o.mu.Unlock() + + return o.opens +} + +// installFakeConntrack sets current as the package handle and replaces +// openConntrack with a fakeOpener handing out next. Everything is restored +// when the test ends. +func installFakeConntrack(t *testing.T, current conntrackHandle, next ...conntrackHandle) *fakeOpener { + t.Helper() + + opener := &fakeOpener{handles: next} + + nfctLock.Lock() + prevNfct, prevReopen, prevOpen := nfct, nfctReopen, openConntrack + nfct, nfctReopen, openConntrack = current, false, opener.open + nfctLock.Unlock() + + t.Cleanup(func() { + nfctLock.Lock() + nfct, nfctReopen, openConntrack = prevNfct, prevReopen, prevOpen + nfctLock.Unlock() + }) + return opener +} + +func testEntry() ct.Con { + return fakeCon(net.IPv4(10, 0, 0, 1), net.IPv4(10, 0, 0, 2)) +} + +// TestIsDesyncError checks the classification against errors produced by the +// real go-conntrack/netlink code paths. +func TestIsDesyncError(t *testing.T) { + t.Parallel() + + // Kernel error reply: benign, handle stays in sync. + h, _ := newFakeNfct(t) + err := h.Delete(ct.Conntrack, ct.IPv4, testEntry()) + if !errors.Is(err, syscall.ENOENT) { + t.Fatalf("Delete of missing entry: expected ENOENT, got %v", err) + } + if isDesyncError(err) { + t.Errorf("ENOENT must not be a desync error: %v", err) + } + + // Stale reply of an earlier request: sequence mismatch. + h, sock := newFakeNfct(t) + sock.datagrams = append(sock.datagrams, []netlink.Message{fakeAckMessage(netlink.Message{ + Header: netlink.Header{Sequence: 0xdead, PID: fakeNetlinkPID}, + }, 0)}) + err = h.Delete(ct.Conntrack, ct.IPv4, testEntry()) + if err == nil { + t.Fatal("Delete after stale reply: expected error") + } + if !isDesyncError(err) { + t.Errorf("sequence mismatch must be a desync error: %v", err) + } + + // Socket receive error (ENOBUFS) during Delete and Query. + h = newNfctWithSocket(t, &failingSocket{fakeKernelSocket: newFakeKernelSocket(), recvErr: syscall.ENOBUFS}) + err = h.Delete(ct.Conntrack, ct.IPv4, testEntry()) + if !isDesyncError(err) { + t.Errorf("Delete with ENOBUFS on recvmsg must be a desync error: %v", err) + } + _, err = h.Query(ct.Conntrack, ct.IPv4, ct.FilterAttr{ + Mark: []byte{0, 0, 0, 0}, + MarkMask: []byte{0xFF, 0xFF, 0xFF, 0xFF}, + }) + if !isDesyncError(err) { + t.Errorf("Query with ENOBUFS on recvmsg must be a desync error: %v", err) + } + + // go-conntrack fails to encode the request before sending anything. + _, err = h.Query(ct.Conntrack, ct.IPv4, ct.FilterAttr{}) + if err == nil || isDesyncError(err) { + t.Errorf("request encoding error must not be a desync error: %v", err) + } + + // Not a netlink error at all, and wrapped errors. + if isDesyncError(nil) || isDesyncError(errFakeOther) { + t.Error("nil and unrelated errors must not be desync errors") + } + if !isDesyncError(fmt.Errorf("wrapped: %w", errFakeSeqMismatch)) { + t.Error("wrapped sequence mismatch must be a desync error") + } +} + +// failingSocket fails every Receive with recvErr as recvmsg would. +type failingSocket struct { + *fakeKernelSocket + + recvErr error +} + +func (s *failingSocket) Receive() ([]netlink.Message, error) { + return nil, os.NewSyscallError("recvmsg", s.recvErr) +} + +func newNfctWithSocket(t *testing.T, sock *failingSocket) *ct.Nfct { + t.Helper() + + h, err := ct.Open(&ct.Config{}) + if err != nil { + t.Skipf("cannot open netfilter netlink socket: %s", err) + } + _ = h.Con.Close() + h.Con = netlink.NewConn(sock, fakeNetlinkPID) + t.Cleanup(func() { _ = h.Close() }) + return h +} + +// TestDeleteMarkedConnectionRecoversFromDesync uses the real go-conntrack +// handle on a fake kernel socket that has a stale reply queued (as left by +// the old Get+Delete code). Without recovery, every later request reads the +// reply of the previous one and fails forever. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestDeleteMarkedConnectionRecoversFromDesync(t *testing.T) { + desynced, desyncedSock := newFakeNfct(t) + desyncedSock.entries["10.0.0.1|10.0.0.2"] = true + desyncedSock.datagrams = append(desyncedSock.datagrams, []netlink.Message{fakeAckMessage(netlink.Message{ + Header: netlink.Header{Sequence: 0xdead, PID: fakeNetlinkPID}, + }, 0)}) + + fresh, freshSock := newFakeNfct(t) + freshSock.entries["10.0.0.1|10.0.0.2"] = true + + opener := installFakeConntrack(t, desynced, fresh) + + // testConnection is 10.0.0.1:40000 -> 10.0.0.2:443/TCP. + err := DeleteMarkedConnection(testConnection()) + if err != nil { + t.Errorf("first DeleteMarkedConnection after desync: %s", err) + } + err = DeleteMarkedConnection(testConnection()) + if !errors.Is(err, syscall.ENOENT) { + t.Errorf("second DeleteMarkedConnection: expected ENOENT (entry already deleted), got %v", err) + } + if n := opener.count(); n != 1 { + t.Errorf("expected the handle to be reopened exactly once, got %d opens", n) + } + if len(freshSock.datagrams) != 0 { + t.Errorf("reopened handle has %d unread datagrams", len(freshSock.datagrams)) + } +} + +// TestDeleteAllMarkedConnectionRecoversFromDesync checks that a dump that +// fails with ENOBUFS is restarted on a reopened handle. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestDeleteAllMarkedConnectionRecoversFromDesync(t *testing.T) { + broken := &fakeHandle{queryErr: errFakeENOBUFS, deleteErr: errFakeSeqMismatch} + fresh := &fakeHandle{entries: []ct.Con{testEntry(), testEntry()}} + opener := installFakeConntrack(t, broken, fresh) + + err := DeleteAllMarkedConnection() + if err != nil { + t.Fatalf("DeleteAllMarkedConnection: %s", err) + } + if !broken.isClosed() { + t.Error("desynchronized handle was not closed") + } + if n := opener.count(); n != 1 { + t.Errorf("expected exactly one reopen, got %d", n) + } + if broken.queries != 1 { + t.Errorf("expected the broken handle to be used once, got %d queries", broken.queries) + } + if fresh.deletes != 2 || len(fresh.entries) != 0 { + t.Errorf("expected both entries to be deleted on the reopened handle, got %d deletes, %d left", + fresh.deletes, len(fresh.entries)) + } +} + +// TestConntrackBenignErrorKeepsHandle checks that a kernel error reply such as +// ENOENT does not reopen the handle. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestConntrackBenignErrorKeepsHandle(t *testing.T) { + h := &fakeHandle{} + opener := installFakeConntrack(t, h) + + err := DeleteMarkedConnection(testConnection()) + if !errors.Is(err, syscall.ENOENT) { + t.Fatalf("expected ENOENT, got %v", err) + } + if h.isClosed() || opener.count() != 0 || h.deletes != 1 { + t.Errorf("benign error must not reopen or retry: closed=%v opens=%d deletes=%d", + h.isClosed(), opener.count(), h.deletes) + } +} + +// TestConntrackRetriesOnce checks that a failed operation is retried at most +// once, and that a handle that is still out of sync after the retry is +// replaced on the next call. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestConntrackRetriesOnce(t *testing.T) { + first := &fakeHandle{deleteErr: errFakeSeqMismatch} + second := &fakeHandle{deleteErr: errFakeSeqMismatch} + third := &fakeHandle{entries: []ct.Con{testEntry()}} + opener := installFakeConntrack(t, first, second, third) + + err := DeleteMarkedConnection(testConnection()) + if err == nil { + t.Fatal("expected error when the retry fails as well") + } + if first.deletes != 1 || second.deletes != 1 || opener.count() != 1 { + t.Errorf("expected one attempt per handle and one reopen: %d, %d, opens=%d", + first.deletes, second.deletes, opener.count()) + } + if !first.isClosed() || !second.isClosed() { + t.Error("desynchronized handles were not closed") + } + + err = DeleteMarkedConnection(testConnection()) + if err != nil { + t.Errorf("next call on a reopened handle: %s", err) + } + if opener.count() != 2 || third.deletes != 1 { + t.Errorf("expected the next call to reopen: opens=%d deletes=%d", opener.count(), third.deletes) + } +} + +// TestConntrackReopenFailure checks that a failed reopen leaves a state from +// which a later call recovers, and that teardown still wins. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestInitNFCTClosesPreviousHandle(t *testing.T) { + old := &fakeHandle{} + fresh := &fakeHandle{} + opener := installFakeConntrack(t, old, fresh) + + err := InitNFCT() + if err != nil { + t.Fatalf("InitNFCT: %s", err) + } + if !old.isClosed() { + t.Error("InitNFCT did not close the previously open handle") + } + if fresh.isClosed() { + t.Error("InitNFCT closed the new handle") + } + if n := opener.count(); n != 1 { + t.Errorf("expected 1 open, got %d", n) + } + + TeardownNFCT() + if !fresh.isClosed() { + t.Error("TeardownNFCT did not close the new handle") + } +} + +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestConntrackReopenFailure(t *testing.T) { + broken := &fakeHandle{deleteErr: errFakeENOBUFS} + fresh := &fakeHandle{entries: []ct.Con{testEntry()}} + opener := installFakeConntrack(t, broken, nil, nil, fresh) + + err := DeleteMarkedConnection(testConnection()) + if !errors.Is(err, syscall.ENOBUFS) { + t.Fatalf("expected the original ENOBUFS error, got %v", err) + } + err = DeleteAllMarkedConnection() + if err == nil { + t.Error("DeleteAllMarkedConnection: expected error while the handle cannot be reopened") + } + err = DeleteMarkedConnection(testConnection()) + if err != nil { + t.Errorf("DeleteMarkedConnection after the open works again: %s", err) + } + if n := opener.count(); n != 3 { + t.Errorf("expected 3 open attempts, got %d", n) + } + + TeardownNFCT() + if !fresh.isClosed() { + t.Error("TeardownNFCT did not close the reopened handle") + } + err = DeleteMarkedConnection(testConnection()) + if !errors.Is(err, errNFCTNotInitialized) { + t.Errorf("after teardown: expected not initialized, got %v", err) + } + if n := opener.count(); n != 3 { + t.Errorf("handle must not be reopened after teardown, got %d opens", n) + } +} + +// TestConntrackRetriedDeleteENOENT checks that ENOENT on the retry of a +// delete is not reported as a failure: the kernel may have executed the first +// attempt before its reply was lost or left behind, so the entry is gone +// either way. ENOENT on a first attempt is still reported (see +// TestConntrackBenignErrorKeepsHandle). +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestConntrackRetriedDeleteENOENT(t *testing.T) { + // The kernel deleted the entry, but its ACK was lost (ENOBUFS); the + // entry is no longer in the table when the delete is retried. + broken := &fakeHandle{deleteErr: errFakeENOBUFS} + fresh := &fakeHandle{} + opener := installFakeConntrack(t, broken, fresh) + + err := DeleteMarkedConnection(testConnection()) + if err != nil { + t.Errorf("retried delete that found no entry reported a failure: %s", err) + } + if opener.count() != 1 || broken.deletes != 1 || fresh.deletes != 1 { + t.Errorf("expected one reopen and one retry: opens=%d deletes=%d,%d", + opener.count(), broken.deletes, fresh.deletes) + } + // ENOENT on the first attempt of the next delete is still an error. + err = DeleteMarkedConnection(testConnection()) + if !errors.Is(err, syscall.ENOENT) { + t.Errorf("first-attempt ENOENT: expected ENOENT, got %v", err) + } + + // The same applies to the deletes of DeleteAllMarkedConnection: the + // queried entry counts as deleted. Later queries go to the empty + // reopened handle. + broken2 := &fakeHandle{entries: []ct.Con{testEntry()}, deleteErr: errFakeSeqMismatch} + installFakeConntrack(t, broken2, &fakeHandle{}) + nfctLock.Lock() + deleted := deleteMarkedConnections(ct.IPv4) + nfctLock.Unlock() + if deleted != 1 { + t.Errorf("expected 1 deleted entry, got %d", deleted) + } +} diff --git a/service/firewall/interception/nfq/conntrack_test.go b/service/firewall/interception/nfq/conntrack_test.go new file mode 100644 index 000000000..0e5e08d0a --- /dev/null +++ b/service/firewall/interception/nfq/conntrack_test.go @@ -0,0 +1,116 @@ +//go:build linux + +package nfq + +import ( + "errors" + "net" + "testing" + + ct "github.com/florianl/go-conntrack" + + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/network" + pmpacket "github.com/safing/portmaster/service/network/packet" +) + +func testConnection() *network.Connection { + return &network.Connection{ + IPVersion: pmpacket.IPv4, + LocalIP: net.IPv4(10, 0, 0, 1), + LocalPort: 40000, + Entity: &intel.Entity{ + IP: net.IPv4(10, 0, 0, 2), + Protocol: 6, + Port: 443, + }, + } +} + +// TestConntrackUninitialized checks that all operations report an error +// instead of using a nil (or closed) handle, and that teardown is idempotent. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestConntrackUninitialized(t *testing.T) { + TeardownNFCT() + TeardownNFCT() + + if DeleteUnmarkedConnections() == nil { + t.Error("DeleteUnmarkedConnections: expected error on uninitialized handle") + } + if DeleteAllMarkedConnection() == nil { + t.Error("DeleteAllMarkedConnection: expected error on uninitialized handle") + } + if DeleteMarkedConnection(testConnection()) == nil { + t.Error("DeleteMarkedConnection: expected error on uninitialized handle") + } +} + +// TestDeleteMarkedConnectionIncomplete checks that a connection without +// remote entity or local address is rejected instead of dereferencing nil. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestDeleteMarkedConnectionIncomplete(t *testing.T) { + h := &fakeHandle{} + installFakeConntrack(t, h) + + noEntity := testConnection() + noEntity.Entity = nil + noEntityIP := testConnection() + noEntityIP.Entity.IP = nil + noLocalIP := testConnection() + noLocalIP.LocalIP = nil + + for _, conn := range []*network.Connection{noEntity, noEntityIP, noLocalIP} { + err := DeleteMarkedConnection(conn) + if !errors.Is(err, errConnectionIncomplete) { + t.Errorf("expected errConnectionIncomplete, got %v", err) + } + } + if h.deletes != 0 { + t.Errorf("no request must be sent for incomplete connections, got %d", h.deletes) + } +} + +// TestDeleteFlow checks that DeleteFlow deletes by the given original tuple +// and treats a missing entry as success. +// +//nolint:paralleltest // Modifies the package-level conntrack handle. +func TestDeleteFlow(t *testing.T) { + localIP, remoteIP := net.IPv4(10, 0, 2, 15).To4(), net.IPv4(10, 0, 2, 3).To4() + + // No entry: ENOENT is not an error. + h := &fakeHandle{} + installFakeConntrack(t, h) + deleted, err := DeleteFlow(17, localIP, 59823, remoteIP, 53) + if err != nil || deleted { + t.Fatalf("missing entry: expected no error and no delete, got %v, %v", deleted, err) + } + + // Existing entry: deleted by the original tuple. + h = &fakeHandle{entries: []ct.Con{testEntry()}} + installFakeConntrack(t, h) + deleted, err = DeleteFlow(17, localIP, 59823, remoteIP, 53) + if err != nil || !deleted { + t.Fatalf("existing entry: expected a delete, got %v, %v", deleted, err) + } + if len(h.deleted) != 1 { + t.Fatalf("expected 1 delete, got %d", len(h.deleted)) + } + origin := h.deleted[0].Origin + switch { + case !origin.Src.Equal(localIP) || !origin.Dst.Equal(remoteIP): + t.Errorf("deleted %s -> %s, expected %s -> %s", origin.Src, origin.Dst, localIP, remoteIP) + case *origin.Proto.Number != 17 || *origin.Proto.SrcPort != 59823 || *origin.Proto.DstPort != 53: + t.Errorf("deleted protocol %d ports %d -> %d, expected 17 ports 59823 -> 53", + *origin.Proto.Number, *origin.Proto.SrcPort, *origin.Proto.DstPort) + } + + // Other errors are returned. + h = &fakeHandle{deleteErr: errFakeOpenFailed} + installFakeConntrack(t, h, &fakeHandle{deleteErr: errFakeOpenFailed}) + _, err = DeleteFlow(17, localIP, 59823, remoteIP, 53) + if err == nil { + t.Error("expected an error to be returned") + } +} diff --git a/service/firewall/interception/nfq/nfq.go b/service/firewall/interception/nfq/nfq.go index ddead1013..e823fb390 100644 --- a/service/firewall/interception/nfq/nfq.go +++ b/service/firewall/interception/nfq/nfq.go @@ -194,39 +194,26 @@ func (q *Queue) packetHandler(ctx context.Context) func(nfqueue.Attribute) int { return 0 } - select { - case q.packets <- pkt: - // DEBUG: - // log.Tracef("nfqueue: queued packet %s (%s -> %s) after %s", pkt.ID(), pkt.Info().Src, pkt.Info().Dst, time.Since(pkt.Info().SeenAt)) - case <-ctx.Done(): - return 0 - case <-time.After(time.Second): - // The packet did not make it into the handler queue, so no handler - // will ever see it and set a verdict. Drop it now instead of letting - // it wait in the kernel queue until the verdict timeout. - log.Warningf("nfqueue: failed to queue packet %s (%s since it was handed over by the kernel), dropping", pkt.ID(), time.Since(pkt.Info().SeenAt)) - if err := pkt.Drop(); err != nil { - log.Warningf("nfqueue: failed to drop unqueued packet %s: %s", pkt.ID(), err) - } - return 0 - } - - go func() { - select { - case <-pkt.verdictSet: - - case <-time.After(20 * time.Second): - log.Warningf("nfqueue: no verdict set for packet %s (%s -> %s) after %s, dropping", pkt.ID(), pkt.Info().Src, pkt.Info().Dst, time.Since(pkt.Info().SeenAt)) - if err := pkt.Drop(); err != nil { - log.Warningf("nfqueue: failed to apply default-drop to unveridcted packet %s (%s -> %s)", pkt.ID(), pkt.Info().Src, pkt.Info().Dst) - } - } - }() + q.queuePacket(ctx, pkt) return 0 // continue calling this fn } } +// Timeouts for packets handed to the handler queue. They are variables so tests +// can shorten them. +var ( + // queueTimeout is how long the nfqueue receive goroutine waits for room in + // the handler queue before dropping the packet. + queueTimeout = time.Second + // verdictTimeout is how long a queued packet may wait for a verdict before + // it is dropped by the verdict watchdog. + verdictTimeout = 20 * time.Second + // verdictTimeoutHandler is called by the verdict watchdog. Tests may + // replace it, as the real handler needs a live nfqueue to set a verdict. + verdictTimeoutHandler = (*packet).handleVerdictTimeout +) + // Destroy destroys the queue. Any error encountered is logged. func (q *Queue) Destroy() { if q == nil { @@ -246,3 +233,35 @@ func (q *Queue) Destroy() { func (q *Queue) PacketChannel() <-chan pmpacket.Packet { return q.packets } + +// queuePacket hands the packet to the handler queue and arms the watchdog +// that drops the packet if no verdict is set in time. +func (q *Queue) queuePacket(ctx context.Context, pkt *packet) { + // Fast path: the handler queue has room. Do not allocate a timer. + select { + case q.packets <- pkt: + pkt.startVerdictWatchdog() + return + default: + } + + // Slow path: wait for room in the handler queue, but not forever. + timer := time.NewTimer(queueTimeout) + defer timer.Stop() + select { + case q.packets <- pkt: + // DEBUG: + // log.Tracef("nfqueue: queued packet %s (%s -> %s) after %s", pkt.ID(), pkt.Info().Src, pkt.Info().Dst, time.Since(pkt.Info().SeenAt)) + pkt.startVerdictWatchdog() + case <-ctx.Done(): + case <-timer.C: + // The packet did not make it into the handler queue, so no handler + // will ever see it and set a verdict. Drop it now instead of letting + // it wait in the kernel queue until the verdict timeout. + log.Warningf("nfqueue: failed to queue packet %s (%s since it was handed over by the kernel), dropping", pkt.ID(), time.Since(pkt.Info().SeenAt)) + err := pkt.Drop() + if err != nil { + log.Warningf("nfqueue: failed to drop unqueued packet %s: %s", pkt.ID(), err) + } + } +} diff --git a/service/firewall/interception/nfq/nfq_bench_test.go b/service/firewall/interception/nfq/nfq_bench_test.go new file mode 100644 index 000000000..8d046cae8 --- /dev/null +++ b/service/firewall/interception/nfq/nfq_bench_test.go @@ -0,0 +1,95 @@ +//go:build linux + +package nfq + +import ( + "context" + "testing" + + "github.com/florianl/go-nfqueue" + "github.com/tevino/abool" + + pmpacket "github.com/safing/portmaster/service/network/packet" +) + +// simulateVerdict does what packet.mark does, minus talking to the kernel. +func simulateVerdict(pkt *packet) { + if pkt.verdictPending.SetToIf(false, true) { + pkt.verdictDone() + } +} + +func newTestQueue() *Queue { + return &Queue{ + id: 1, + packets: make(chan pmpacket.Packet, 1000), + verdictCompleted: make(chan struct{}, 1), + } +} + +func newTestPacket(q *Queue, id uint32) *packet { + return &packet{ + pktID: id, + queue: q, + verdictSet: make(chan struct{}), + verdictPending: abool.New(), + } +} + +// runVerdicter consumes packets from the queue and sets a verdict on each. +func runVerdicter(q *Queue) (stop func()) { + done := make(chan struct{}) + go func() { + defer close(done) + for p := range q.packets { + simulateVerdict(p.(*packet)) //nolint:forcetypeassert + } + }() + return func() { + close(q.packets) + <-done + } +} + +// BenchmarkQueuePacket measures the per-packet bookkeeping done on the nfqueue +// receive goroutine after parsing: handing the packet to the handler queue and +// arming the missing-verdict watchdog. A consumer sets verdicts immediately. +func BenchmarkQueuePacket(b *testing.B) { + q := newTestQueue() + stop := runVerdicter(q) + ctx := context.Background() + + b.ReportAllocs() + b.ResetTimer() + for i := range b.N { + q.queuePacket(ctx, newTestPacket(q, uint32(i))) //nolint:gosec + } + b.StopTimer() + stop() +} + +// testPayload is a minimal IPv4/TCP SYN packet (10.0.0.1:40000 -> 10.0.0.2:443). +var testPayload = []byte{ + 0x45, 0x00, 0x00, 0x28, 0x00, 0x01, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, + 10, 0, 0, 1, 10, 0, 0, 2, + 0x9c, 0x40, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x50, 0x02, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, +} + +// BenchmarkPacketHandler measures the complete nfqueue callback (including +// payload parsing) for context. +func BenchmarkPacketHandler(b *testing.B) { + q := newTestQueue() + stop := runVerdicter(q) + handler := q.packetHandler(context.Background()) + payload := testPayload + + b.ReportAllocs() + b.ResetTimer() + for i := range b.N { + id := uint32(i) //nolint:gosec + handler(nfqueue.Attribute{PacketID: &id, Payload: &payload}) + } + b.StopTimer() + stop() +} diff --git a/service/firewall/interception/nfq/nfq_test.go b/service/firewall/interception/nfq/nfq_test.go new file mode 100644 index 000000000..b9c250619 --- /dev/null +++ b/service/firewall/interception/nfq/nfq_test.go @@ -0,0 +1,132 @@ +//go:build linux + +package nfq + +import ( + "context" + "testing" + "time" + + pmpacket "github.com/safing/portmaster/service/network/packet" +) + +// setWatchdogForTest shortens the verdict timeout and replaces the timeout +// handler with one that reports the packet on the returned channel. +func setWatchdogForTest(t *testing.T, timeout time.Duration) <-chan *packet { + t.Helper() + + fired := make(chan *packet, 10) + oldTimeout, oldHandler := verdictTimeout, verdictTimeoutHandler + verdictTimeout = timeout + verdictTimeoutHandler = func(pkt *packet) { fired <- pkt } + t.Cleanup(func() { + verdictTimeout, verdictTimeoutHandler = oldTimeout, oldHandler + }) + return fired +} + +func TestVerdictWatchdogStoppedByVerdict(t *testing.T) { //nolint:paralleltest // Modifies the package-level verdict timeout and handler. + fired := setWatchdogForTest(t, 50*time.Millisecond) + + q := newTestQueue() + pkt := newTestPacket(q, 1) + q.queuePacket(context.Background(), pkt) + + if queued := <-q.packets; queued != pkt { + t.Fatal("unexpected packet in queue") + } + if pkt.verdictWatchdog.Load() == nil { + t.Fatal("watchdog not armed for queued packet") + } + simulateVerdict(pkt) + + // The watchdog must have been stopped by setting the verdict. + if pkt.verdictWatchdog.Load().Stop() { + t.Fatal("watchdog still active after verdict was set") + } + select { + case <-fired: + t.Fatal("watchdog fired although a verdict was set") + case <-time.After(200 * time.Millisecond): + } +} + +func TestVerdictWatchdogVerdictBeforeArming(t *testing.T) { //nolint:paralleltest // Modifies the package-level verdict timeout and handler. + fired := setWatchdogForTest(t, 50*time.Millisecond) + + // The verdict is set by a handler before the receive goroutine armed the + // watchdog: arming must stop it right away. + pkt := newTestPacket(newTestQueue(), 1) + simulateVerdict(pkt) + pkt.startVerdictWatchdog() + + if pkt.verdictWatchdog.Load().Stop() { + t.Fatal("watchdog still active after verdict was set") + } + select { + case <-fired: + t.Fatal("watchdog fired although a verdict was set") + case <-time.After(200 * time.Millisecond): + } +} + +func TestVerdictWatchdogFiresWithoutVerdict(t *testing.T) { //nolint:paralleltest // Modifies the package-level verdict timeout and handler. + const timeout = 100 * time.Millisecond + fired := setWatchdogForTest(t, timeout) + + q := newTestQueue() + pkt := newTestPacket(q, 1) + start := time.Now() + q.queuePacket(context.Background(), pkt) + <-q.packets // The handler receives the packet, but never sets a verdict. + + select { + case got := <-fired: + if got != pkt { + t.Fatal("watchdog fired for wrong packet") + } + if elapsed := time.Since(start); elapsed < timeout { + t.Fatalf("watchdog fired too early: after %s", elapsed) + } + case <-time.After(5 * time.Second): + t.Fatal("watchdog did not fire for packet without verdict") + } + select { + case <-fired: + t.Fatal("watchdog fired more than once") + case <-time.After(200 * time.Millisecond): + } +} + +func TestHandleVerdictTimeoutAfterVerdict(t *testing.T) { + t.Parallel() + + // If the verdict was set by the time the watchdog fires, the timeout + // handler must neither log nor try to drop (which would need a live queue + // and panic without one). + pkt := newTestPacket(newTestQueue(), 1) + simulateVerdict(pkt) + pkt.handleVerdictTimeout() +} + +func TestQueuePacketCanceled(t *testing.T) { //nolint:paralleltest // Modifies the package-level verdict timeout and handler. + fired := setWatchdogForTest(t, 50*time.Millisecond) + + // Full handler queue and canceled context: the packet is not queued and + // no watchdog is armed, as before. + q := newTestQueue() + q.packets = make(chan pmpacket.Packet) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + pkt := newTestPacket(q, 1) + q.queuePacket(ctx, pkt) + if pkt.verdictWatchdog.Load() != nil { + t.Fatal("watchdog armed for packet that was not queued") + } + select { + case <-fired: + t.Fatal("watchdog fired for packet that was not queued") + case <-time.After(200 * time.Millisecond): + } +} diff --git a/service/firewall/interception/nfq/packet.go b/service/firewall/interception/nfq/packet.go index f6e99d21b..d3ef1b920 100644 --- a/service/firewall/interception/nfq/packet.go +++ b/service/firewall/interception/nfq/packet.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "sync/atomic" + "time" "github.com/florianl/go-nfqueue" "github.com/tevino/abool" @@ -66,6 +67,10 @@ type packet struct { queue *Queue verdictSet chan struct{} verdictPending *abool.AtomicBool + + // verdictWatchdog drops the packet if no verdict is set in time. + // It is stopped as soon as a verdict was set. + verdictWatchdog atomic.Pointer[time.Timer] } func (pkt *packet) ID() string { @@ -95,7 +100,7 @@ func (pkt *packet) VerdictSet() bool { // raw-socket. func (pkt *packet) mark(mark int) (err error) { if pkt.verdictPending.SetToIf(false, true) { - defer close(pkt.verdictSet) + defer pkt.verdictDone() return pkt.setMark(mark) } @@ -201,10 +206,49 @@ func (pkt *packet) RerouteToNameserver() error { return pkt.mark(MarkRerouteNS) } -func (pkt *packet) RerouteToTunnel() error { - return pkt.mark(MarkRerouteSPN) -} - func (pkt *packet) RerouteToSplitTun() error { return pkt.mark(MarkRerouteSplitTun) } + +// verdictDone signals that the verdict was set and stops the verdict watchdog. +func (pkt *packet) verdictDone() { + close(pkt.verdictSet) + if t := pkt.verdictWatchdog.Load(); t != nil { + t.Stop() + } +} + +// startVerdictWatchdog arms a timer that drops the packet if no verdict was set +// within verdictTimeout. It must be called at most once per packet. +func (pkt *packet) startVerdictWatchdog() { + t := time.AfterFunc(verdictTimeout, func() { + verdictTimeoutHandler(pkt) + }) + pkt.verdictWatchdog.Store(t) + + // The verdict may have been set before the timer was stored, in which case + // verdictDone did not see it. Stop it here, so it does not keep the packet + // alive until it fires. (Should both miss each other, the timeout handler + // still checks verdictSet and does nothing.) + select { + case <-pkt.verdictSet: + t.Stop() + default: + } +} + +// handleVerdictTimeout drops the packet if no verdict was set yet. +func (pkt *packet) handleVerdictTimeout() { + select { + case <-pkt.verdictSet: + // Verdict was set in the meantime. + return + default: + } + + log.Warningf("nfqueue: no verdict set for packet %s (%s -> %s) after %s, dropping", pkt.ID(), pkt.Info().Src, pkt.Info().Dst, time.Since(pkt.Info().SeenAt)) + err := pkt.Drop() + if err != nil { + log.Warningf("nfqueue: failed to apply default-drop to unveridcted packet %s (%s -> %s)", pkt.ID(), pkt.Info().Src, pkt.Info().Dst) + } +} diff --git a/service/firewall/interception/packet_tracer.go b/service/firewall/interception/packet_tracer.go index d7f466d14..24607688f 100644 --- a/service/firewall/interception/packet_tracer.go +++ b/service/firewall/interception/packet_tracer.go @@ -61,11 +61,6 @@ func (p *tracedPacket) RerouteToNameserver() error { return p.Packet.RerouteToNameserver() } -func (p *tracedPacket) RerouteToTunnel() error { - defer p.markServed("reroute-tunnel") - return p.Packet.RerouteToTunnel() -} - func (p *tracedPacket) RerouteToSplitTun() error { defer p.markServed("reroute-splittun") return p.Packet.RerouteToSplitTun() diff --git a/service/firewall/interception/windowskext/packet.go b/service/firewall/interception/windowskext/packet.go index 5fdba4508..c35cb0da9 100644 --- a/service/firewall/interception/windowskext/packet.go +++ b/service/firewall/interception/windowskext/packet.go @@ -133,14 +133,6 @@ func (pkt *Packet) RerouteToNameserver() error { return nil } -// RerouteToTunnel permanently reroutes the connection to the local tunnel entrypoint (and the current packet). -func (pkt *Packet) RerouteToTunnel() error { - if pkt.verdictSet.SetToIf(false, true) { - return SetVerdict(pkt, network.VerdictRerouteToTunnel) - } - return nil -} - // RerouteToSplitTun permanently reroutes the connection to the split tunnel (and the current packet). func (pkt *Packet) RerouteToSplitTun() error { if pkt.verdictSet.SetToIf(false, true) { diff --git a/service/firewall/interception/windowskext2/packet.go b/service/firewall/interception/windowskext2/packet.go index 23c29edf5..e1d4edea7 100644 --- a/service/firewall/interception/windowskext2/packet.go +++ b/service/firewall/interception/windowskext2/packet.go @@ -138,14 +138,6 @@ func (pkt *Packet) RerouteToNameserver() error { return nil } -// RerouteToTunnel permanently reroutes the connection to the local tunnel entrypoint (and the current packet). -func (pkt *Packet) RerouteToTunnel() error { - if pkt.verdictSet.SetToIf(false, true) { - return SetVerdict(pkt, kextinterface.VerdictRerouteToTunnel) - } - return nil -} - // RerouteToSplitTun permanently reroutes the connection to the local split tunnel entrypoint (and the current packet). func (pkt *Packet) RerouteToSplitTun() error { if pkt.verdictSet.SetToIf(false, true) { diff --git a/service/firewall/master.go b/service/firewall/master.go index 95d22212f..bf73a8eba 100644 --- a/service/firewall/master.go +++ b/service/firewall/master.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/agext/levenshtein" - "golang.org/x/net/publicsuffix" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/detection/dga" @@ -483,8 +482,8 @@ func checkDomainHeuristics(ctx context.Context, conn *network.Connection, p *pro } trimmedDomain := strings.TrimRight(conn.Entity.Domain, ".") - etld1, err := publicsuffix.EffectiveTLDPlusOne(trimmedDomain) - if err != nil { + etld1, ok := conn.Entity.EffectiveTLDPlusOne() + if !ok { // Don't run the check if the domain is a TLD. return false } diff --git a/service/firewall/module.go b/service/firewall/module.go index 0fbcbc565..c933fa538 100644 --- a/service/firewall/module.go +++ b/service/firewall/module.go @@ -18,8 +18,6 @@ import ( "github.com/safing/portmaster/service/profile" "github.com/safing/portmaster/service/resolver" "github.com/safing/portmaster/service/updates" - "github.com/safing/portmaster/spn/access" - "github.com/safing/portmaster/spn/captain" ) type stringSliceFlag []string @@ -68,10 +66,10 @@ func (f *Firewall) Stop() error { } func prep() error { - network.SetDefaultFirewallHandler(defaultFirewallHandler) + network.SetDefaultFirewallHandler(defaultFirewallHandler, defaultLockFreeFirewallHandler) // Reset connections every time configuration changes - // this will be triggered on spn enable/disable + // so that changed settings apply to existing connections. module.instance.Config().EventConfigChange.AddCallback("reset connection verdicts after global config change", func(w *mgr.WorkerCtx, _ struct{}) (bool, error) { resetAllConnectionVerdicts() return false, nil @@ -90,20 +88,6 @@ func prep() error { }, ) - // Reset connections when spn is connected - // connect and disconnecting is triggered on config change event but connecting takеs more time - module.instance.Captain().EventSPNConnected.AddCallback("reset connection verdicts on SPN connect", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) { - resetAllConnectionVerdicts() - return false, err - }) - - // Reset connections when account is updated. - // This will not change verdicts, but will update the feature flags on connections. - module.instance.Access().EventAccountUpdate.AddCallback("update connection feature flags after account update", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) { - resetAllConnectionVerdicts() - return false, err - }) - module.instance.Network().EventConnectionReattributed.AddCallback("reset connection verdicts after connection re-attribution", func(wc *mgr.WorkerCtx, connID string) (cancel bool, err error) { // Expected event data: connection ID. resetSingleConnectionVerdict(connID) @@ -164,8 +148,6 @@ type instance interface { Config() *config.Config BinaryUpdates() *updates.Updater Profile() *profile.ProfileModule - Captain() *captain.Captain - Access() *access.Access Network() *network.Network NetQuery() *netquery.NetQuery Resolver() *resolver.ResolverModule diff --git a/service/firewall/packet_handler.go b/service/firewall/packet_handler.go index 15acb8962..8303e21f1 100644 --- a/service/firewall/packet_handler.go +++ b/service/firewall/packet_handler.go @@ -27,7 +27,6 @@ import ( "github.com/safing/portmaster/service/process" "github.com/safing/portmaster/service/profile" "github.com/safing/portmaster/service/resolver" - "github.com/safing/portmaster/spn/access" ) type ExtVerdictHandlerFunc func(conn *network.Connection) (verdict network.Verdict, reason string, skipTunnel bool) @@ -64,6 +63,15 @@ func resetSingleConnectionVerdict(connID string) { } } + // Skip incomplete connections, as they have no process, entity and profile + // to re-evaluate yet. Only complete connections are re-attributed, but the + // ID may refer to a new connection by now. Its firewall handler decides on + // it with the current profile once its data is complete. + if !conn.DataIsComplete() { + tracer.Debugf("filter: skipping re-evaluation of incomplete connection %s", connID) + return + } + resetConnectionVerdict(ctx, conn) } @@ -73,16 +81,16 @@ func resetProfileConnectionVerdict(profileSource, profileID string) { defer tracer.Submit() // Resetting will force all the connection to be evaluated by the firewall again - // this will set new verdicts if configuration was update or spn has been disabled or enabled. + // this will set new verdicts if configuration was updated. tracer.Infof("filter: re-evaluating connections of %s/%s", profileSource, profileID) // Re-evaluate all connections. var changedVerdicts int for _, conn := range network.GetAllConnections() { // Check if connection is complete and attributed to the deleted profile. - if conn.DataIsComplete() && - conn.ProcessContext.Profile == profileID && - conn.ProcessContext.Source == profileSource { + // The attribution may only be read while holding the connection lock, + // as connections are re-attributed concurrently. + if conn.IsAttributedToProfile(profileSource, profileID) { if resetConnectionVerdict(ctx, conn) { changedVerdicts++ } @@ -97,7 +105,7 @@ func resetAllConnectionVerdicts() { defer tracer.Submit() // Resetting will force all the connection to be evaluated by the firewall again - // this will set new verdicts if configuration was update or spn has been disabled or enabled. + // this will set new verdicts if configuration was updated. tracer.Info("filter: re-evaluating all connections") // Re-evaluate all connections. @@ -130,14 +138,11 @@ func resetConnectionVerdict(ctx context.Context, conn *network.Connection) (verd } // Update feature flags. - if err := conn.UpdateFeatures(); err != nil && !errors.Is(err, access.ErrNotLoggedIn) { - tracer.Warningf("filter: failed to update connection feature flags: %s", err) - } + conn.UpdateFeatures() // Skip internal connections: // - Pre-authenticated connections from Portmaster // - Redirected DNS requests - // - SPN Uplink to Home Hub if conn.Internal { // tracer.Tracef("filter: skipping internal connection %s", conn) return false @@ -146,23 +151,11 @@ func resetConnectionVerdict(ctx context.Context, conn *network.Connection) (verd tracer.Debugf("filter: re-evaluating verdict of %s", conn) previousVerdict := conn.Verdict - // Apply privacy filter and check tunneling. + // Apply privacy filter and check split tunneling. FilterConnection(ctx, conn, nil, true, true) - // Stop existing SPN tunnel if not needed anymore. - if conn.Verdict != network.VerdictRerouteToTunnel && conn.TunnelContext != nil { - err := conn.TunnelContext.StopTunnel() - if err != nil { - tracer.Debugf("filter: failed to stopped unneeded tunnel: %s", err) - } - } - // Save if verdict changed. if conn.Verdict != previousVerdict { - err := interception.UpdateVerdictOfConnection(conn) - if err != nil { - log.Debugf("filter: failed to update connection verdict: %s", err) - } conn.Save() tracer.Infof("filter: verdict of connection %s changed from %s to %s", conn, previousVerdict.Verb(), conn.VerdictVerb()) @@ -212,9 +205,15 @@ func handlePacket(pkt packet.Packet) { // First, check for an existing connection. conn, ok := network.GetConnection(pkt.GetConnectionID()) if ok { - // Add packet to connection handler queue or apply verdict directly. - conn.HandlePacket(pkt) - return + // An ended connection stays in the state for a while. A packet with + // its address tuple then comes from a new socket, possibly of another + // process, and must not inherit its verdict. + if !conn.HasEnded() || !network.RemoveEndedConnection(conn) { + // Add packet to connection handler queue or apply verdict directly. + conn.HandlePacket(pkt) + return + } + log.Tracer(pkt.Ctx()).Debugf("filter: %s reuses the address tuple of an ended connection", pkt) } // Info-only packets do not represent an actual packet and can never complete @@ -384,7 +383,11 @@ func fastTrackedPermit(conn *network.Connection, pkt packet.Packet) (verdict net // Add to DNS request connections to attribute DNS request if outgoing. if pkt.IsOutbound() { // Assign PID from packet directly, as processing stops after fast-track. - conn.PID = pkt.Info().PID + // Keep a PID that is already known (e.g. adopted from a PID hint) if + // the packet does not carry one, as nfqueue packets never do. + if pkt.Info().PID != process.UndefinedProcessID { + conn.PID = pkt.Info().PID + } network.SaveDNSRequestConnection(conn, pkt) } @@ -530,7 +533,7 @@ func filterHandler(conn *network.Connection, pkt packet.Packet) { return } - // Apply privacy filter and check tunneling. + // Apply privacy filter and check split tunneling. FilterConnection(pkt.Ctx(), conn, pkt, filterConnection, checkTunnel) // Decide how to continue handling connection. @@ -548,7 +551,7 @@ func filterHandler(conn *network.Connection, pkt packet.Packet) { } } -// FilterConnection runs all the filtering (and tunneling) procedures. +// FilterConnection runs all the filtering (and split tunneling) procedures. func FilterConnection(ctx context.Context, conn *network.Connection, pkt packet.Packet, checkFilter, checkTunnel bool) { // Skip if data is not complete. if !conn.DataIsComplete() { @@ -585,8 +588,7 @@ func FilterConnection(ctx context.Context, conn *network.Connection, pkt packet. // TODO: Enable inspection framework again. // conn.Inspecting = false - // TODO: Quick fix for the SPN. - // Use inspection framework for proper encryption detection. + // TODO: Use inspection framework for proper encryption detection. switch conn.Entity.DstPort() { case 22, // SSH @@ -598,29 +600,12 @@ func FilterConnection(ctx context.Context, conn *network.Connection, pkt packet. conn.Encrypted = true } - // Check if connection should be tunneled. + // Check if connection should be split tunneled. if checkTunnel { - checkTunneling(ctx, conn) - - if conn.Verdict != network.VerdictRerouteToTunnel { - // SPN takes precedence over Split Tunnel, so only check split tunneling if not already set to tunnel. - checkSplitTunneling(ctx, conn) - } + checkSplitTunneling(ctx, conn) } - // Request tunneling if no tunnel is set and connection should be tunneled. - if conn.Verdict == network.VerdictRerouteToTunnel && - conn.TunnelContext == nil { - err := requestTunneling(ctx, conn) - if err == nil { - conn.ConnectionEstablished = true - } else { - // Set connection to failed, but keep tunneling data. - // The tunneling data makes connection easy to recognize as a failed SPN - // connection and the data will help with debugging and displaying in the UI. - conn.Failed(fmt.Sprintf("failed to request tunneling: %s", err), "") - } - } else if conn.Verdict == network.VerdictRerouteToSplitTun { + if conn.Verdict == network.VerdictRerouteToSplitTun { // Request split tunneling err := requestSplitTunneling(ctx, conn) if err != nil { @@ -629,7 +614,9 @@ func FilterConnection(ctx context.Context, conn *network.Connection, pkt packet. } } -// defaultFirewallHandler is used when no other firewall handler is set on a connection. +// defaultFirewallHandler is used when no other firewall handler is set on a +// connection. Like all firewall handlers, it is called with the connection +// locked. func defaultFirewallHandler(conn *network.Connection, pkt packet.Packet) { switch conn.IPProtocol { //nolint:exhaustive case packet.ICMP, packet.ICMPv6: @@ -641,6 +628,27 @@ func defaultFirewallHandler(conn *network.Connection, pkt packet.Packet) { } } +// defaultLockFreeFirewallHandler is used when no other firewall handler is +// set on a connection and the packet is handled directly on the packet +// dispatching goroutine. The connection is not locked and the handler must +// never wait for the connection lock. It may only access the immutable +// attributes of the connection and its lock-free verdict state. +func defaultLockFreeFirewallHandler(conn *network.Connection, pkt packet.Packet) { + switch conn.IPProtocol { //nolint:exhaustive + case packet.ICMP, packet.ICMPv6: + // Always use the ICMP handler for ICMP connections. + icmpLockFreeHandler(conn, pkt) + + default: + // Ignore info-only packets in this handler. + if pkt.InfoOnly() { + return + } + + issueVerdictLockFree(conn, pkt, 0, true) + } +} + func verdictHandler(conn *network.Connection, pkt packet.Packet) { // Ignore info-only packets in this handler. if pkt.InfoOnly() { @@ -761,19 +769,55 @@ func inspectDNSPacket(conn *network.Connection, pkt packet.Packet) { } func icmpFilterHandler(conn *network.Connection, pkt packet.Packet) { + // Handle packets that do not need to be evaluated. + if verdict, handled := icmpPreFilter(pkt); handled { + issueVerdict(conn, pkt, verdict, false) + return + } + + icmpEvaluate(conn, pkt) + + issueVerdict(conn, pkt, 0, false) +} + +// icmpLockFreeHandler handles ICMP packets like icmpFilterHandler, but is +// called without the connection being locked and never waits for the lock. +func icmpLockFreeHandler(conn *network.Connection, pkt packet.Packet) { + // Handle packets that do not need to be evaluated. + if verdict, handled := icmpPreFilter(pkt); handled { + issueVerdictLockFree(conn, pkt, verdict, false) + return + } + + // Evaluating the connection changes it and requires the lock. If the + // connection is locked right now, apply the current verdict instead and + // leave the evaluation to a later packet. + state := conn.VerdictState() + needsEvaluation := state.Verdict == network.VerdictUndecided || + state.Verdict == network.VerdictUndeterminable || + (state.Inbound && pkt.IsOutbound()) + if needsEvaluation && conn.TryLock() { + icmpEvaluate(conn, pkt) + conn.Unlock() + } + + issueVerdictLockFree(conn, pkt, 0, false) +} + +// icmpPreFilter handles the ICMP packets that are not subject to the verdict +// of their connection. It does not access the connection. +func icmpPreFilter(pkt packet.Packet) (verdict network.Verdict, handled bool) { // Load packet data. err := pkt.LoadPacketData() if err != nil { log.Tracer(pkt.Ctx()).Debugf("filter: failed to load ICMP packet data: %s", err) - issueVerdict(conn, pkt, network.VerdictDrop, false) - return + return network.VerdictDrop, true } // Submit to ICMP listener. submitted := netenv.SubmitPacketToICMPListener(pkt) if submitted { - issueVerdict(conn, pkt, network.VerdictDrop, false) - return + return network.VerdictDrop, true } // Handle echo request and replies regularly. @@ -786,8 +830,7 @@ func icmpFilterHandler(conn *network.Connection, pkt packet.Packet) { layers.ICMPv4TypeEchoReply: // Continue default: - issueVerdict(conn, pkt, network.VerdictAccept, false) - return + return network.VerdictAccept, true } case *layers.ICMPv6: @@ -797,15 +840,20 @@ func icmpFilterHandler(conn *network.Connection, pkt packet.Packet) { // Continue default: - issueVerdict(conn, pkt, network.VerdictAccept, false) - return + return network.VerdictAccept, true } } + return network.VerdictUndecided, false +} + +// icmpEvaluate decides on ICMP echo connections. +// The caller must hold the lock of the connection. +func icmpEvaluate(conn *network.Connection, pkt packet.Packet) { // Check if we already have a verdict. switch conn.Verdict { //nolint:exhaustive case network.VerdictUndecided, network.VerdictUndeterminable: - // Apply privacy filter and check tunneling. + // Apply privacy filter and check split tunneling. FilterConnection(pkt.Ctx(), conn, pkt, true, false) // Save and propagate changes. @@ -817,21 +865,17 @@ func icmpFilterHandler(conn *network.Connection, pkt packet.Packet) { // Change direction from inbound to outbound on first outbound ICMP packet. conn.Inbound = false - // Apply privacy filter and check tunneling. + // Apply privacy filter and check split tunneling. FilterConnection(pkt.Ctx(), conn, pkt, true, false) // Save and propagate changes. conn.SaveWhenFinished() } - - issueVerdict(conn, pkt, 0, false) } +// issueVerdict applies the verdict of the connection to the packet. +// The caller must hold the lock of the connection. func issueVerdict(conn *network.Connection, pkt packet.Packet, verdict network.Verdict, allowPermanent bool) { - type permanentAcceptFinaler interface { - PermanentAcceptFinal() error - } - // Check if packed was already fast-tracked by the OS integration. if pkt.FastTrackedByIntegration() { return @@ -843,19 +887,51 @@ func issueVerdict(conn *network.Connection, pkt packet.Packet, verdict network.V conn.SaveWhenFinished() } + applyVerdict(pkt, verdict, network.VerdictState{ + Verdict: conn.Verdict, + VerdictPermanent: conn.VerdictPermanent, + Inbound: conn.Inbound, + PID: conn.PID, + }) +} + +// issueVerdictLockFree applies the verdict of the connection to the packet +// without requiring or waiting for the lock of the connection. +func issueVerdictLockFree(conn *network.Connection, pkt packet.Packet, verdict network.Verdict, allowPermanent bool) { + // Check if packed was already fast-tracked by the OS integration. + if pkt.FastTrackedByIntegration() { + return + } + + // Enable permanent verdict. + state := conn.VerdictState() + if allowPermanent && !state.VerdictPermanent && permanentVerdicts() { + state = conn.MakeVerdictPermanentLockFree() + } + + applyVerdict(pkt, verdict, state) +} + +// applyVerdict applies the given verdict to the packet, but at least the +// verdict of the given connection verdict state. +func applyVerdict(pkt packet.Packet, verdict network.Verdict, state network.VerdictState) { + type permanentAcceptFinaler interface { + PermanentAcceptFinal() error + } + // do not allow to circumvent decision: e.g. to ACCEPT packets from a DROP-ed connection - if verdict < conn.Verdict { - verdict = conn.Verdict + if verdict < state.Verdict { + verdict = state.Verdict } var err error switch verdict { case network.VerdictAccept: atomic.AddUint64(packetsAccepted, 1) - if conn.VerdictPermanent { + if state.VerdictPermanent { // Portmaster-owned outbound connections should be finalized to avoid // later third-party OUTPUT rules from overriding the allow decision. - if !conn.Inbound && conn.PID == ownPID { + if !state.Inbound && state.PID == ownPID { if finaler, ok := pkt.(permanentAcceptFinaler); ok { err = finaler.PermanentAcceptFinal() } else { @@ -869,28 +945,27 @@ func issueVerdict(conn *network.Connection, pkt packet.Packet, verdict network.V } case network.VerdictBlock: atomic.AddUint64(packetsBlocked, 1) - if conn.VerdictPermanent { + if state.VerdictPermanent { err = pkt.PermanentBlock() } else { err = pkt.Block() } case network.VerdictDrop: atomic.AddUint64(packetsDropped, 1) - if conn.VerdictPermanent { + if state.VerdictPermanent { err = pkt.PermanentDrop() } else { err = pkt.Drop() } case network.VerdictRerouteToNameserver: err = pkt.RerouteToNameserver() - case network.VerdictRerouteToTunnel: - err = pkt.RerouteToTunnel() case network.VerdictRerouteToSplitTun: err = pkt.RerouteToSplitTun() case network.VerdictFailed: atomic.AddUint64(packetsFailed, 1) err = pkt.Drop() - case network.VerdictUndecided, network.VerdictUndeterminable: + case network.VerdictUndecided, network.VerdictUndeterminable, + network.VerdictRerouteToTunnel: // SPN tunneling is not available in this build. log.Tracer(pkt.Ctx()).Warningf("filter: tried to apply verdict %s to pkt %s: dropping instead", verdict, pkt) fallthrough default: @@ -903,19 +978,6 @@ func issueVerdict(conn *network.Connection, pkt packet.Packet, verdict network.V } } -// func tunnelHandler(pkt packet.Packet) { -// tunnelInfo := GetTunnelInfo(pkt.Info().Dst) -// if tunnelInfo == nil { -// pkt.Block() -// return -// } -// -// entry.CreateTunnel(pkt, tunnelInfo.Domain, tunnelInfo.RRCache.ExportAllARecords()) -// log.Tracef("filter: rerouting %s to tunnel entry point", pkt) -// pkt.RerouteToTunnel() -// return -// } - func packetHandler(w *mgr.WorkerCtx) error { for { select { @@ -932,6 +994,7 @@ func packetHandler(w *mgr.WorkerCtx) error { } func bandwidthUpdateHandler(w *mgr.WorkerCtx) error { + pending := newPendingBandwidth() for { select { case <-w.Done(): @@ -940,7 +1003,7 @@ func bandwidthUpdateHandler(w *mgr.WorkerCtx) error { if bwUpdate != nil { // DEBUG: // log.Debugf("filter: bandwidth update: %s", bwUpdate) - updateBandwidth(w.Ctx(), bwUpdate) + updateBandwidth(w.Ctx(), pending, bwUpdate, time.Now()) } else { return errors.New("received nil bandwidth update from interception") } @@ -948,46 +1011,28 @@ func bandwidthUpdateHandler(w *mgr.WorkerCtx) error { } } -func updateBandwidth(ctx context.Context, bwUpdate *packet.BandwidthUpdate) { +func updateBandwidth(ctx context.Context, pending *pendingBandwidth, bwUpdate *packet.BandwidthUpdate, now time.Time) { // Check if update makes sense. if bwUpdate.BytesReceived == 0 && bwUpdate.BytesSent == 0 { return } // Get connection. + // Additive updates of unknown connections are held for a short time and + // added to the next update of the connection, as their bytes would be + // lost otherwise. conn, ok := network.GetConnection(bwUpdate.ConnID) + bwUpdate = pending.resolve(bwUpdate, ok, now) if !ok { return } - // Do not wait for connections that are locked. - // TODO: Use atomic operations for updating bandwidth stats. - if !conn.TryLock() { - // DEBUG: - // log.Warningf("filter: failed to lock connection for bandwidth update: %s", conn) + bytesIn, bytesOut, ok := applyBandwidthUpdate(conn, bwUpdate) + if !ok { return } defer conn.Unlock() - bytesIn := bwUpdate.BytesReceived - bytesOut := bwUpdate.BytesSent - - // Update stats according to method. - switch bwUpdate.Method { - case packet.Absolute: - bytesIn = bwUpdate.BytesReceived - conn.BytesReceived - bytesOut = bwUpdate.BytesSent - conn.BytesSent - - conn.BytesReceived = bwUpdate.BytesReceived - conn.BytesSent = bwUpdate.BytesSent - case packet.Additive: - conn.BytesReceived += bwUpdate.BytesReceived - conn.BytesSent += bwUpdate.BytesSent - default: - log.Warningf("filter: unsupported bandwidth update method: %d", bwUpdate.Method) - return - } - // Update bandwidth in the netquery module. if module.instance.NetQuery() != nil && conn.BandwidthEnabled { if err := module.instance.NetQuery().Store.UpdateBandwidth( @@ -1004,6 +1049,62 @@ func updateBandwidth(ctx context.Context, bwUpdate *packet.BandwidthUpdate) { } } +// applyBandwidthUpdate applies the bandwidth update to the connection and +// returns the bytes that were transferred since the last applied update. +// If ok is true, the connection is locked and must be unlocked by the caller. +// +// It does not wait for connections that are locked. Additive updates are then +// kept on the connection and applied with the next update, as their bytes +// would be missing otherwise. Absolute updates are skipped, as the next +// update includes their bytes. +func applyBandwidthUpdate(conn *network.Connection, bwUpdate *packet.BandwidthUpdate) (bytesIn, bytesOut uint64, ok bool) { + switch bwUpdate.Method { + case packet.Absolute, packet.Additive: + default: + log.Warningf("filter: unsupported bandwidth update method: %d", bwUpdate.Method) + return 0, 0, false + } + + if !conn.TryLock() { + if bwUpdate.Method == packet.Additive { + conn.DeferBandwidthUpdate(bwUpdate.BytesReceived, bwUpdate.BytesSent) + } + return 0, 0, false + } + + // Update stats according to method. + switch bwUpdate.Method { + case packet.Absolute: + bytesIn = absoluteBandwidthDelta(conn.BytesReceived, bwUpdate.BytesReceived) + bytesOut = absoluteBandwidthDelta(conn.BytesSent, bwUpdate.BytesSent) + + conn.BytesReceived = bwUpdate.BytesReceived + conn.BytesSent = bwUpdate.BytesSent + case packet.Additive: + // Include the updates that could not be applied before. + deferredIn, deferredOut := conn.TakeDeferredBandwidthUpdate() + bytesIn = bwUpdate.BytesReceived + deferredIn + bytesOut = bwUpdate.BytesSent + deferredOut + + conn.BytesReceived += bytesIn + conn.BytesSent += bytesOut + } + + return bytesIn, bytesOut, true +} + +// absoluteBandwidthDelta returns the bytes transferred between the previous +// and the current value of an absolute byte counter. A counter that went +// backwards was reset, eg. because the OS integration started counting a new +// socket with the same connection ID. It then counted the current value since +// the reset, which becomes the new baseline. +func absoluteBandwidthDelta(previous, current uint64) uint64 { + if current < previous { + return current + } + return current - previous +} + func statLogger(w *mgr.WorkerCtx) error { for { select { diff --git a/service/firewall/packet_handler_test.go b/service/firewall/packet_handler_test.go new file mode 100644 index 000000000..91d85e445 --- /dev/null +++ b/service/firewall/packet_handler_test.go @@ -0,0 +1,238 @@ +package firewall + +import ( + "net" + "testing" + + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/process" +) + +// realTestPacket is a packet that is not info-only, but otherwise behaves like +// an info packet. It is enough for the fast-track checks, which never apply a +// verdict themselves. +type realTestPacket struct { + *packet.InfoPacket +} + +func (pkt realTestPacket) InfoOnly() bool { return false } + +func TestFastTrackedLocalDNSKeepsKnownPID(t *testing.T) { //nolint:paralleltest // Modifies the global nameserver IP matcher. + nameserverIP := net.IPv4(127, 0, 0, 17) + + // Set nameserver IP matcher directly, as SetNameserverIPMatcher can only be called once. + prevMatcher, prevReady := nameserverIPMatcher, nameserverIPMatcherReady.IsSet() + nameserverIPMatcher = func(ip net.IP) bool { return ip.Equal(nameserverIP) } + nameserverIPMatcherReady.Set() + t.Cleanup(func() { + nameserverIPMatcher = prevMatcher + nameserverIPMatcherReady.SetTo(prevReady) + }) + + newDNSPacket := func(srcPort uint16, pid int) packet.Packet { + return realTestPacket{packet.NewInfoPacket(packet.Info{ + Inbound: false, + Version: packet.IPv4, + Protocol: packet.UDP, + Src: net.IPv4(127, 0, 0, 1), + SrcPort: srcPort, + Dst: nameserverIP, + DstPort: 53, + PID: pid, + })} + } + + tests := []struct { + name string + connPID int + pktPID int + wantPID int + wantPermanent bool + }{ + { + // Linux: nfqueue packets carry no PID, the connection got it from an eBPF PID hint. + name: "packet without PID keeps hinted PID", + connPID: 1234, + pktPID: process.UndefinedProcessID, + wantPID: 1234, + wantPermanent: true, + }, + { + // Windows: the kext reports the PID with the packet. + name: "packet PID is applied", + connPID: process.UndefinedProcessID, + pktPID: 4321, + wantPID: 4321, + wantPermanent: true, + }, + { + name: "no PID known at all", + connPID: process.UndefinedProcessID, + pktPID: process.UndefinedProcessID, + wantPID: process.UndefinedProcessID, + wantPermanent: false, + }, + } + + for i, tc := range tests { //nolint:paralleltest // Subtests share the global state modified by the parent test. + t.Run(tc.name, func(t *testing.T) { //nolint:paralleltest // Subtests share the global state modified by the parent test. + pkt := newDNSPacket(uint16(41000+i), tc.pktPID) //nolint:gosec // i is a small test index. + conn := &network.Connection{PID: tc.connPID} + + verdict, permanent := fastTrackedPermit(conn, pkt) + if verdict != network.VerdictAccept { + t.Fatalf("expected local DNS to be fast-track accepted, got %s", verdict) + } + if conn.PID != tc.wantPID { + t.Errorf("expected connection PID %d, got %d", tc.wantPID, conn.PID) + } + if permanent != tc.wantPermanent { + t.Errorf("expected permanent=%v, got %v", tc.wantPermanent, permanent) + } + + // The DNS request connection must be saved for fast DNS request + // attribution whenever the PID is known. + _, saved := network.GetDNSRequestConnection(pkt.Info()) + if wantSaved := tc.wantPID != process.UndefinedProcessID; saved != wantSaved { + t.Errorf("expected dns request connection saved=%v, got %v", wantSaved, saved) + } + }) + } +} + +// TestApplyBandwidthUpdateWhileLocked checks that additive bandwidth updates +// are not lost when the connection is locked while they arrive. +func TestApplyBandwidthUpdateWhileLocked(t *testing.T) { + t.Parallel() + + conn := &network.Connection{} + + // The connection is locked, eg. while it is evaluated. + conn.Lock() + for range 3 { + _, _, ok := applyBandwidthUpdate(conn, &packet.BandwidthUpdate{ + BytesReceived: 100, + BytesSent: 50, + Method: packet.Additive, + }) + if ok { + t.Fatal("update must not be applied to a locked connection") + } + } + conn.Unlock() + + // The next update includes the bytes of the skipped updates. + bytesIn, bytesOut, ok := applyBandwidthUpdate(conn, &packet.BandwidthUpdate{ + BytesReceived: 10, + BytesSent: 5, + Method: packet.Additive, + }) + if !ok { + t.Fatal("update was not applied to an unlocked connection") + } + if bytesIn != 310 || bytesOut != 155 { + t.Errorf("reported %d/%d bytes, want 310/155", bytesIn, bytesOut) + } + if conn.BytesReceived != 310 || conn.BytesSent != 155 { + t.Errorf("connection has %d/%d bytes, want 310/155", conn.BytesReceived, conn.BytesSent) + } + conn.Unlock() + + // Skipped absolute updates are included in the next one anyway. + conn.Lock() + if _, _, ok := applyBandwidthUpdate(conn, &packet.BandwidthUpdate{ + BytesReceived: 1000, + BytesSent: 500, + Method: packet.Absolute, + }); ok { + t.Fatal("update must not be applied to a locked connection") + } + conn.Unlock() + bytesIn, bytesOut, ok = applyBandwidthUpdate(conn, &packet.BandwidthUpdate{ + BytesReceived: 2000, + BytesSent: 1000, + Method: packet.Absolute, + }) + if !ok { + t.Fatal("update was not applied to an unlocked connection") + } + if bytesIn != 1690 || bytesOut != 845 { + t.Errorf("reported %d/%d bytes, want 1690/845", bytesIn, bytesOut) + } + if conn.BytesReceived != 2000 || conn.BytesSent != 1000 { + t.Errorf("connection has %d/%d bytes, want 2000/1000", conn.BytesReceived, conn.BytesSent) + } + conn.Unlock() +} + +// TestResetSingleConnectionVerdictSkipsIncomplete checks that a connection +// whose data is not yet complete is not re-evaluated after a re-attribution +// event, as it has no process, entity or profile yet. Its verdict is decided +// by its firewall handler once its data is complete. +func TestResetSingleConnectionVerdictSkipsIncomplete(t *testing.T) { + t.Parallel() + + conn := network.NewIncompleteConnection(realTestPacket{packet.NewInfoPacket(packet.Info{ + Inbound: false, + Version: packet.IPv4, + Protocol: packet.TCP, + Src: net.IPv4(127, 0, 0, 1), + SrcPort: 42017, + Dst: net.IPv4(192, 0, 2, 17), + DstPort: 443, + })}) + + // Connection IDs are reused, so the connection the re-attribution event + // refers to may have been replaced by a new, incomplete one. + resetSingleConnectionVerdict(conn.ID) + + conn.Lock() + defer conn.Unlock() + if conn.DataIsComplete() { + t.Error("connection must stay incomplete") + } + if conn.Verdict != network.VerdictUndecided { + t.Errorf("verdict of incomplete connection changed to %s", conn.VerdictVerb()) + } +} + +// TestApplyBandwidthUpdateCounterReset checks that an absolute bandwidth update +// with lower counters than the connection has does not underflow, but is +// treated as a reset counter. +func TestApplyBandwidthUpdateCounterReset(t *testing.T) { + t.Parallel() + + conn := &network.Connection{} + apply := func(received, sent uint64) (bytesIn, bytesOut uint64) { + t.Helper() + + bytesIn, bytesOut, ok := applyBandwidthUpdate(conn, &packet.BandwidthUpdate{ + BytesReceived: received, + BytesSent: sent, + Method: packet.Absolute, + }) + if !ok { + t.Fatal("update was not applied to an unlocked connection") + } + conn.Unlock() + return bytesIn, bytesOut + } + + if bytesIn, bytesOut := apply(1000, 500); bytesIn != 1000 || bytesOut != 500 { + t.Errorf("reported %d/%d bytes, want 1000/500", bytesIn, bytesOut) + } + + // The received counter was reset and counted 100 bytes since then. + if bytesIn, bytesOut := apply(100, 600); bytesIn != 100 || bytesOut != 100 { + t.Errorf("reported %d/%d bytes after counter reset, want 100/100", bytesIn, bytesOut) + } + if conn.BytesReceived != 100 || conn.BytesSent != 600 { + t.Errorf("connection has %d/%d bytes, want 100/600", conn.BytesReceived, conn.BytesSent) + } + + // The reset counter is the new baseline. + if bytesIn, bytesOut := apply(150, 600); bytesIn != 50 || bytesOut != 0 { + t.Errorf("reported %d/%d bytes, want 50/0", bytesIn, bytesOut) + } +} diff --git a/service/firewall/preauth.go b/service/firewall/preauth.go index 974d2fd14..d1235c374 100644 --- a/service/firewall/preauth.go +++ b/service/firewall/preauth.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/safing/portmaster/base/log" + "github.com/safing/portmaster/service/firewall/interception" "github.com/safing/portmaster/service/netenv" "github.com/safing/portmaster/service/network" "github.com/safing/portmaster/service/network/packet" @@ -21,8 +22,9 @@ var ( func init() { resolver.SetLocalAddrFactory(PermittedAddr) resolver.SetLocalPortHooks(resolver.LocalPortHooks{ - Authorize: authorizeLocalPort, - Release: releaseLocalPort, + Authorize: authorizeLocalPort, + Release: releaseLocalPort, + ClearUDPFlow: clearUDPFlow, }) netenv.SetLocalAddrFactory(PermittedAddr) netenv.SetLocalPortReleaser(releaseLocalPort) @@ -116,6 +118,27 @@ func releaseLocalPort(netw string, port uint16, unusable bool) { } } +// clearUDPFlow drops OS state of an earlier flow with the same addresses as a +// new UDP socket of Portmaster. On Linux, the conntrack entry of an +// application's DNS query that was redirected to the Portmaster nameserver +// outlives the application's socket. If the OS then gives the same port to a +// Portmaster query to the same server, that entry redirects it to Portmaster +// itself and the query times out. +func clearUDPFlow(local, remote *net.UDPAddr) { + // Portmaster may still track the earlier flow, with its verdict. + network.EndConnectionForReusedTuple(packet.CreateConnectionID( + packet.UDP, local.IP, uint16(local.Port), remote.IP, uint16(remote.Port), false, //nolint:gosec // Ports of net.Addr are within the uint16 range. + )) + + cleared, err := interception.ClearFlow(uint8(packet.UDP), local.IP, uint16(local.Port), remote.IP, uint16(remote.Port)) //nolint:gosec // Ports of net.Addr are within the uint16 range. + switch { + case err != nil: + log.Debugf("filter: failed to clear earlier flow %s -> %s: %s", local, remote, err) + case cleared: + log.Debugf("filter: cleared earlier flow %s -> %s for a new socket", local, remote) + } +} + func protocolFromNetwork(netw string) (packet.IPProtocol, bool) { switch netw { case "udp": diff --git a/service/firewall/tunnel.go b/service/firewall/tunnel.go deleted file mode 100644 index f975a2b97..000000000 --- a/service/firewall/tunnel.go +++ /dev/null @@ -1,215 +0,0 @@ -package firewall - -import ( - "context" - "errors" - - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/service/intel" - "github.com/safing/portmaster/service/netenv" - "github.com/safing/portmaster/service/network" - "github.com/safing/portmaster/service/network/packet" - "github.com/safing/portmaster/service/process" - "github.com/safing/portmaster/service/profile" - "github.com/safing/portmaster/service/profile/endpoints" - "github.com/safing/portmaster/service/resolver" - "github.com/safing/portmaster/spn/captain" - "github.com/safing/portmaster/spn/crew" - "github.com/safing/portmaster/spn/navigator" - "github.com/safing/portmaster/spn/sluice" -) - -func checkTunneling(ctx context.Context, conn *network.Connection) { - // Check if the connection should be tunneled at all. - switch { - case !tunnelEnabled(): - // Tunneling is disabled. - return - case !conn.Entity.IPScope.IsGlobal(): - // Can't tunnel Local/LAN connections. - return - case conn.Inbound: - // Can't tunnel incoming connections. - return - case conn.Verdict != network.VerdictAccept: - // Connection will be blocked. - return - case conn.IPProtocol != packet.TCP && conn.IPProtocol != packet.UDP: - // Unsupported protocol. - return - case conn.Process().Pid == ownPID: - // Bypass tunneling for certain own connections. - switch { - case !captain.ClientReady(): - return - case captain.IsExcepted(conn.Entity.IP): - return - } - } - - // Check more extensively for Local/LAN connections. - localNet, err := netenv.GetLocalNetwork(conn.Entity.IP) - if err != nil { - log.Warningf("firewall: failed to check if %s is in my net: %s", conn.Entity.IP, err) - } else if localNet != nil { - // With IPv6, just checking the IP scope is not enough, as the host very - // likely has a public IPv6 address. - // Don't tunnel LAN connections. - - // TODO: We currently don't check the full LAN scope, but only the - // broadcast domain of the host - ie. the networks that the host is - // directly attached to. - return - } - - // Get profile. - layeredProfile := conn.Process().Profile() - if layeredProfile == nil { - conn.Failed("no profile set", "") - return - } - - // Update profile. - if layeredProfile.NeedsUpdate() { - // Update revision counter in connection. - conn.ProfileRevisionCounter = layeredProfile.Update( - conn.Process().MatchingData(), - conn.Process().CreateProfileCallback, - ) - conn.SaveWhenFinished() - } else { - // Check if the revision counter of the connection needs updating. - revCnt := layeredProfile.RevisionCnt() - if conn.ProfileRevisionCounter != revCnt { - conn.ProfileRevisionCounter = revCnt - conn.SaveWhenFinished() - } - } - - // Check if tunneling is enabled for this app at all. - if !layeredProfile.UseSPN() { - return - } - - // Check if tunneling is enabled for entity. - conn.Entity.FetchData(ctx) - result, _ := layeredProfile.MatchSPNUsagePolicy(ctx, conn.Entity) - switch result { - case endpoints.MatchError: - conn.Failed("failed to check SPN rules", profile.CfgOptionSPNUsagePolicyKey) - return - case endpoints.Denied: - return - case endpoints.Permitted, endpoints.NoMatch: - // Continue - } - - // Tunnel all the things! - conn.SaveWhenFinished() - - // Check if ready. - if !captain.ClientReady() { - // Block connection as SPN is not ready yet. - log.Tracer(ctx).Trace("SPN not ready for tunneling") - conn.Failed("SPN not ready for tunneling", "") - return - } - - conn.SetVerdictDirectly(network.VerdictRerouteToTunnel) - conn.Tunneled = true -} - -func requestTunneling(ctx context.Context, conn *network.Connection) error { - // Get profile. - layeredProfile := conn.Process().Profile() - if layeredProfile == nil { - return errors.New("no profile set") - } - - // Get tunnel options. - conn.TunnelOpts = DeriveTunnelOptions(layeredProfile, conn.Process(), conn.Entity, conn.Encrypted) - - // Queue request in sluice. - err := sluice.AwaitRequest(conn, crew.HandleSluiceRequest) - if err != nil { - return err - } - - log.Tracer(ctx).Trace("filter: tunneling requested") - return nil -} - -func init() { - navigator.DeriveTunnelOptions = func(lp *profile.LayeredProfile, destination *intel.Entity, connEncrypted bool) *navigator.Options { - return DeriveTunnelOptions(lp, nil, destination, connEncrypted) - } -} - -// DeriveTunnelOptions derives and returns the tunnel options from the connection and profile. -func DeriveTunnelOptions(lp *profile.LayeredProfile, proc *process.Process, destination *intel.Entity, connEncrypted bool) *navigator.Options { - // Set options. - tunnelOpts := &navigator.Options{ - Transit: &navigator.TransitHubOptions{ - HubPolicies: lp.StackedTransitHubPolicies(), - }, - Destination: &navigator.DestinationHubOptions{ - HubPolicies: lp.StackedExitHubPolicies(), - CheckHubPolicyWith: destination, - }, - RoutingProfile: lp.SPNRoutingAlgorithm(), - } - if !connEncrypted { - tunnelOpts.Destination.Regard = tunnelOpts.Destination.Regard.Add(navigator.StateTrusted) - // TODO: Add this when all Hubs are on v0.6.21+ - // tunnelOpts.Destination.Regard = tunnelOpts.Destination.Regard.Add(navigator.StateAllowUnencrypted) - } - - // Add required verified owners if community nodes should not be used. - if !useCommunityNodes() { - tunnelOpts.Transit.RequireVerifiedOwners = captain.NonCommunityVerifiedOwners - tunnelOpts.Destination.RequireVerifiedOwners = captain.NonCommunityVerifiedOwners - } - - // Get routing profile for checking for upgrades. - routingProfile := navigator.GetRoutingProfile(tunnelOpts.RoutingProfile) - - // If we have any exit hub policies, we must be able to hop in order to follow the policy. - // Switch to single-hop routing to allow for routing with hub selection. - if routingProfile.MaxHops <= 1 && navigator.HubPoliciesAreSet(tunnelOpts.Destination.HubPolicies) { - tunnelOpts.RoutingProfile = navigator.RoutingProfileSingleHopID - } - - // If the current home node is not trusted, then upgrade at least to two hops. - if routingProfile.MinHops < 2 { - homeNode, _ := navigator.Main.GetHome() - if homeNode != nil && !homeNode.State.Has(navigator.StateTrusted) { - tunnelOpts.RoutingProfile = navigator.RoutingProfileDoubleHopID - } - } - - // Special handling for the internal DNS resolver. - if proc != nil && proc.Pid == ownPID && resolver.IsResolverAddress(destination.IP, destination.Port) { - dnsExitHubPolicy, err := captain.GetDNSExitHubPolicy() - if err != nil { - log.Errorf("firewall: failed to get dns exit hub policy: %s", err) - } - - if err == nil && dnsExitHubPolicy.IsSet() { - // Apply the dns exit hub policy, if set. - tunnelOpts.Destination.HubPolicies = []endpoints.Endpoints{dnsExitHubPolicy} - // Use the routing algorithm from the profile, as the home profile won't work with the policy. - tunnelOpts.RoutingProfile = lp.SPNRoutingAlgorithm() - // Raise the routing algorithm at least to single-hop. - if tunnelOpts.RoutingProfile == navigator.RoutingProfileHomeID { - tunnelOpts.RoutingProfile = navigator.RoutingProfileSingleHopID - } - } else { - // Disable any policies for the internal DNS resolver. - tunnelOpts.Destination.HubPolicies = nil - // Always use the home routing profile for the internal DNS resolver. - tunnelOpts.RoutingProfile = navigator.RoutingProfileHomeID - } - } - - return tunnelOpts -} diff --git a/service/instance.go b/service/instance.go index fead7e7b1..274eacddc 100644 --- a/service/instance.go +++ b/service/instance.go @@ -40,20 +40,10 @@ import ( "github.com/safing/portmaster/service/sync" "github.com/safing/portmaster/service/ui" "github.com/safing/portmaster/service/updates" - "github.com/safing/portmaster/spn/access" - "github.com/safing/portmaster/spn/cabin" - "github.com/safing/portmaster/spn/captain" - "github.com/safing/portmaster/spn/crew" - "github.com/safing/portmaster/spn/docks" - "github.com/safing/portmaster/spn/hub" - "github.com/safing/portmaster/spn/navigator" - "github.com/safing/portmaster/spn/patrol" - "github.com/safing/portmaster/spn/ships" - "github.com/safing/portmaster/spn/sluice" - "github.com/safing/portmaster/spn/terminal" ) // Instance is an instance of a Portmaster service. +// SPN and account access modules have been removed. type Instance struct { ctx context.Context cancelCtx context.CancelFunc @@ -106,20 +96,6 @@ type Instance struct { splittun *splittun.SplitTunModule - access *access.Access - - // SPN modules - SpnGroup *mgr.ExtendedGroup - cabin *cabin.Cabin - navigator *navigator.Navigator - captain *captain.Captain - crew *crew.Crew - docks *docks.Docks - patrol *patrol.Patrol - ships *ships.Ships - sluice *sluice.SluiceModule - terminal *terminal.TerminalModule - CommandLineOperation func() error ShouldRestart bool } @@ -246,7 +222,6 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx if err != nil { return instance, fmt.Errorf("create customlist module: %w", err) } - instance.status, err = status.New(instance) if err != nil { return instance, fmt.Errorf("create status module: %w", err) @@ -283,54 +258,11 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx if err != nil { return instance, fmt.Errorf("create interop module: %w", err) } - instance.access, err = access.New(instance) - if err != nil { - return instance, fmt.Errorf("create access module: %w", err) - } - instance.splittun, err = splittun.New(instance) if err != nil { return instance, fmt.Errorf("create splittun module: %w", err) } - // SPN modules - instance.cabin, err = cabin.New(instance) - if err != nil { - return instance, fmt.Errorf("create cabin module: %w", err) - } - instance.navigator, err = navigator.New(instance) - if err != nil { - return instance, fmt.Errorf("create navigator module: %w", err) - } - instance.captain, err = captain.New(instance) - if err != nil { - return instance, fmt.Errorf("create captain module: %w", err) - } - instance.crew, err = crew.New(instance) - if err != nil { - return instance, fmt.Errorf("create crew module: %w", err) - } - instance.docks, err = docks.New(instance) - if err != nil { - return instance, fmt.Errorf("create docks module: %w", err) - } - instance.patrol, err = patrol.New(instance) - if err != nil { - return instance, fmt.Errorf("create patrol module: %w", err) - } - instance.ships, err = ships.New(instance) - if err != nil { - return instance, fmt.Errorf("create ships module: %w", err) - } - instance.sluice, err = sluice.New(instance) - if err != nil { - return instance, fmt.Errorf("create sluice module: %w", err) - } - instance.terminal, err = terminal.New(instance) - if err != nil { - return instance, fmt.Errorf("create terminal module: %w", err) - } - // Grouped interception modules that can be paused/resumed together. instance.serviceGroupInterception = mgr.NewGroupModule("Interception Group", instance.interception, @@ -367,7 +299,7 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx instance.splittun, - instance.interop, // required to start before interception + instance.interop, // Grouped pausable interception modules: // instance.interception, @@ -380,21 +312,6 @@ func New(svcCfg *ServiceConfig) (*Instance, error) { //nolint:maintidx instance.sync, instance.ui, instance.control, - - instance.access, - ) - - // SPN Group - instance.SpnGroup = mgr.NewExtendedGroup( - instance.cabin, - instance.navigator, - instance.captain, - instance.crew, - instance.docks, - instance.patrol, - instance.ships, - instance.sluice, - instance.terminal, ) return instance, nil @@ -412,21 +329,14 @@ func (i *Instance) SetSleep(enabled bool) { sm.SetSleep(enabled) } } - for _, module := range i.SpnGroup.Modules() { - if sm, ok := module.(SleepyModule); ok { - sm.SetSleep(enabled) - } - } } // BinDir returns the directory for binaries. -// This directory may be read-only. func (i *Instance) BinDir() string { return i.binDir } // DataDir returns the directory for variable data. -// This directory is expected to be read/writeable. func (i *Instance) DataDir() string { return i.dataDir } @@ -510,56 +420,6 @@ func (i *Instance) NetEnv() *netenv.NetEnv { return i.netenv } -// Access returns the access module. -func (i *Instance) Access() *access.Access { - return i.access -} - -// Cabin returns the cabin module. -func (i *Instance) Cabin() *cabin.Cabin { - return i.cabin -} - -// Captain returns the captain module. -func (i *Instance) Captain() *captain.Captain { - return i.captain -} - -// Crew returns the crew module. -func (i *Instance) Crew() *crew.Crew { - return i.crew -} - -// Docks returns the crew module. -func (i *Instance) Docks() *docks.Docks { - return i.docks -} - -// Navigator returns the navigator module. -func (i *Instance) Navigator() *navigator.Navigator { - return i.navigator -} - -// Patrol returns the patrol module. -func (i *Instance) Patrol() *patrol.Patrol { - return i.patrol -} - -// Ships returns the ships module. -func (i *Instance) Ships() *ships.Ships { - return i.ships -} - -// Sluice returns the ships module. -func (i *Instance) Sluice() *sluice.SluiceModule { - return i.sluice -} - -// Terminal returns the terminal module. -func (i *Instance) Terminal() *terminal.TerminalModule { - return i.terminal -} - // UI returns the ui module. func (i *Instance) UI() *ui.UI { return i.ui @@ -650,46 +510,21 @@ func (i *Instance) Core() *core.Core { return i.core } -// SPNGroup returns the group of all SPN modules. -func (i *Instance) SPNGroup() *mgr.ExtendedGroup { - return i.SpnGroup -} - -// Events - -// GetEventSPNConnected return the event manager for the SPN connected event. -func (i *Instance) GetEventSPNConnected() *mgr.EventMgr[struct{}] { - return i.captain.EventSPNConnected -} - -func (i *Instance) GetHookSPNConnecting() *mgr.HookMgr[hub.Announcement] { - return i.captain.HookSPNConnecting -} - // Special functions -// SetCmdLineOperation sets a command line operation to be executed instead of starting the system. This is useful when functions need all modules to be prepared for a special operation. +// SetCmdLineOperation sets a command line operation to be executed instead of starting the system. func (i *Instance) SetCmdLineOperation(f func() error) { i.CommandLineOperation = f } // GetStates returns the current states of all group modules. func (i *Instance) GetStates() []mgr.StateUpdate { - mainStates := i.serviceGroup.GetStates() - spnStates := i.SpnGroup.GetStates() - - updates := make([]mgr.StateUpdate, 0, len(mainStates)+len(spnStates)) - updates = append(updates, mainStates...) - updates = append(updates, spnStates...) - - return updates + return i.serviceGroup.GetStates() } -// AddStatesCallback adds the given callback function to all group modules that -// expose a state manager at States(). +// AddStatesCallback adds the given callback function to all group modules. func (i *Instance) AddStatesCallback(callbackName string, callback mgr.EventCallbackFunc[mgr.StateUpdate]) { i.serviceGroup.AddStatesCallback(callbackName, callback) - i.SpnGroup.AddStatesCallback(callbackName, callback) } // Ready returns whether all modules in the main service module group have been started and are still running. @@ -707,58 +542,41 @@ func (i *Instance) Stop() error { return i.serviceGroup.Stop() } -// RestartExitCode will instruct portmaster-start to restart the process immediately, potentially with a new version. +// RestartExitCode will instruct portmaster-start to restart the process immediately. const RestartExitCode = 23 // Restart asynchronously restarts the instance. -// This only works if the underlying system/process supports this. func (i *Instance) Restart() { - // Send a restart event, give it 10ms extra to propagate. i.core.EventRestart.Submit(struct{}{}) time.Sleep(10 * time.Millisecond) - - // Set the restart flag and shutdown. i.ShouldRestart = true i.shutdown(RestartExitCode) } // Shutdown asynchronously stops the instance. func (i *Instance) Shutdown() { - // Send a shutdown event, give it 10ms extra to propagate. i.core.EventShutdown.Submit(struct{}{}) time.Sleep(10 * time.Millisecond) - i.shutdown(0) } func (i *Instance) shutdown(exitCode int) { - // Only shutdown once. if i.IsShuttingDown() { return } - - // Cancel main context. i.cancelCtx() - - // Set given exit code. i.exitCode.Store(int32(exitCode)) - - // Start shutdown asynchronously in a separate manager. m := mgr.New("instance") m.Go("shutdown", func(w *mgr.WorkerCtx) error { - // Stop all modules. if err := i.Stop(); err != nil { w.Error("failed to shutdown", "err", err) } - - // Cancel shutdown process context. i.cancelShutdownCtx() return nil }) } // Ctx returns the instance context. -// It is canceled when shutdown is started. func (i *Instance) Ctx() context.Context { return i.ctx } @@ -774,7 +592,6 @@ func (i *Instance) ShuttingDown() <-chan struct{} { } // ShutdownCtx returns the instance shutdown context. -// It is canceled when shutdown is complete. func (i *Instance) ShutdownCtx() context.Context { return i.shutdownCtx } @@ -784,7 +601,7 @@ func (i *Instance) IsShutDown() bool { return i.shutdownCtx.Err() != nil } -// ShutDownComplete returns a channel that is triggered when the instance has shut down. +// ShutdownComplete returns a channel that is triggered when the instance has shut down. func (i *Instance) ShutdownComplete() <-chan struct{} { return i.shutdownCtx.Done() } diff --git a/service/integration/integration_windows.go b/service/integration/integration_windows.go index b049638dc..4d848c566 100644 --- a/service/integration/integration_windows.go +++ b/service/integration/integration_windows.go @@ -60,10 +60,15 @@ func (i *OSIntegration) loadDLL() error { } // Enumerate all needed dll functions. - i.os.etwFunctions, err = initializeETW(i.os.dll) + // Only publish the functions if all of them were found: on error, + // initializeETW returns a partially filled struct with nil procs, which + // would make GetETWInterface return a non-nil interface that panics when + // a missing function is called. + etwFunctions, err := initializeETW(i.os.dll) if err != nil { return err } + i.os.etwFunctions = etwFunctions // Notify listeners i.OnInitializedEvent.Submit(struct{}{}) diff --git a/service/intel/customlists/module.go b/service/intel/customlists/module.go index 915f055ef..bfaee8a37 100644 --- a/service/intel/customlists/module.go +++ b/service/intel/customlists/module.go @@ -184,14 +184,48 @@ func LookupCountry(countryCode string) bool { return ok } +// splitDomain returns the domain and all its parent domains up to, but +// excluding, the public suffix. Every result is fully qualified (ends with a dot). func splitDomain(domain string) []string { - domain = strings.Trim(domain, ".") - suffix, _ := publicsuffix.PublicSuffix(domain) - if suffix == domain { - return []string{domain} + d := strings.Trim(domain, ".") + suffix, _ := publicsuffix.PublicSuffix(d) + if suffix == d { + return []string{d} } - domainWithoutSuffix := domain[:len(domain)-len(suffix)] + // All domains to return are a suffix of the fully qualified domain, if + // the labels before the public suffix are well-formed: Slice them from + // the domain instead of joining the labels again. + // This is called for every domain and CNAME of every new connection. + subdomains := d[:len(d)-len(suffix)] + if !strings.HasSuffix(d, suffix) || + !strings.HasSuffix(subdomains, ".") || + strings.HasPrefix(subdomains, ".") || + strings.Contains(subdomains, "..") { + return splitIrregularDomain(d, suffix) + } + + fqdn := domain + if len(fqdn) != len(d)+1 || !strings.HasPrefix(fqdn, d) || fqdn[len(d)] != '.' { + fqdn = d + "." + } + + domains := make([]string, 0, strings.Count(subdomains, ".")) + start := 0 + for i := range len(subdomains) { + if subdomains[i] == '.' { + domains = append(domains, fqdn[start:]) + start = i + 1 + } + } + return domains +} + +// splitIrregularDomain is the general implementation of splitDomain, which +// also handles domains with empty labels. d is the domain without leading and +// trailing dots. +func splitIrregularDomain(d, suffix string) []string { + domainWithoutSuffix := d[:len(d)-len(suffix)] domainWithoutSuffix = strings.Trim(domainWithoutSuffix, ".") splitted := strings.FieldsFunc(domainWithoutSuffix, func(r rune) bool { @@ -200,7 +234,6 @@ func splitDomain(domain string) []string { domains := make([]string, 0, len(splitted)) for idx := range splitted { - d := strings.Join(splitted[idx:], ".") + "." + suffix if d[len(d)-1] != '.' { d += "." diff --git a/service/intel/customlists/splitdomain_test.go b/service/intel/customlists/splitdomain_test.go new file mode 100644 index 000000000..95ea93450 --- /dev/null +++ b/service/intel/customlists/splitdomain_test.go @@ -0,0 +1,112 @@ +package customlists + +import ( + "math/rand" + "reflect" + "strings" + "testing" + + "golang.org/x/net/publicsuffix" +) + +// splitDomainReference is the previous implementation of splitDomain. +func splitDomainReference(domain string) []string { + domain = strings.Trim(domain, ".") + suffix, _ := publicsuffix.PublicSuffix(domain) + if suffix == domain { + return []string{domain} + } + + domainWithoutSuffix := domain[:len(domain)-len(suffix)] + domainWithoutSuffix = strings.Trim(domainWithoutSuffix, ".") + + splitted := strings.FieldsFunc(domainWithoutSuffix, func(r rune) bool { + return r == '.' + }) + + domains := make([]string, 0, len(splitted)) + for idx := range splitted { + + d := strings.Join(splitted[idx:], ".") + "." + suffix + if d[len(d)-1] != '.' { + d += "." + } + domains = append(domains, d) + } + return domains +} + +func checkSplitDomain(t *testing.T, domain string) { + t.Helper() + want := splitDomainReference(domain) + got := splitDomain(domain) + if !reflect.DeepEqual(want, got) { + t.Fatalf("splitDomain(%q) = %q, want %q", domain, got, want) + } +} + +var splitDomainTable = []string{ + "", ".", "..", "...", "com", "com.", ".com", ".com.", "co.uk", "github.io", "foo.github.io", + "example.com", "example.com.", ".example.com", "..example.com..", "www.example.com", + "a.b.c.d.e.example.com.", "a.b.co.uk", "a.b.co.uk.", "a..b.com", "a..b.com.", "a.b..com", + "a.com..", "..a.com", "A.B.COM", "Foo.GitHub.IO", "xn--bcher-kva.example", "www.xn--bcher-kva.de", + "foo.unknowntld", "a.b.unknowntld.", "localhost", "a.localhost", "x.y.z.s3.amazonaws.com", + "foo.bar.blogspot.com", "a.b.kobe.jp", "city.kobe.jp", "a.ck", "www.ck", "1.2.3.4", "a. b.com", + "a.b.com.\t", "e\u00e9.com", "a.b.\u30b3\u30e0", +} + +func TestSplitDomainMatchesReference(t *testing.T) { + t.Parallel() + for _, domain := range splitDomainTable { + checkSplitDomain(t, domain) + } +} + +func TestSplitDomainMatchesReferenceRandom(t *testing.T) { + t.Parallel() + labels := []string{ + "a", "b", "www", "example", "foo", "bar", "A", "XN--bcher-kva", "xn--p1ai", "com", "org", "uk", "co", + "github", "io", "blogspot", "amazonaws", "s3", "jp", "kobe", "ck", "unknowntld", "localhost", "", "-", "1", + } + rng := rand.New(rand.NewSource(42)) //nolint:gosec // Deterministic test data. + for range 100000 { + var sb strings.Builder + for range rng.Intn(3) { + if rng.Intn(4) == 0 { + sb.WriteByte('.') + } + } + n := rng.Intn(7) + for i := range n { + if i > 0 { + sb.WriteByte('.') + if rng.Intn(15) == 0 { + sb.WriteByte('.') + } + } + sb.WriteString(labels[rng.Intn(len(labels))]) + } + for range rng.Intn(3) { + if rng.Intn(3) == 0 { + sb.WriteByte('.') + } + } + checkSplitDomain(t, sb.String()) + } +} + +var splitDomainBenchDomains = []string{"www.example.com.", "a.b.c.example.co.uk.", "foo.github.io."} + +func BenchmarkSplitDomain(b *testing.B) { + b.ReportAllocs() + for i := range b.N { + _ = splitDomain(splitDomainBenchDomains[i%len(splitDomainBenchDomains)]) + } +} + +func BenchmarkSplitDomainReference(b *testing.B) { + b.ReportAllocs() + for i := range b.N { + _ = splitDomainReference(splitDomainBenchDomains[i%len(splitDomainBenchDomains)]) + } +} diff --git a/service/intel/entity.go b/service/intel/entity.go index 673eb806a..08ef8f638 100644 --- a/service/intel/entity.go +++ b/service/intel/entity.go @@ -2,8 +2,9 @@ package intel import ( "context" + "errors" "net" - "sort" + "slices" "strconv" "strings" "sync" @@ -21,7 +22,7 @@ import ( // functions performs locking. The caller MUST ENSURE // proper locking and synchronization when accessing // any properties of Entity. -type Entity struct { //nolint:maligned +type Entity struct { sync.Mutex // lists exist for most entity information and @@ -33,6 +34,7 @@ type Entity struct { //nolint:maligned reverseResolveEnabled bool resolveSubDomainLists bool checkCNAMEs bool + publicSuffixICANN bool // See publicSuffix. // IP is the IP address of the connection. If domain is // set, IP has been resolved by following all CNAMEs. @@ -96,6 +98,13 @@ type Entity struct { //nolint:maligned // ListsError holds an error message if fetching the lists failed. ListsError string + // publicSuffix and publicSuffixICANN hold the result of + // publicsuffix.PublicSuffix(publicSuffixOf), if publicSuffix is set. The + // public suffix of the domain is needed for the lists and the domain + // heuristics. The domain may change, see getPublicSuffix. + publicSuffixOf string + publicSuffix string + // we only load each data above at most once fetchLocationOnce sync.Once reverseResolveOnce sync.Once @@ -236,6 +245,28 @@ func (e *Entity) GetDomain(ctx context.Context, mayUseReverseDomain bool) (strin return e.Domain, true } +// EffectiveTLDPlusOne returns publicsuffix.EffectiveTLDPlusOne of the domain +// of the entity without the trailing dots, and whether it is valid. The public +// suffix of the domain is looked up only once for the lists and this. +func (e *Entity) EffectiveTLDPlusOne() (string, bool) { + // Same as publicsuffix.EffectiveTLDPlusOne, which returns an error instead + // of false. + domain := strings.TrimRight(e.Domain, ".") + if strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") || strings.Contains(domain, "..") { + return "", false + } + + suffix, _ := e.getPublicSuffix(domain) + if len(domain) <= len(suffix) { + return "", false + } + i := len(domain) - len(suffix) - 1 + if domain[i] != '.' { + return "", false + } + return domain[1+strings.LastIndexByte(domain[:i], '.'):], true +} + // GetIP returns the IP and whether it is set. func (e *Entity) GetIP() (net.IP, bool) { if e.IP == nil { @@ -256,7 +287,12 @@ func (e *Entity) getLocation(ctx context.Context) { // get location data loc, err := geoip.GetLocation(e.IP) if err != nil { - log.Tracer(ctx).Warningf("intel: failed to get location data for %s: %s", e.IP, err) + if errors.Is(err, geoip.ErrDatabaseNotAvailable) { + // No intel data downloaded yet: true for every connection. + log.Tracer(ctx).Debugf("intel: no location data for %s: %s", e.IP, err) + } else { + log.Tracer(ctx).Warningf("intel: failed to get location data for %s: %s", e.IP, err) + } e.LocationError = err.Error() return } @@ -314,11 +350,14 @@ func (e *Entity) GetCountry(ctx context.Context) (string, bool) { return e.Country, true } -// GetCountryInfo returns the two letter ISO country code and whether it is set. +// GetCountryInfo returns the country information of the entity's location. +// It returns nil if the location could not be determined, ie. if there was a +// location lookup error or if no location is available, eg. for non-global IPs. func (e *Entity) GetCountryInfo(ctx context.Context) *geoip.CountryInfo { e.getLocation(ctx) - if e.LocationError != "" { + // The location is also unset without an error, eg. for non-global IPs. + if e.LocationError != "" || e.location == nil { return nil } return &e.location.Country @@ -366,24 +405,14 @@ func (e *Entity) getDomainLists(ctx context.Context) { } e.loadDomainListOnce.Do(func() { - domainsToInspect := []string{domain} - if e.checkCNAMEs && len(e.CNAME) > 0 { log.Tracer(ctx).Tracef("intel: CNAME filtering enabled, checking %v too", e.CNAME) - domainsToInspect = append(domainsToInspect, e.CNAME...) - } - - var domains []string - if e.resolveSubDomainLists { - for _, domain := range domainsToInspect { - subdomains := splitDomain(domain) - domains = append(domains, subdomains...) - } - } else { - domains = domainsToInspect } - domains = makeDistinct(domains) + // Collect the domains to look up in a buffer on the stack: A domain + // and its CNAMEs usually have only a few parent domains. + var domainsBuf [16]string + domains := makeDistinct(e.appendListDomains(domainsBuf[:0], domain)) for _, d := range domains { list, err := filterlists.LookupDomain(d) @@ -402,14 +431,75 @@ func (e *Entity) getDomainLists(ctx context.Context) { }) } +// splitDomain returns the domain and all its parent domains up to, but +// excluding, the public suffix. A public suffix that is not an ICANN TLD is +// included. func splitDomain(domain string) []string { + return appendSplitDomain(nil, domain) +} + +// appendSplitDomain appends the result of splitDomain to dst. +func appendSplitDomain(dst []string, domain string) []string { // Get suffix. d := strings.TrimSuffix(domain, ".") suffix, icann := publicsuffix.PublicSuffix(d) + return appendSplitDomainWithSuffix(dst, domain, d, suffix, icann) +} + +// splitDomainWithSuffix is splitDomain with the domain without the trailing +// dot d and the result of publicsuffix.PublicSuffix(d). +func splitDomainWithSuffix(domain, d, suffix string, icann bool) []string { + return appendSplitDomainWithSuffix(nil, domain, d, suffix, icann) +} + +// appendSplitDomainWithSuffix appends the result of splitDomainWithSuffix to +// dst. +func appendSplitDomainWithSuffix(dst []string, domain, d, suffix string, icann bool) []string { if suffix == d { - return []string{domain} + return append(dst, domain) + } + + // All domains to return are a suffix of the fully qualified domain, if + // the labels before the public suffix are well-formed: Slice them from + // the domain instead of joining the labels again. + // This is called for every domain and CNAME of every new connection. + subdomains := d[:len(d)-len(suffix)] + if !strings.HasSuffix(d, suffix) || + !strings.HasSuffix(subdomains, ".") || + strings.HasPrefix(subdomains, ".") || + strings.Contains(subdomains, "..") { + irregular := splitIrregularDomain(d, suffix, icann) + if dst == nil { + return irregular + } + return append(dst, irregular...) + } + fqdn := domain + if len(fqdn) == len(d) { + fqdn += "." + } + + dst = slices.Grow(dst, strings.Count(subdomains, ".")+1) + start := 0 + for i := range len(subdomains) { + if subdomains[i] == '.' { + dst = append(dst, fqdn[start:]) + start = i + 1 + } + } + + // If the suffix is not a real TLD, but a public suffix, add it to the list. + if !icann { + dst = append(dst, fqdn[len(subdomains):]) } + return dst +} + +// splitIrregularDomain is the general implementation of splitDomain, which +// also handles domains with empty labels. d is the domain without the +// trailing dot. +func splitIrregularDomain(d, suffix string, icann bool) []string { // Split all subdomain into labels. labels := strings.FieldsFunc(d[:len(d)-len(suffix)], func(r rune) bool { return r == '.' @@ -536,10 +626,10 @@ func (e *Entity) MatchLists(lists []string) bool { e.BlockedByLists = nil e.BlockedEntities = nil - lm := makeMap(lists) + // There are only a few filter lists: Scan them instead of building a map. for key, keyLists := range e.ListOccurences { for _, keyListID := range keyLists { - if _, ok := lm[keyListID]; ok { + if slices.Contains(lists, keyListID) { e.BlockedByLists = append(e.BlockedByLists, keyListID) e.BlockedEntities = append(e.BlockedEntities, key) } @@ -556,15 +646,13 @@ func (e *Entity) MatchLists(lists []string) bool { func (e *Entity) ListBlockReason() ListBlockReason { blockedBy := make([]ListMatch, len(e.BlockedEntities)) - lm := makeMap(e.BlockedByLists) - for idx, blockedEntity := range e.BlockedEntities { if entityLists, ok := e.ListOccurences[blockedEntity]; ok { var activeLists []string var inactiveLists []string for _, l := range entityLists { - if _, ok := lm[l]; ok { + if slices.Contains(e.BlockedByLists, l) { activeLists = append(activeLists, l) } else { inactiveLists = append(inactiveLists, l) @@ -582,24 +670,78 @@ func (e *Entity) ListBlockReason() ListBlockReason { return blockedBy } -func mergeStringList(a, b []string) []string { - listMap := make(map[string]struct{}) - for _, s := range a { - listMap[s] = struct{}{} +// appendListDomains appends the domains to look up in the filter lists for +// the given domain of the entity to dst: the domain and its CNAMEs, if +// enabled, and their parent domains, if enabled. The result may contain +// duplicates. +func (e *Entity) appendListDomains(dst []string, domain string) []string { + checkCNAMEs := e.checkCNAMEs && len(e.CNAME) > 0 + + if !e.resolveSubDomainLists { + dst = append(dst, domain) + if checkCNAMEs { + dst = append(dst, e.CNAME...) + } + return dst } - for _, s := range b { - listMap[s] = struct{}{} + + // Use the public suffix of the domain from the entity. + d := strings.TrimSuffix(domain, ".") + suffix, icann := e.getPublicSuffix(d) + dst = appendSplitDomainWithSuffix(dst, domain, d, suffix, icann) + if checkCNAMEs { + for _, cname := range e.CNAME { + dst = appendSplitDomain(dst, cname) + } } + return dst +} - res := make([]string, 0, len(listMap)) - for s := range listMap { - res = append(res, s) +// getPublicSuffix returns publicsuffix.PublicSuffix(d). The result is kept +// for the last d, which is the domain of the entity. +func (e *Entity) getPublicSuffix(d string) (suffix string, icann bool) { + if e.publicSuffixOf != d || e.publicSuffix == "" { + e.publicSuffix, e.publicSuffixICANN = publicsuffix.PublicSuffix(d) + e.publicSuffixOf = d } - sort.Strings(res) - return res + return e.publicSuffix, e.publicSuffixICANN +} + +// mergeStringList returns the sorted, distinct values of a and b in a new +// slice. The result is not nil. +func mergeStringList(a, b []string) []string { + res := make([]string, 0, len(a)+len(b)) + res = append(res, a...) + res = append(res, b...) + slices.Sort(res) + return slices.Compact(res) } +// makeDistinctMaxScan is the length up to which makeDistinct scans the +// distinct values instead of using a map. The values are the domains of an +// entity, or its list matches, which are usually only a few. +const makeDistinctMaxScan = 64 + +// makeDistinct returns the distinct values of slice in the order of their first +// occurrence. The result is not nil. It may use the array of slice. func makeDistinct(slice []string) []string { + switch { + case slice == nil: + return []string{} + case len(slice) > makeDistinctMaxScan: + return makeDistinctWithMap(slice) + } + + result := slice[:0] + for _, v := range slice { + if !slices.Contains(result, v) { + result = append(result, v) + } + } + return result +} + +func makeDistinctWithMap(slice []string) []string { m := make(map[string]struct{}, len(slice)) result := make([]string, 0, len(slice)) @@ -614,11 +756,3 @@ func makeDistinct(slice []string) []string { return result } - -func makeMap(slice []string) map[string]struct{} { - lm := make(map[string]struct{}) - for _, v := range slice { - lm[v] = struct{}{} - } - return lm -} diff --git a/service/intel/entity_lists_test.go b/service/intel/entity_lists_test.go new file mode 100644 index 000000000..932eed528 --- /dev/null +++ b/service/intel/entity_lists_test.go @@ -0,0 +1,234 @@ +package intel + +import ( + "math/rand/v2" + "reflect" + "slices" + "strconv" + "testing" +) + +// oldMatchLists, oldListBlockReason, oldMakeDistinct and oldMakeMap are the +// previous implementations with maps, kept to check that the results are +// unchanged. + +func oldMatchLists(e *Entity, lists []string) bool { + if len(lists) == 0 { + return false + } + + e.BlockedByLists = nil + e.BlockedEntities = nil + + lm := oldMakeMap(lists) + for key, keyLists := range e.ListOccurences { + for _, keyListID := range keyLists { + if _, ok := lm[keyListID]; ok { + e.BlockedByLists = append(e.BlockedByLists, keyListID) + e.BlockedEntities = append(e.BlockedEntities, key) + } + } + } + + e.BlockedByLists = oldMakeDistinct(e.BlockedByLists) + e.BlockedEntities = oldMakeDistinct(e.BlockedEntities) + + return len(e.BlockedByLists) > 0 +} + +func oldListBlockReason(e *Entity) ListBlockReason { + blockedBy := make([]ListMatch, len(e.BlockedEntities)) + + lm := oldMakeMap(e.BlockedByLists) + + for idx, blockedEntity := range e.BlockedEntities { + if entityLists, ok := e.ListOccurences[blockedEntity]; ok { + var activeLists []string + var inactiveLists []string + + for _, l := range entityLists { + if _, ok := lm[l]; ok { + activeLists = append(activeLists, l) + } else { + inactiveLists = append(inactiveLists, l) + } + } + + blockedBy[idx] = ListMatch{ + Entity: blockedEntity, + ActiveLists: activeLists, + InactiveLists: inactiveLists, + } + } + } + + return blockedBy +} + +func oldMakeDistinct(slice []string) []string { + m := make(map[string]struct{}, len(slice)) + result := make([]string, 0, len(slice)) + + for _, v := range slice { + if _, ok := m[v]; ok { + continue + } + + m[v] = struct{}{} + result = append(result, v) + } + + return result +} + +func oldMakeMap(slice []string) map[string]struct{} { + lm := make(map[string]struct{}) + for _, v := range slice { + lm[v] = struct{}{} + } + return lm +} + +// randomStrings returns up to maxLen strings of a pool of poolSize strings +// with the given prefix, possibly with duplicates, or nil. +func randomStrings(rng *rand.Rand, prefix string, poolSize, maxLen int) []string { + n := rng.IntN(maxLen + 1) + if n == 0 && rng.IntN(2) == 0 { + return nil + } + s := make([]string, n) + for i := range s { + s[i] = prefix + strconv.Itoa(rng.IntN(poolSize)) + } + return s +} + +func TestMakeDistinctMatchesMapImplementation(t *testing.T) { + t.Parallel() + + rng := rand.New(rand.NewPCG(1, 2)) //nolint:gosec // Test input. + for range 100000 { + // Also cover inputs longer than the linear scan threshold. + in := randomStrings(rng, "d", 1+rng.IntN(200), rng.IntN(150)) + want := oldMakeDistinct(slices.Clone(in)) + got := makeDistinct(slices.Clone(in)) + if !reflect.DeepEqual(got, want) || (got == nil) != (want == nil) { + t.Fatalf("makeDistinct(%q): got %q, want %q", in, got, want) + } + } +} + +func TestMatchListsMatchesMapImplementation(t *testing.T) { + t.Parallel() + + rng := rand.New(rand.NewPCG(3, 4)) //nolint:gosec // Test input. + for i := range 100000 { + lists := randomStrings(rng, "L", 30, 40) + + // The order of the results of MatchLists depends on the iteration + // order of ListOccurences, which is random: Compare the order only + // for a single key. + keys := 1 + if i%2 == 1 { + keys = rng.IntN(12) + } + var occurrences map[string][]string + if keys > 0 || rng.IntN(2) == 0 { + occurrences = make(map[string][]string, keys) + } + for range keys { + occurrences["k"+strconv.Itoa(rng.IntN(20))] = randomStrings(rng, "L", 40, 8) + } + + want := &Entity{ListOccurences: occurrences} + wantMatch := oldMatchLists(want, lists) + got := &Entity{ListOccurences: occurrences} + gotMatch := got.MatchLists(lists) + + if keys > 1 { + // Sort a copy of the results of both. + for _, e := range []*Entity{want, got} { + if e.BlockedByLists != nil { + e.BlockedByLists = slices.Sorted(slices.Values(e.BlockedByLists)) + } + if e.BlockedEntities != nil { + e.BlockedEntities = slices.Sorted(slices.Values(e.BlockedEntities)) + } + } + } + if gotMatch != wantMatch || + !reflect.DeepEqual(got.BlockedByLists, want.BlockedByLists) || + !reflect.DeepEqual(got.BlockedEntities, want.BlockedEntities) { + t.Fatalf("MatchLists(%q) of %q: got %v %q %q, want %v %q %q", + lists, occurrences, + gotMatch, got.BlockedByLists, got.BlockedEntities, + wantMatch, want.BlockedByLists, want.BlockedEntities) + } + + // The block reason only depends on the entity. + if wantReason, gotReason := oldListBlockReason(got), got.ListBlockReason(); !reflect.DeepEqual(gotReason, wantReason) { + t.Fatalf("ListBlockReason of %q, %q, %q: got %v, want %v", + occurrences, got.BlockedByLists, got.BlockedEntities, gotReason, wantReason) + } + } +} + +const ( + testDomain = "www.example.com." + testParentDomain = "example.com." + testCNAME = "e1.example.net." +) + +// benchListIDs are the source IDs of the active filter lists. The default +// categories resolve to about this many sources. +var benchListIDs = []string{ + "TRAC-1", "TRAC-2", "TRAC-3", "TRAC-4", "TRAC-5", + "MAL-1", "MAL-2", "MAL-3", + "BAD-1", "BAD-2", + "UNBREAK-1", "UNBREAK-2", +} + +// BenchmarkMatchLists measures matching the list occurrences of an entity +// against the active filter lists, and the block reason if it matches. +func BenchmarkMatchLists(b *testing.B) { + for _, bc := range []struct { + name string + occurrences map[string][]string + }{ + {name: "unlisted"}, + {name: "inactive", occurrences: map[string][]string{ + testParentDomain: {"SOC-1", "SOC-2"}, + "15133": {"ASN-1"}, + }}, + {name: "listed", occurrences: map[string][]string{ + testParentDomain: {"MAL-2", "SOC-1", "TRAC-3"}, + testCNAME: {"CDN-1", "TRAC-4"}, + "15133": {"ASN-1"}, + }}, + } { + b.Run(bc.name, func(b *testing.B) { + e := &Entity{ListOccurences: bc.occurrences} + b.ReportAllocs() + for b.Loop() { + if e.MatchLists(benchListIDs) { + _ = e.ListBlockReason() + } + } + }) + } +} + +// BenchmarkMakeDistinct measures removing duplicates from the domains to look +// up in the filter lists of a domain with a CNAME. +func BenchmarkMakeDistinct(b *testing.B) { + domains := []string{ + testDomain, testParentDomain, + testCNAME, "example.net.", + } + in := make([]string, len(domains)) + b.ReportAllocs() + for b.Loop() { + copy(in, domains) + _ = makeDistinct(in) + } +} diff --git a/service/intel/entity_loadlists_test.go b/service/intel/entity_loadlists_test.go new file mode 100644 index 000000000..12f40264d --- /dev/null +++ b/service/intel/entity_loadlists_test.go @@ -0,0 +1,123 @@ +package intel + +import ( + "context" + "net" + "slices" + "strings" + "testing" + _ "unsafe" // For go:linkname. + + "golang.org/x/net/publicsuffix" + + "github.com/safing/portmaster/service/network/netutils" +) + +// filterListsLoaded is the channel of the filterlists package that is closed +// when the filter lists are loaded. Lookups before that only log a warning. +// +//go:linkname filterListsLoaded github.com/safing/portmaster/service/intel/filterlists.filterListsLoaded +var filterListsLoaded chan struct{} + +// BenchmarkLoadLists measures looking up all filter lists of the entity of a +// new connection with a domain and a CNAME, with loaded filter lists that do +// not contain the entity, like almost all entities. +func BenchmarkLoadLists(b *testing.B) { + prevLoaded := filterListsLoaded + filterListsLoaded = make(chan struct{}) + close(filterListsLoaded) + b.Cleanup(func() { filterListsLoaded = prevLoaded }) + + ctx := context.Background() + b.ReportAllocs() + for b.Loop() { + e := (&Entity{ + IP: net.IPv4(93, 184, 216, 34), + IPScope: netutils.Global, + Protocol: 6, + Port: 443, + Domain: testDomain, + CNAME: []string{testCNAME}, + Country: "US", + ASN: 15133, + ASOrg: "Edgecast Inc.", + }).Init(443) + // The location was already looked up when the entity was created. + e.fetchLocationOnce.Do(func() {}) + e.ResolveSubDomainLists(ctx, true) + e.EnableCNAMECheck(ctx, true) + + e.LoadLists(ctx) + if e.ListOccurences != nil || e.ListsError != "" { + b.Fatalf("unexpected lists: %v %s", e.ListOccurences, e.ListsError) + } + } +} + +// oldListDomains is the previous implementation of collecting the domains to +// look up in getDomainLists, kept to check that the result is unchanged. +func oldListDomains(e *Entity, domain string) []string { + domainsToInspect := []string{domain} + + if e.checkCNAMEs && len(e.CNAME) > 0 { + domainsToInspect = append(domainsToInspect, e.CNAME...) + } + + var domains []string + if e.resolveSubDomainLists { + for i, domain := range domainsToInspect { + var subdomains []string + if i == 0 { + d := strings.TrimSuffix(domain, ".") + suffix, icann := publicsuffix.PublicSuffix(d) + subdomains = splitDomainWithSuffix(domain, d, suffix, icann) + } else { + subdomains = splitDomain(domain) + } + domains = append(domains, subdomains...) + } + } else { + domains = domainsToInspect + } + + return makeDistinct(domains) +} + +func TestAppendListDomainsMatchesOld(t *testing.T) { + t.Parallel() + + domains := []string{ + testDomain, testParentDomain, "org.", ".", "", + "a.b.c.d.example.co.uk.", "co.uk.", "foo.blogspot.com.", "blogspot.com.", + "www.example.com", "...com", "a..example.com.", ".example.com.", + "localhost.", "x.localhost.", "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.example.org.", + } + cnameSets := [][]string{ + nil, + {}, + {testCNAME}, + {testCNAME, "edge.example-cdn.net.", testDomain}, + {testParentDomain, "a..b.example.org.", "net."}, + } + for _, domain := range domains { + for _, cnames := range cnameSets { + for _, subDomains := range []bool{false, true} { + for _, checkCNAMEs := range []bool{false, true} { + e := &Entity{ + Domain: domain, + CNAME: cnames, + resolveSubDomainLists: subDomains, + checkCNAMEs: checkCNAMEs, + } + want := oldListDomains(e, domain) + var buf [16]string + got := makeDistinct(e.appendListDomains(buf[:0], domain)) + if !slices.Equal(got, want) { + t.Errorf("domain %q, CNAMEs %q, sub-domains %v, CNAME check %v: got %q, want %q", + domain, cnames, subDomains, checkCNAMEs, got, want) + } + } + } + } + } +} diff --git a/service/intel/entity_merge_test.go b/service/intel/entity_merge_test.go new file mode 100644 index 000000000..3a40c232d --- /dev/null +++ b/service/intel/entity_merge_test.go @@ -0,0 +1,64 @@ +package intel + +import ( + "fmt" + "math/rand" + "reflect" + "sort" + "testing" +) + +func mergeStringListMap(a, b []string) []string { + listMap := make(map[string]struct{}) + for _, s := range a { + listMap[s] = struct{}{} + } + for _, s := range b { + listMap[s] = struct{}{} + } + + res := make([]string, 0, len(listMap)) + for s := range listMap { + res = append(res, s) + } + sort.Strings(res) + return res +} + +func randStrings(r *rand.Rand, n int) []string { + if n < 0 { + return nil + } + s := make([]string, n) + for i := range s { + s[i] = fmt.Sprintf("list%d", r.Intn(12)) + } + return s +} + +func TestMergeStringListMatchesMap(t *testing.T) { + t.Parallel() + r := rand.New(rand.NewSource(1)) //nolint:gosec + for range 50000 { + a, b := randStrings(r, r.Intn(12)-1), randStrings(r, r.Intn(12)-1) + want := mergeStringListMap(a, b) + got := mergeStringList(a, b) + if !reflect.DeepEqual(want, got) { + t.Fatalf("mergeStringList(%v, %v) = %#v, want %#v", a, b, got, want) + } + } +} + +func BenchmarkMergeStringList(b *testing.B) { + for _, n := range []int{0, 1, 3, 10} { + r := rand.New(rand.NewSource(2)) //nolint:gosec + x, y := randStrings(r, n), randStrings(r, n) + b.Run(fmt.Sprintf("n%d", n), func(b *testing.B) { + b.ReportAllocs() + for range b.N { + _ = mergeStringList(nil, y) + _ = mergeStringList(x, y) + } + }) + } +} diff --git a/service/intel/entity_publicsuffix_test.go b/service/intel/entity_publicsuffix_test.go new file mode 100644 index 000000000..13b687022 --- /dev/null +++ b/service/intel/entity_publicsuffix_test.go @@ -0,0 +1,72 @@ +package intel + +import ( + "slices" + "strings" + "testing" + + "golang.org/x/net/publicsuffix" +) + +var publicSuffixTestDomains = []string{ + "", ".", "..", "...", + "com.", "COM", "localhost", "localhost.", "notatld", "a.notatld.", + "example.com", testDomain, "a.b.c.d.example.com.", + "WWW.Example.COM.", "Example.Com", + "example.com..", "www.example.com...", ".example.com", ".example.com.", + "www..example.com.", "a...b.example.com", "..example.com.", + "co.uk", "co.uk.", "bbc.co.uk.", "www.bbc.co.uk.", "www.BBC.CO.UK", + "github.io", "github.io.", "user.github.io.", "www.user.github.io", + "blogspot.com.", "a.b.c.blogspot.com.", "foo.appspot.com", + "bucket.s3.amazonaws.com.", "s3.amazonaws.com", + "ck", "x.ck.", "www.ck.", "a.www.ck", "a.b.x.ck.", + "kyoto.jp", "a.kyoto.jp.", "b.a.kyoto.jp", "city.kawasaki.jp.", "x.city.kawasaki.jp.", + "xn--bcher-kva.de.", "www.xn--bcher-kva.example.", "bücher.de", "www.bücher.de.", + "xn--fiqs8s", "www.xn--fiqs8s.", "www.example.xn--fiqs8s.", "\u4f8b\u5b50.\u4e2d\u56fd.", + "1.2.3.4", "1.2.3.4.", "::1", "2001:db8::1", "[::1]", + "*.example.com.", "-.example.com", "a b.example.com", "a/b.com.", + testCNAME, "edge-12.eu-west-1.cdn.example.co.uk.", + strings.Repeat("a.", 60) + "example.com.", +} + +// TestEntityPublicSuffixMatchesPublicSuffix checks that the public suffix +// kept by the entity gives the same results as looking it up every time, +// also when the domain of the entity changes. +func TestEntityPublicSuffixMatchesPublicSuffix(t *testing.T) { + t.Parallel() + + reused := &Entity{} + for _, firstHeuristics := range []bool{false, true} { + for _, domain := range publicSuffixTestDomains { + for _, e := range []*Entity{{}, reused} { + e.Domain = domain + if firstHeuristics { + checkEffectiveTLDPlusOne(t, e) + } + + // Like getDomainLists. + d := strings.TrimSuffix(domain, ".") + suffix, icann := e.getPublicSuffix(d) + wantSuffix, wantICANN := publicsuffix.PublicSuffix(d) + if suffix != wantSuffix || icann != wantICANN { + t.Errorf("public suffix of %q: got %q %v, want %q %v", d, suffix, icann, wantSuffix, wantICANN) + } + if got, want := splitDomainWithSuffix(domain, d, suffix, icann), splitDomain(domain); !slices.Equal(got, want) { + t.Errorf("split %q: got %q, want %q", domain, got, want) + } + + checkEffectiveTLDPlusOne(t, e) + } + } + } +} + +func checkEffectiveTLDPlusOne(t *testing.T, e *Entity) { + t.Helper() + + got, ok := e.EffectiveTLDPlusOne() + want, wantErr := publicsuffix.EffectiveTLDPlusOne(strings.TrimRight(e.Domain, ".")) + if got != want || ok != (wantErr == nil) { + t.Errorf("eTLD+1 of %q: got %q %v, want %q %v", e.Domain, got, ok, want, wantErr) + } +} diff --git a/service/intel/entity_test.go b/service/intel/entity_test.go index 83a8fd7bc..1d32a6bae 100644 --- a/service/intel/entity_test.go +++ b/service/intel/entity_test.go @@ -1,9 +1,13 @@ package intel import ( + "context" + "net" + "strings" "testing" "github.com/stretchr/testify/assert" + "golang.org/x/net/publicsuffix" ) var splitDomainTestCases = [][]string{ @@ -31,3 +35,71 @@ func TestSplitDomain(t *testing.T) { assert.Equal(t, testCase, splitted, "result must match") } } + +// TestSplitDomainMatchesGeneralImplementation checks that slicing the parent +// domains from the domain returns exactly what joining the labels returns, +// also for irregular domains. +func TestSplitDomainMatchesGeneralImplementation(t *testing.T) { + t.Parallel() + + labels := []string{"", "a", "www", "example", "com", "co", "uk", "googleapis", "blogspot", "xn--bcher-kva", "ck", "*", "!www", "compute", "amazonaws", "cn", "local", "1", "EXAMPLE", "Com"} + domains := make([]string, 0, 110000) + for _, l1 := range labels { + domains = append(domains, l1) + for _, l2 := range labels { + domains = append(domains, l1+"."+l2) + for _, l3 := range labels { + domains = append(domains, l1+"."+l2+"."+l3) + for _, l4 := range []string{"", "com", "uk", "ck", "cn", "www"} { + domains = append(domains, l1+"."+l2+"."+l3+"."+l4) + domains = append(domains, "sub.domain."+l1+"."+l2+"."+l3+"."+l4) + } + } + } + } + + var sliced int + for _, domain := range domains { + for _, domain := range []string{domain, domain + ".", domain + "..", "." + domain} { + d := strings.TrimSuffix(domain, ".") + suffix, icann := publicsuffix.PublicSuffix(d) + expected := []string{domain} + if suffix != d { + expected = splitIrregularDomain(d, suffix, icann) + } + + splitted := splitDomain(domain) + if !assert.Equal(t, expected, splitted, "domain %q", domain) { + return + } + if len(splitted) > 1 { + sliced++ + } + } + } + assert.Greater(t, sliced, 10000) +} + +func BenchmarkSplitDomain(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + splitDomain("www.example.com.") + splitDomain("edge-12.eu-west-1.cdn.example.co.uk.") + } +} + +func TestGetCountryInfoWithoutLocation(t *testing.T) { + t.Parallel() + + // Neither an entity without IP nor one with a non-global IP gets a location + // or a location error, so no geoip database is involved. + for name, e := range map[string]*Entity{ + "no IP": {}, + "non-global IP": {IP: net.ParseIP("192.168.1.1")}, + } { + e.Init(0) + assert.NotPanics(t, func() { + assert.Nil(t, e.GetCountryInfo(context.Background()), name) + }, name) + } +} diff --git a/service/intel/filterlists/decoder.go b/service/intel/filterlists/decoder.go index a0b580f77..70509b8ec 100644 --- a/service/intel/filterlists/decoder.go +++ b/service/intel/filterlists/decoder.go @@ -1,6 +1,7 @@ package filterlists import ( + "bufio" "compress/gzip" "context" "encoding/binary" @@ -51,8 +52,12 @@ func decodeFile(ctx context.Context, r io.Reader, ch chan<- *listEntry) error { } } - // we need a reader that supports io.ByteReader - reader := &byteReader{r} + // Buffer the reads: the entry lengths are read byte by byte, which would + // otherwise be one read from the (decompressing) source per byte. + reader := bufio.NewReaderSize(r, 64*1024) + // The entry buffer is reused for all entries. This is safe, as all + // formats that can decode a listEntry copy the strings out of the data. + var buf []byte var entryCount int for { entryCount++ @@ -64,7 +69,10 @@ func decodeFile(ctx context.Context, r io.Reader, ch chan<- *listEntry) error { return fmt.Errorf("failed to load varint entity length: %w", readErr) } - blob := make([]byte, length) + if uint64(cap(buf)) < length { + buf = make([]byte, length) + } + blob := buf[:length] _, readErr = io.ReadFull(reader, blob) if readErr != nil { if errors.Is(readErr, io.EOF) { @@ -134,12 +142,3 @@ func parseHeader(r io.Reader) (compressed bool, format byte, err error) { return compressed, format, err } - -// byteReader extends an io.Reader to implement the ByteReader interface. -type byteReader struct{ io.Reader } - -func (br *byteReader) ReadByte() (byte, error) { - var b [1]byte - _, err := br.Read(b[:]) - return b[0], err -} diff --git a/service/intel/filterlists/decoder_test.go b/service/intel/filterlists/decoder_test.go new file mode 100644 index 000000000..236c6590e --- /dev/null +++ b/service/intel/filterlists/decoder_test.go @@ -0,0 +1,92 @@ +package filterlists + +import ( + "bytes" + "compress/gzip" + "encoding/binary" + "encoding/json" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/structures/dsd" +) + +const testTypeDomain = "Domain" + +func encodeTestList(t *testing.T, compressed bool, entries []listEntry) []byte { + t.Helper() + + var body bytes.Buffer + for _, e := range entries { + data, err := json.Marshal(e) + require.NoError(t, err) + body.Write(binary.AppendUvarint(nil, uint64(len(data)))) + body.Write(data) + } + + out := bytes.Buffer{} + out.WriteByte(dsd.LIST) + if !compressed { + out.WriteByte(dsd.JSON) + out.Write(body.Bytes()) + return out.Bytes() + } + out.WriteByte(dsd.GZIP) + out.WriteByte(dsd.JSON) + zw := gzip.NewWriter(&out) + _, err := zw.Write(body.Bytes()) + require.NoError(t, err) + require.NoError(t, zw.Close()) + return out.Bytes() +} + +func TestDecodeFile(t *testing.T) { + t.Parallel() + + // Entries of different lengths, so the reused buffer shrinks and grows. + entries := []listEntry{ + {Type: testTypeDomain, Entity: "a-rather-long-domain-name.example.com", Resources: []entryResource{{SourceID: "TRAC", ResourceID: "x"}}}, + {Type: testTypeDomain, Entity: "b.org"}, + {Type: "IPv4", Entity: "192.0.2.1", Whitelist: true}, + {Type: testTypeDomain, Entity: "another-long-domain-name-for-growing-the-buffer.example.net"}, + } + + for _, compressed := range []bool{false, true} { + ch := make(chan *listEntry, len(entries)+1) + err := decodeFile(t.Context(), bytes.NewReader(encodeTestList(t, compressed, entries)), ch) + require.NoError(t, err) + close(ch) + + var got []listEntry + for e := range ch { + got = append(got, *e) + } + assert.Equal(t, entries, got, "compressed=%v", compressed) + } +} + +func BenchmarkDecodeFile(b *testing.B) { + t := &testing.T{} + entries := make([]listEntry, 20000) + for i := range entries { + entries[i] = listEntry{Type: testTypeDomain, Entity: "host-" + strconv.Itoa(i) + ".example.com", Resources: []entryResource{{SourceID: "TRAC", ResourceID: "x"}}} + } + data := encodeTestList(t, true, entries) + + b.ReportAllocs() + for b.Loop() { + ch := make(chan *listEntry, 128) + go func() { + for range ch { //nolint:revive // Drain. + } + }() + err := decodeFile(b.Context(), bytes.NewReader(data), ch) + if err != nil { + b.Fatal(err) + } + close(ch) + } +} diff --git a/service/intel/filterlists/lookup.go b/service/intel/filterlists/lookup.go index 2b3348165..805505358 100644 --- a/service/intel/filterlists/lookup.go +++ b/service/intel/filterlists/lookup.go @@ -14,12 +14,13 @@ import ( // key does not exist, instead, an empty slice is // returned. func lookupBlockLists(entity, value string) ([]string, error) { - key := makeListCacheKey(entity, value) if !isLoaded() { - log.Warningf("intel/filterlists: not searching for %s because filterlists not loaded", key) // filterLists have not yet been loaded so // there's no point querying into the cache - // database. + // database. This happens for every connection until the first + // download; the module state "filter lists disabled" already tells + // the user, so do not fill the log. + log.Debugf("intel/filterlists: not searching for %s because filterlists not loaded", makeListCacheKey(entity, value)) return nil, nil } @@ -30,6 +31,10 @@ func lookupBlockLists(entity, value string) ([]string, error) { return nil, nil } + // Only build the key for values that may be in a list: Almost all lookups + // end at the bloom filter above. + key := makeListCacheKey(entity, value) + // log.Debugf("intel/filterlists: searching for entries with %s", key) entry, err := getEntityRecordByKey(key) if err != nil { diff --git a/service/intel/filterlists/lookup_bench_test.go b/service/intel/filterlists/lookup_bench_test.go new file mode 100644 index 000000000..eb993aa60 --- /dev/null +++ b/service/intel/filterlists/lookup_bench_test.go @@ -0,0 +1,22 @@ +package filterlists + +import "testing" + +// BenchmarkLookupDomainMiss measures looking up a domain that is in no filter +// list, which is the result of almost every lookup. Every new connection looks +// up its domain, its CNAMEs and all their parent domains. +func BenchmarkLookupDomainMiss(b *testing.B) { + // Mark the (empty) filter lists as loaded. + prevLoaded := filterListsLoaded + filterListsLoaded = make(chan struct{}) + close(filterListsLoaded) + b.Cleanup(func() { filterListsLoaded = prevLoaded }) + + b.ReportAllocs() + for b.Loop() { + lists, err := LookupDomain("www.example.com.") + if err != nil || len(lists) > 0 { + b.Fatalf("unexpected result: %v, %v", lists, err) + } + } +} diff --git a/service/intel/geoip/database.go b/service/intel/geoip/database.go index 395827569..484feed32 100644 --- a/service/intel/geoip/database.go +++ b/service/intel/geoip/database.go @@ -1,6 +1,7 @@ package geoip import ( + "errors" "fmt" "os" "sync" @@ -61,7 +62,13 @@ func (ub *updateBroadcaster) AvailableUpdate() *updates.Artifact { // Get artifact. artifact, err := module.instance.IntelUpdates().GetFile(ub.dbName) - if err != nil { + switch { + case errors.Is(err, updates.ErrNotFound): + // No intel data downloaded yet. Lookups trigger this check, so do not + // warn about it each time. + log.Debugf("geoip: %s not available yet", ub.dbName) + return nil + case err != nil: log.Warningf("geoip: failed to get geoip update: %s", err) return nil } diff --git a/service/intel/geoip/database_test.go b/service/intel/geoip/database_test.go index 2d9c5e939..ca4ef24f7 100644 --- a/service/intel/geoip/database_test.go +++ b/service/intel/geoip/database_test.go @@ -19,10 +19,12 @@ func TestFileReplaced(t *testing.T) { downloaded := filepath.Join(dir, "downloaded.mmdb") content := []byte("mapped database") - if err := os.WriteFile(active, content, 0o600); err != nil { + err := os.WriteFile(active, content, 0o600) + if err != nil { t.Fatal(err) } - if err := os.WriteFile(downloaded, content, 0o600); err != nil { + err = os.WriteFile(downloaded, content, 0o600) + if err != nil { t.Fatal(err) } @@ -33,15 +35,18 @@ func TestFileReplaced(t *testing.T) { } // Give the replacement the same timestamp as the mapped file. - if err := os.Chtimes(downloaded, mapped.ModTime(), mapped.ModTime()); err != nil { + err = os.Chtimes(downloaded, mapped.ModTime(), mapped.ModTime()) + if err != nil { t.Fatal(err) } // Updater: move the mapped file away, rename the replacement into place. - if err := os.Rename(active, purged); err != nil { + err = os.Rename(active, purged) + if err != nil { t.Fatal(err) } - if err := os.Rename(downloaded, active); err != nil { + err = os.Rename(downloaded, active) + if err != nil { t.Fatal(err) } @@ -77,7 +82,8 @@ func TestFileReplaced(t *testing.T) { } // Missing file: an error, not a verdict. - if _, err := fileReplaced(mapped, filepath.Join(dir, "missing.mmdb")); err == nil { + _, err = fileReplaced(mapped, filepath.Join(dir, "missing.mmdb")) + if err == nil { t.Error("missing file did not return an error") } } diff --git a/service/intel/geoip/lookup.go b/service/intel/geoip/lookup.go index 0aeef434d..9de888228 100644 --- a/service/intel/geoip/lookup.go +++ b/service/intel/geoip/lookup.go @@ -7,6 +7,9 @@ import ( "github.com/oschwald/maxminddb-golang" ) +// ErrDatabaseNotAvailable is returned by lookups while no geoip database is loaded. +var ErrDatabaseNotAvailable = errors.New("geoip database not available") + func getReader(ip net.IP) *maxminddb.Reader { isV6 := ip.To4() == nil return worker.GetReader(isV6, true) @@ -16,7 +19,7 @@ func getReader(ip net.IP) *maxminddb.Reader { func GetLocation(ip net.IP) (*Location, error) { db := getReader(ip) if db == nil { - return nil, errors.New("geoip database not available") + return nil, ErrDatabaseNotAvailable } record := &Location{} if err := db.Lookup(ip, record); err != nil { diff --git a/service/interop/ivpn/evt_handlers.go b/service/interop/ivpn/evt_handlers.go index a5e3b3a30..ac2100dda 100644 --- a/service/interop/ivpn/evt_handlers.go +++ b/service/interop/ivpn/evt_handlers.go @@ -15,7 +15,7 @@ import ( func (i *InteropIvpn) onConnectionStarting(wc *mgr.WorkerCtx, _ string, messageData string) { // While VPN is active, ignore network-derived location sources. // Virtual VPN interfaces/IPs can skew detected device location - // and lead to selecting an incorrect SPN home hub. + // and lead to an incorrect device location. netenv.DisableNetworkDerivedLocation(true) connInfo := ivpnclient.ConnectionStarting{} diff --git a/service/interop/ivpn/hook_default.go b/service/interop/ivpn/hook_default.go index b06ee9088..39d319d89 100644 --- a/service/interop/ivpn/hook_default.go +++ b/service/interop/ivpn/hook_default.go @@ -1,16 +1,19 @@ -//go:build !linux && !windows +//go:build !linux package ivpn import ( "github.com/safing/portmaster/service/mgr" - "github.com/safing/portmaster/spn/hub" ) type platformSpecific struct{} -func (i *InteropIvpn) spnConnectingHook(w *mgr.WorkerCtx, hookCtx hub.Announcement) (cancel bool, err error) { - return true, nil -} func (i *InteropIvpn) reconcileCompatibilityState(wc *mgr.WorkerCtx) { } + +// clientInstalled reports whether the IVPN client is installed. On these +// platforms the IVPN client library reports a missing installation as +// fs.ErrNotExist, so no separate check is needed. +func clientInstalled() bool { + return true +} diff --git a/service/interop/ivpn/hook_linux.go b/service/interop/ivpn/hook_linux.go index e9a1ed4bb..4e0cdc888 100644 --- a/service/interop/ivpn/hook_linux.go +++ b/service/interop/ivpn/hook_linux.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "net" + "os" "os/exec" "strconv" "sync/atomic" @@ -13,14 +14,11 @@ import ( "github.com/ivpn/desktop-app/daemon/protocol/ivpnclient" "github.com/safing/portmaster/base/config" "github.com/safing/portmaster/service/mgr" - "github.com/safing/portmaster/service/netenv" - "github.com/safing/portmaster/spn/hub" ) type platformSpecific struct { - spnWgNftRuleHandle atomic.Int32 // nft rule handle we registered for SPN compatibility with WireGuard - spnWgIptRuleIP atomic.Value // last WG local IP used for iptables fallback rule (string) - spnHubInfo atomic.Pointer[hub.Announcement] // last SPN hub info (hub.Info) + wgNftRuleHandle atomic.Int64 // nft rule handle we registered for split tunnel compatibility with WireGuard + wgIptRuleIP atomic.Value // last WG local IP used for iptables fallback rule (string) } const ( @@ -28,47 +26,28 @@ const ( // If IVPN changes the WG interface naming, this constant may need adjustment. nftTableWgQuickIvpn = "wg-quick-wgivpn" wgKillswitchBypassComment = "portmaster-wg-ks-bypass" - spnSlitTunRouteTableID = "717" - spnSlitTunRulePriority = "717" ) -// spnConnectingHook is called when SPN is connecting to a hub. -func (i *InteropIvpn) spnConnectingHook(wc *mgr.WorkerCtx, homeHub hub.Announcement) (cancel bool, retErr error) { - i.doReconcileCompatibilityState(wc, &homeHub) - return false, nil -} - +// reconcileCompatibilityState reconciles the WireGuard firewall rule to +// maintain SplitTunnel compatibility with the current IVPN connection state. func (i *InteropIvpn) reconcileCompatibilityState(wc *mgr.WorkerCtx) { - i.doReconcileCompatibilityState(wc, i.extra.spnHubInfo.Load()) -} - -// doReconcileCompatibilityState reconciles WireGuard firewall and routing rules -// to maintain SPN and SplitTunnel compatibility with the current IVPN connection state. -func (i *InteropIvpn) doReconcileCompatibilityState(wc *mgr.WorkerCtx, hubInfo *hub.Announcement) { - // Ensure WireGuard-specific firewall rule is in place or removed as needed based on current VPN and SPN/ST state. + // Ensure WireGuard-specific firewall rule is in place or removed as needed based on current VPN and ST state. err := i.ensureWgCompatRule(wc) if err != nil { // Could happen, for example, if IVPN Client is paused wc.Warn(fmt.Sprintf("IVPN: failed to ensure WireGuard compatibility rule: %v", err)) } - - // Ensure routing rules are in place to keep SPN hub traffic outside the VPN tunnel when connected, - // or clean up stale rules when disconnected. - err = i.ensureSpnHubBypassVpnRoutes(wc, hubInfo) - if err != nil { - wc.Warn(fmt.Sprintf("IVPN: failed to ensure VPN and SPN tunnel routes: %v", err)) - } } -// SPN and SplitTunnel (ST) compatibility workaround for WireGuard kill-switch rules. +// SplitTunnel (ST) compatibility workaround for WireGuard kill-switch rules. // // WireGuard (wg-quick) installs a prerouting/raw kill-switch rule that drops // packets destined to the WG local address when they arrive from non-WG interfaces. -// Portmaster SPN/ST reverse-NAT replies are delivered via loopback (iif lo) with a +// Portmaster ST reverse-NAT replies are delivered via loopback (iif lo) with a // non-local source, which matches that drop pattern and breaks the TCP handshake // (SYN-SENT/SYN-RECV). // -// To preserve the kill-switch behavior while allowing SPN/ST reverse-NAT, Portmaster +// To preserve the kill-switch behavior while allowing ST reverse-NAT, Portmaster // inserts a narrow exception rule before the wg-quick drop: // - nft path (when wg-quick-wgivpn table exists, i.e. non-snap IVPN): // `iifname "lo" ip daddr fib saddr type != local accept` @@ -77,7 +56,7 @@ func (i *InteropIvpn) doReconcileCompatibilityState(wc *mgr.WorkerCtx, hubInfo * // // Rule lifecycle is managed here: // - Remove previously managed rule (nft/iptables) first. -// - Recreate only when WireGuard is connected and SPN/ST is enabled. +// - Recreate only when WireGuard is connected and ST is enabled. func (i *InteropIvpn) ensureWgCompatRule(wc *mgr.WorkerCtx) error { status := i.getStatus() connectedInfo := status.connectedInfo @@ -86,17 +65,17 @@ func (i *InteropIvpn) ensureWgCompatRule(wc *mgr.WorkerCtx) error { iptablesPath, _ := exec.LookPath("iptables") // Always clean previously managed rules first. This keeps behavior idempotent - // across reconnects, interface IP changes, and SPN config toggles. + // across reconnects, interface IP changes, and ST config toggles. if nftPath != "" { - oldRuleHandle := i.extra.spnWgNftRuleHandle.Load() + oldRuleHandle := i.extra.wgNftRuleHandle.Load() if oldRuleHandle != 0 { - _ = exec.Command(nftPath, "delete", "rule", "ip", nftTableWgQuickIvpn, "preraw", "handle", strconv.Itoa(int(oldRuleHandle))).Run() - i.extra.spnWgNftRuleHandle.Store(0) + _ = exec.Command(nftPath, "delete", "rule", "ip", nftTableWgQuickIvpn, "preraw", "handle", strconv.FormatInt(oldRuleHandle, 10)).Run() + i.extra.wgNftRuleHandle.Store(0) } } if iptablesPath != "" { - if oldRuleIP, ok := i.extra.spnWgIptRuleIP.Load().(string); ok && oldRuleIP != "" { + if oldRuleIP, ok := i.extra.wgIptRuleIP.Load().(string); ok && oldRuleIP != "" { _ = exec.Command( iptablesPath, "-t", "raw", @@ -107,7 +86,7 @@ func (i *InteropIvpn) ensureWgCompatRule(wc *mgr.WorkerCtx) error { "-m", "comment", "--comment", wgKillswitchBypassComment, "-j", "ACCEPT", ).Run() - i.extra.spnWgIptRuleIP.Store("") + i.extra.wgIptRuleIP.Store("") } } @@ -122,16 +101,15 @@ func (i *InteropIvpn) ensureWgCompatRule(wc *mgr.WorkerCtx) error { wgLocalIP := vpnIP.String() - // If SPN not enabled -we do not need the rule - cfgSpnEnabled := config.GetAsBool("spn/enable", false) + // If split tunneling is not enabled - we do not need the rule cfgSplittunEnabled := config.GetAsBool("splittun/enable", false) - if !cfgSpnEnabled() && !cfgSplittunEnabled() { + if !cfgSplittunEnabled() { return nil } if nftPath != "" && nftTableExists(nftPath, nftTableWgQuickIvpn) { // Insert rule by executing command: - // sudo nft --echo --json insert rule ip wg-quick-wgivpn preraw iifname "lo" ip daddr 1.2.3.4 fib saddr type != local accept comment "portmaster-spn-lo-rnat" + // sudo nft --echo --json insert rule ip wg-quick-wgivpn preraw iifname "lo" ip daddr 1.2.3.4 fib saddr type != local accept comment "portmaster-wg-ks-bypass" out, err := exec.Command(nftPath, "--echo", "--json", "insert", "rule", "ip", nftTableWgQuickIvpn, "preraw", "iifname", "lo", "ip", "daddr", wgLocalIP, "fib", "saddr", "type", "!=", "local", "accept", "comment", wgKillswitchBypassComment).Output() @@ -144,14 +122,14 @@ func (i *InteropIvpn) ensureWgCompatRule(wc *mgr.WorkerCtx) error { return fmt.Errorf("failed to parse nft rule handle: %w", parseErr) } - i.extra.spnWgNftRuleHandle.Store(int32(handle)) - wc.Debug(fmt.Sprintf("IVPN: Inserted nft SPN compatibility rule for WireGuard (handle %d, addr %s)", handle, wgLocalIP)) + i.extra.wgNftRuleHandle.Store(int64(handle)) + wc.Debug(fmt.Sprintf("IVPN: Inserted nft split tunnel compatibility rule for WireGuard (handle %d, addr %s)", handle, wgLocalIP)) return nil } if iptablesPath != "" { // Fallback for systems without nft where wg-quick uses iptables/raw rules. - // Equivalent strict exception to allow SPN reverse-NAT loopback path. + // Equivalent strict exception to allow ST reverse-NAT loopback path. err := exec.Command( iptablesPath, "-t", "raw", @@ -166,8 +144,8 @@ func (i *InteropIvpn) ensureWgCompatRule(wc *mgr.WorkerCtx) error { return fmt.Errorf("failed to insert iptables fallback rule: %w", err) } - i.extra.spnWgIptRuleIP.Store(wgLocalIP) - wc.Debug(fmt.Sprintf("IVPN: Inserted iptables SPN compatibility rule for WireGuard (addr %s)", wgLocalIP)) + i.extra.wgIptRuleIP.Store(wgLocalIP) + wc.Debug(fmt.Sprintf("IVPN: Inserted iptables split tunnel compatibility rule for WireGuard (addr %s)", wgLocalIP)) } return nil @@ -201,164 +179,15 @@ func parseNftInsertHandle(data []byte) (int, error) { return 0, fmt.Errorf("no rule entry found in nft output") } -// ensureSpnHubBypassVpnRoutes keeps Linux policy routing in sync so -// traffic to the selected SPN hub is sent via the system default gateway, not -// through the active VPN tunnel. -// -// Why this is needed: -// - When IVPN is connected, default routing points to the VPN interface. -// - SPN hub control/data path must reach the hub directly on the non-VPN uplink. -// - Without this rule/table setup, SPN hub traffic can be tunneled into VPN -// -// The function removes stale rules/routes from previous hub state, installs a -// dedicated routing table default route via the non-VPN gateway, and adds a -// high-priority destination rule for the current hub IP. -func (i *InteropIvpn) ensureSpnHubBypassVpnRoutes(wc *mgr.WorkerCtx, hubInfo *hub.Announcement) error { - oldHubInfo := i.extra.spnHubInfo.Swap(hubInfo) - - ipPath, _ := exec.LookPath("ip") - if ipPath == "" { - return fmt.Errorf("ip command not found") - } - - deleteRule := func(family, destination string) { - if destination == "" { - return - } - _ = exec.Command(ipPath, family, "rule", "del", "pref", spnSlitTunRulePriority, - "to", destination, "lookup", spnSlitTunRouteTableID).Run() - } - - // Clean up old rules for previous hub destination (if any). - if oldHubInfo != nil { - if oldHubInfo.IPv4 != nil { - deleteRule("-4", oldHubInfo.IPv4.String()+"/32") - } - if oldHubInfo.IPv6 != nil { - deleteRule("-6", oldHubInfo.IPv6.String()+"/128") - } - _ = exec.Command(ipPath, "-4", "route", "flush", "table", spnSlitTunRouteTableID).Run() - _ = exec.Command(ipPath, "-6", "route", "flush", "table", spnSlitTunRouteTableID).Run() - } - - // If VPN is not connected - we do not need to set up the rules. - connectedInfo := i.getStatus().connectedInfo - if connectedInfo == nil || connectedInfo.IsPaused { - return nil - } - vpnInterfaceIP := net.ParseIP(connectedInfo.ClientIP) - - // If SPN not enabled - we do not need the rule - // And erase stale info about the spnHub - cfgSpnEnabled := config.GetAsBool("spn/enable", false) - if !cfgSpnEnabled() || hubInfo == nil { - i.extra.spnHubInfo.Store(nil) - return nil - } - - // Check the default gateway: - // - the only one default gateway must be present - // - the VPN connection gateway (interface) must be ignored - var gw *netenv.GatewayInfo = nil - gateways := netenv.GatewaysInfo() - for idx := range gateways { - g := &gateways[idx] - if g.Mask == nil || g.IP == nil || g.Interface == "" { - continue - } - // Mask: /0 - candidate default gateway. - if ones, _ := g.Mask.Size(); ones == 0 { - // Skip the gateway if it belongs to the VPN tunnel interface (heuristic by IP). - if has, err := hasInterfaceIp(g.Interface, vpnInterfaceIP); err == nil && has { - continue - } - // in case more than 1 default gateway exists, we can not be sure which one is correct - if gw != nil { - return fmt.Errorf("multiple default gateways found, unable to determine correct one") - } - gw = g - } - } - - if gw == nil { - return fmt.Errorf("failed to find default gateway for SPN hub bypass route") - } - - // Initialize route table - - family := "-4" - hubRule := "" - if gw.IP.To4() != nil { - if err := exec.Command(ipPath, "-4", "route", "replace", "default", - "via", gw.IP.String(), "dev", gw.Interface, "table", spnSlitTunRouteTableID).Run(); err != nil { - return fmt.Errorf("failed to set IPv4 default route for SPN slit tunnel table: %w", err) - } - - if hubInfo.IPv4 != nil { - hubRule = hubInfo.IPv4.String() + "/32" - } - } else { - family = "-6" - if err := exec.Command(ipPath, "-6", "route", "replace", "default", - "via", gw.IP.String(), "dev", gw.Interface, "table", spnSlitTunRouteTableID).Run(); err != nil { - return fmt.Errorf("failed to set IPv6 default route for SPN slit tunnel table: %w", err) - } - - if hubInfo.IPv6 != nil { - hubRule = hubInfo.IPv6.String() + "/128" - } - } - - if hubRule == "" { - return nil - } - - // Remove potential stale rule for current hub destination before adding. - deleteRule(family, hubRule) - - // Initialize rule to route SPN traffic - if err := exec.Command( - ipPath, - family, - "rule", "add", - "pref", spnSlitTunRulePriority, - "to", hubRule, - "lookup", spnSlitTunRouteTableID, - ).Run(); err != nil { - return fmt.Errorf("failed to add SPN hub policy route rule (%s): %w", hubRule, err) - } - - wc.Debug(fmt.Sprintf("IVPN: Reconciled SPN hub route rule (%s -> table %s via %s dev %s)", hubRule, spnSlitTunRouteTableID, gw.IP.String(), gw.Interface)) - - return nil -} - -// hasInterfaceIp checks if the given IP address is assigned to the specified network interface. -func hasInterfaceIp(ifName string, ip net.IP) (bool, error) { - iface, err := net.InterfaceByName(ifName) - if err != nil { - return false, err - } - - addrs, err := iface.Addrs() - if err != nil { - return false, err - } - - for _, addr := range addrs { - var currentIP net.IP - - switch v := addr.(type) { - case *net.IPNet: - currentIP = v.IP - case *net.IPAddr: - currentIP = v.IP - } - - if currentIP != nil && currentIP.Equal(ip) { - return true, nil +// clientInstalled reports whether the IVPN client is installed, either as a +// package or as a snap. These are the directories the IVPN client library +// looks for the connection info in. +func clientInstalled() bool { + for _, dir := range []string{"/etc/opt/ivpn/mutable", "/var/snap/ivpn/common"} { + _, err := os.Stat(dir) + if err == nil { + return true } } - - return false, nil + return false } diff --git a/service/interop/ivpn/hook_windows.go b/service/interop/ivpn/hook_windows.go deleted file mode 100644 index 4a4760d06..000000000 --- a/service/interop/ivpn/hook_windows.go +++ /dev/null @@ -1,32 +0,0 @@ -//go:build windows - -package ivpn - -import ( - "github.com/safing/portmaster/service/mgr" - "github.com/safing/portmaster/service/netenv" - "github.com/safing/portmaster/spn/conf" - "github.com/safing/portmaster/spn/hub" -) - -type platformSpecific struct{} - -func (i *InteropIvpn) spnConnectingHook(w *mgr.WorkerCtx, hookCtx hub.Announcement) (cancel bool, err error) { - - // Bind SPN outgoing connections to the physical (non-VPN) interface so that - // SPN hub traffic bypasses the IVPN tunnel. Without this, the OS would route - // SPN connections through the VPN interface, defeating the split-tunnel design. - // - // TODO: netenv.GetDefaultInterface() is a heuristic and may not always return - // the correct physical interface (e.g. with multiple uplinks or unusual routing). - defIf := netenv.GetDefaultInterface() - if defIf == nil { - conf.SetBindAddr(nil, nil) - } else { - conf.SetBindAddr(defIf.IPv4Address, defIf.IPv6Address) - } - - return false, nil -} -func (i *InteropIvpn) reconcileCompatibilityState(wc *mgr.WorkerCtx) { -} diff --git a/service/interop/ivpn/ivpn.go b/service/interop/ivpn/ivpn.go index e6514e9db..ae856f1b6 100644 --- a/service/interop/ivpn/ivpn.go +++ b/service/interop/ivpn/ivpn.go @@ -1,13 +1,16 @@ package ivpn import ( + "errors" "fmt" + "io/fs" "net" "sync/atomic" "time" "github.com/ivpn/desktop-app/daemon/protocol/ivpnclient" "github.com/safing/portmaster/base/info" + "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/base/notifications" "github.com/safing/portmaster/service/firewall/interception" "github.com/safing/portmaster/service/mgr" @@ -15,7 +18,6 @@ import ( "github.com/safing/portmaster/service/network" "github.com/safing/portmaster/service/network/netutils" "github.com/safing/portmaster/service/network/packet" - "github.com/safing/portmaster/spn/hub" ) const DNS_LOCKED_DESCRIPTION = "Portmaster controls all DNS resolution on this system, which prevents conflicts with IVPN's DNS settings. To let IVPN manage DNS again, remove all DNS servers from Portmaster's DNS configuration." @@ -27,7 +29,6 @@ type interopBase interface { DnsListenAddress() string DnsNameServers() []string EvtConfigChange() <-chan struct{} - GetHookSPNConnecting() *mgr.HookMgr[hub.Announcement] Interception() *interception.Interception Manager() *mgr.Manager } @@ -81,10 +82,6 @@ func (i *InteropIvpn) setStatus(status *clientStatus) { func (i *InteropIvpn) Start() error { i.connHandler = i.owner.Manager().NewWorkerMgr("ivpn client interoperability", i.connectIvpnClient, nil) - // Subscribe to SPN connecting hook to ensure SPN compatibility rules - // are applied before SPN connects to the network. - i.owner.GetHookSPNConnecting().AddHook("ivpn", i.spnConnectingHook) - firstTryChan := make(chan struct{}) i.firstTryDone.Store(&firstTryChan) @@ -136,7 +133,15 @@ func (i *InteropIvpn) connectIvpnClient(wc *mgr.WorkerCtx) error { } servicePort, _, err := ivpnclient.GetConnectionPortInfo() - if err != nil { + switch { + case errors.Is(err, fs.ErrNotExist), err != nil && !clientInstalled(): + // The IVPN client is not installed: its connection info (registry key + // or file) does not exist. This is the common case, not an error. + // On Linux the IVPN library does not wrap fs.ErrNotExist, so the + // installation is checked separately. + log.Debugf("interop/ivpn: client not installed: %s", err) + return nil + case err != nil: return err } // Save ServicePort. @@ -220,12 +225,17 @@ func (i *InteropIvpn) connectIvpnClient(wc *mgr.WorkerCtx) error { interceptionStartStopStatus := i.owner.Interception().EventStartStopState.Subscribe("ivpn", 10) defer interceptionStartStopStatus.Cancel() + // Subscribe to config changes once. EvtConfigChange creates a new + // subscription on every call, so it must not be called in the select + // below, whose channel operands are evaluated on every iteration. + configChanges := i.owner.EvtConfigChange() + done := false for !done { select { case <-interceptionStartStopStatus.Events(): i.updateIvpnClientDnsSettings(wc, client) - case <-i.owner.EvtConfigChange(): + case <-configChanges: i.updateIvpnClientDnsSettings(wc, client) i.reconcileCompatibilityState(wc) case <-wc.Done(): diff --git a/service/interop/module.go b/service/interop/module.go index e9cca47d8..9365dd286 100644 --- a/service/interop/module.go +++ b/service/interop/module.go @@ -11,7 +11,6 @@ import ( "github.com/safing/portmaster/service/interop/ivpn" "github.com/safing/portmaster/service/mgr" "github.com/safing/portmaster/service/network" - "github.com/safing/portmaster/spn/hub" ) // Interface for separate interoperability objects. @@ -26,7 +25,6 @@ type interopModule interface { type instance interface { Config() *config.Config Interception() *interception.Interception - GetHookSPNConnecting() *mgr.HookMgr[hub.Announcement] } // Module for interoperability with third-party applications @@ -66,9 +64,6 @@ func (u *Interoperability) EvtConfigChange() <-chan struct{} { func (u *Interoperability) Interception() *interception.Interception { return u.instance.Interception() } -func (u *Interoperability) GetHookSPNConnecting() *mgr.HookMgr[hub.Announcement] { - return u.instance.GetHookSPNConnecting() -} func start() error { for _, im := range module.interopModules { diff --git a/service/mgr/events.go b/service/mgr/events.go index 359f9a92e..6d3eb1342 100644 --- a/service/mgr/events.go +++ b/service/mgr/events.go @@ -1,4 +1,3 @@ -//nolint:structcheck,golint // TODO: Seems broken for generics. package mgr import ( diff --git a/service/mgr/group.go b/service/mgr/group.go index 39bd66164..8d30aeb79 100644 --- a/service/mgr/group.go +++ b/service/mgr/group.go @@ -137,7 +137,7 @@ func (g *Group) Start() error { startTime := time.Now() err := m.mgr.Do("start module "+m.mgr.name, func(_ *WorkerCtx) error { - return m.module.Start() //nolint:scopelint // Execution is synchronous. + return m.module.Start() }) if err != nil { m.mgr.Error( diff --git a/service/mgr/sleepyticker.go b/service/mgr/sleepyticker.go index ce0b20b4d..ae9de8bff 100644 --- a/service/mgr/sleepyticker.go +++ b/service/mgr/sleepyticker.go @@ -1,6 +1,9 @@ package mgr -import "time" +import ( + "sync" + "time" +) // SleepyTicker is wrapper over time.Ticker that respects the sleep mode of the module. type SleepyTicker struct { @@ -9,6 +12,8 @@ type SleepyTicker struct { sleepDuration time.Duration sleepMode bool + // lock guards sleepMode and sleepChannel. + lock sync.Mutex sleepChannel chan time.Time } @@ -26,7 +31,11 @@ func NewSleepyTicker(normalDuration time.Duration, sleepDuration time.Duration) } // Wait waits until the module is not in sleep mode and returns time.Ticker.C channel. +// If the ticker sleeps with sleepDuration == 0, the returned channel is closed when sleep mode ends. func (st *SleepyTicker) Wait() <-chan time.Time { + st.lock.Lock() + defer st.lock.Unlock() + if st.sleepMode && st.sleepDuration == 0 { return st.sleepChannel } @@ -40,19 +49,24 @@ func (st *SleepyTicker) Stop() { // SetSleep sets the sleep mode of the ticker. If enabled is true, the ticker will tick with sleepDuration. If enabled is false, the ticker will tick with normalDuration. func (st *SleepyTicker) SetSleep(enabled bool) { + st.lock.Lock() + defer st.lock.Unlock() + st.sleepMode = enabled if enabled { if st.sleepDuration > 0 { st.ticker.Reset(st.sleepDuration) - } else { - // Next call to Wait will wait until SetSleep is called with enabled == false + } else if st.sleepChannel == nil { + // Next call to Wait will wait until SetSleep is called with enabled == false. + // An existing channel is kept so that current waiters are not leaked. st.sleepChannel = make(chan time.Time) } } else { st.ticker.Reset(st.normalDuration) - if st.sleepDuration > 0 { - // Notify that we are not sleeping anymore. + if st.sleepChannel != nil { + // Notify that we are not sleeping anymore. close(st.sleepChannel) + st.sleepChannel = nil } } } diff --git a/service/mgr/sleepyticker_test.go b/service/mgr/sleepyticker_test.go index 9e2175c70..01d98901c 100644 --- a/service/mgr/sleepyticker_test.go +++ b/service/mgr/sleepyticker_test.go @@ -5,6 +5,83 @@ import ( "time" ) +func TestSleepyTickerWakeupWithoutSleepDuration(t *testing.T) { + t.Parallel() + + st := NewSleepyTicker(time.Hour, 0) + defer st.Stop() + st.SetSleep(true) + + released := make(chan struct{}) + go func() { + <-st.Wait() + close(released) + }() + time.Sleep(50 * time.Millisecond) + + st.SetSleep(false) + select { + case <-released: + case <-time.After(time.Second): + t.Fatal("waiter was not released when sleep mode ended") + } +} + +func TestSleepyTickerSetSleepNoPanic(t *testing.T) { + t.Parallel() + + // sleepDuration > 0: no channel exists, must not panic. + st := NewSleepyTicker(time.Hour, time.Hour) + defer st.Stop() + st.SetSleep(false) + st.SetSleep(true) + st.SetSleep(true) + st.SetSleep(false) + st.SetSleep(false) + + // sleepDuration == 0: double calls must not panic or leak waiters. + st = NewSleepyTicker(time.Hour, 0) + defer st.Stop() + st.SetSleep(false) + st.SetSleep(true) + ch := st.Wait() + st.SetSleep(true) // must not replace the channel the waiter holds + released := make(chan struct{}) + go func() { + <-ch + close(released) + }() + time.Sleep(50 * time.Millisecond) + st.SetSleep(false) + st.SetSleep(false) + select { + case <-released: + case <-time.After(time.Second): + t.Fatal("waiter on first channel leaked") + } +} + +func TestSleepyTickerConcurrent(t *testing.T) { + t.Parallel() + + st := NewSleepyTicker(time.Millisecond, 0) + defer st.Stop() + done := make(chan struct{}) + go func() { + defer close(done) + for i := range 200 { + st.SetSleep(i%2 == 0) + } + }() + for range 200 { + select { + case <-st.Wait(): + case <-time.After(time.Millisecond): + } + } + <-done +} + func TestSleepyTickerStop(t *testing.T) { normalDuration := 100 * time.Millisecond sleepDuration := 200 * time.Millisecond diff --git a/service/mgr/workermgr_test.go b/service/mgr/workermgr_test.go index b57447078..0fddbee9f 100644 --- a/service/mgr/workermgr_test.go +++ b/service/mgr/workermgr_test.go @@ -1,13 +1,25 @@ package mgr import ( + "os" "sync/atomic" "testing" "time" ) +// skipTimingSensitiveOnCI skips tests that assert wall-clock scheduling +// precision (±5 %). On shared CI runners with several workflows in parallel +// these fail sporadically without indicating a bug; they still run locally. +func skipTimingSensitiveOnCI(t *testing.T) { + t.Helper() + if os.Getenv("CI") != "" { + t.Skip("timing-sensitive test skipped on CI runner (CI env set)") + } +} + func TestWorkerMgrDelay(t *testing.T) { t.Parallel() + skipTimingSensitiveOnCI(t) m := New("DelayTest") @@ -21,20 +33,23 @@ func TestWorkerMgrDelay(t *testing.T) { }, nil).Delay(1 * time.Second) // Check if value is set after 1 second and not before or after. - iterations := 0 + // Measure the elapsed time instead of counting sleeps: on a busy machine, + // sleeps take longer than requested, so fewer of them fit into a second. + started := time.Now() for !value.Load() { - iterations++ time.Sleep(10 * time.Millisecond) } + elapsed := time.Since(started) - // 5% difference is acceptable since time.Sleep can't be perfect and it may very on different computers. - if iterations < 95 || iterations > 105 { - t.Errorf("WorkerMgr did not delay for a whole second it=%d", iterations) + // Some difference is acceptable since timers can't be perfect and it may vary on different computers. + if elapsed < 950*time.Millisecond || elapsed > 1150*time.Millisecond { + t.Errorf("WorkerMgr did not delay for a whole second: %s", elapsed) } } func TestWorkerMgrRepeat(t *testing.T) { t.Parallel() + skipTimingSensitiveOnCI(t) m := New("RepeatTest") @@ -47,26 +62,12 @@ func TestWorkerMgrRepeat(t *testing.T) { return nil }, nil).Repeat(100 * time.Millisecond) - // Check 10 consecutive runs they should be delayed for around 100 milliseconds each. - for range 10 { - iterations := 0 - for !value.Load() { - iterations++ - time.Sleep(10 * time.Millisecond) - } - - // 10% difference is acceptable at this scale since time.Sleep can't be perfect and it may very on different computers. - if iterations < 9 || iterations > 11 { - t.Errorf("Worker was not delayed for a 100 milliseconds it=%d", iterations) - return - } - // Reset value - value.Store(false) - } + checkRepeatInterval(t, &value) } func TestWorkerMgrDelayAndRepeat(t *testing.T) { //nolint:dupl t.Parallel() + skipTimingSensitiveOnCI(t) m := New("DelayAndRepeatTest") @@ -79,40 +80,28 @@ func TestWorkerMgrDelayAndRepeat(t *testing.T) { //nolint:dupl return nil }, nil).Delay(1 * time.Second).Repeat(100 * time.Millisecond) - iterations := 0 + // Measure the elapsed time instead of counting sleeps: on a busy machine, + // sleeps take longer than requested, so fewer of them fit into a second. + started := time.Now() for !value.Load() { - iterations++ time.Sleep(10 * time.Millisecond) } + elapsed := time.Since(started) - // 5% difference is acceptable since time.Sleep can't be perfect and it may very on different computers. - if iterations < 95 || iterations > 105 { - t.Errorf("WorkerMgr did not delay for a whole second it=%d", iterations) + // Some difference is acceptable since timers can't be perfect and it may vary on different computers. + if elapsed < 950*time.Millisecond || elapsed > 1150*time.Millisecond { + t.Errorf("WorkerMgr did not delay for a whole second: %s", elapsed) } // Reset value value.Store(false) - // Check 10 consecutive runs they should be delayed for around 100 milliseconds each. - for range 10 { - iterations = 0 - for !value.Load() { - iterations++ - time.Sleep(10 * time.Millisecond) - } - - // 10% difference is acceptable at this scale since time.Sleep can't be perfect and it may very on different computers. - if iterations < 9 || iterations > 11 { - t.Errorf("Worker was not delayed for a 100 milliseconds it=%d", iterations) - return - } - // Reset value - value.Store(false) - } + checkRepeatInterval(t, &value) } func TestWorkerMgrRepeatAndDelay(t *testing.T) { //nolint:dupl t.Parallel() + skipTimingSensitiveOnCI(t) m := New("RepeatAndDelayTest") @@ -125,33 +114,48 @@ func TestWorkerMgrRepeatAndDelay(t *testing.T) { //nolint:dupl return nil }, nil).Repeat(100 * time.Millisecond).Delay(1 * time.Second) - iterations := 0 + // Measure the elapsed time instead of counting sleeps: on a busy machine, + // sleeps take longer than requested, so fewer of them fit into a second. + started := time.Now() for !value.Load() { - iterations++ time.Sleep(10 * time.Millisecond) } + elapsed := time.Since(started) - // 5% difference is acceptable since time.Sleep can't be perfect and it may very on different computers. - if iterations < 95 || iterations > 105 { - t.Errorf("WorkerMgr did not delay for a whole second it=%d", iterations) + // Some difference is acceptable since timers can't be perfect and it may vary on different computers. + if elapsed < 950*time.Millisecond || elapsed > 1150*time.Millisecond { + t.Errorf("WorkerMgr did not delay for a whole second: %s", elapsed) } // Reset value value.Store(false) - // Check 10 consecutive runs they should be delayed for around 100 milliseconds each. + checkRepeatInterval(t, &value) +} + +// checkRepeatInterval checks that 10 consecutive runs of a worker repeating +// every 100 milliseconds take around one second in total. It measures the +// elapsed time instead of counting sleeps, as sleeps take longer than +// requested on a busy machine. The total is checked instead of each run, as a +// single run may be late under load while the following one is on time. +func checkRepeatInterval(t *testing.T, value *atomic.Bool) { + t.Helper() + + // Wait for the first repeated run to align with the repeat schedule. + for !value.Load() { + time.Sleep(time.Millisecond) + } + value.Store(false) + + started := time.Now() for range 10 { - iterations := 0 for !value.Load() { - iterations++ - time.Sleep(10 * time.Millisecond) + time.Sleep(time.Millisecond) } - - // 10% difference is acceptable at this scale since time.Sleep can't be perfect and it may very on different computers. - if iterations < 9 || iterations > 11 { - t.Errorf("Worker was not delayed for a 100 milliseconds it=%d", iterations) - return - } - // Reset value value.Store(false) } + elapsed := time.Since(started) + + if elapsed < 900*time.Millisecond || elapsed > 1300*time.Millisecond { + t.Errorf("10 repeated runs did not take around one second: %s", elapsed) + } } diff --git a/service/nameserver/failing.go b/service/nameserver/failing.go index 2637a61f8..ec6329db1 100644 --- a/service/nameserver/failing.go +++ b/service/nameserver/failing.go @@ -72,7 +72,10 @@ func checkIfQueryIsFailing(q *resolver.Query) (failingUntil *time.Time, failingE } // Return failing error and until when it's valid. - return &failing.Until, failing.Err + // Copy the time while holding the lock: returning a pointer into the shared + // struct would let callers read it after unlock, racing with addFailingQuery. + until := failing.Until + return &until, failing.Err } func addFailingQuery(q *resolver.Query, err error) { diff --git a/service/nameserver/failing_test.go b/service/nameserver/failing_test.go new file mode 100644 index 000000000..3d672ad31 --- /dev/null +++ b/service/nameserver/failing_test.go @@ -0,0 +1,45 @@ +package nameserver + +import ( + "errors" + "sync" + "testing" + "time" + + "github.com/miekg/dns" + + "github.com/safing/portmaster/service/resolver" +) + +func TestCheckIfQueryIsFailingNoRace(t *testing.T) { //nolint:paralleltest // Replaces the package-level failing queries map. + q := &resolver.Query{FQDN: "failing.example.com.", QType: dns.Type(dns.TypeA)} + failErr := errors.New("failed") //nolint:err113 // Test error. + + failingQueriesLock.Lock() + failingQueries = make(map[string]*failingQuery) + failingQueriesLock.Unlock() + addFailingQuery(q, failErr) + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for range 1000 { + addFailingQuery(q, failErr) + } + }() + go func() { + defer wg.Done() + for range 1000 { + until, err := checkIfQueryIsFailing(q) + if until != nil { + // Read outside of any lock, as the real caller does. + _ = until.After(time.Now()) + if err == nil { + t.Error("expected error with failing until") + } + } + } + }() + wg.Wait() +} diff --git a/service/nameserver/handle_test.go b/service/nameserver/handle_test.go new file mode 100644 index 000000000..5ac2b711b --- /dev/null +++ b/service/nameserver/handle_test.go @@ -0,0 +1,162 @@ +package nameserver + +import ( + "context" + "net" + "strings" + "sync" + "testing" + + vm "github.com/VictoriaMetrics/metrics" + "github.com/miekg/dns" + + "github.com/safing/portmaster/base/metrics" + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/nameserver/nsutil" + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/resolver" +) + +var registerTestMetricsOnce sync.Once + +func setupHandleRequestTest(t *testing.T) { + t.Helper() + + registerTestMetricsOnce.Do(func() { + // The metrics module is not running, so use unregistered metrics. + set := vm.NewSet() + requestsHistogram = &metrics.Histogram{Histogram: set.NewHistogram("test_duration_seconds")} + totalHandledRequests = &metrics.Counter{Counter: set.NewCounter("test_total")} + hostname = "testhost." + }) +} + +type tcpResponseWriter struct { + testResponseWriter +} + +func (w *tcpResponseWriter) RemoteAddr() net.Addr { + return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 40000} +} + +// TestHandleRequestEarlyReplies tests the request handling paths that reply +// before any connection or resolver is involved. +func TestHandleRequestEarlyReplies(t *testing.T) { + t.Parallel() + setupHandleRequestTest(t) + + q := func(name string, qtype uint16) dns.Question { + return dns.Question{Name: name, Qtype: qtype, Qclass: dns.ClassINET} + } + + tests := []struct { + name string + questions []dns.Question + tcp bool + rcode int + answers int + }{ + {name: "no question", rcode: dns.RcodeRefused}, + {name: "multiple questions", questions: []dns.Question{q("a.example.", dns.TypeA), q("b.example.", dns.TypeA)}, rcode: dns.RcodeRefused}, + {name: "chaos class", questions: []dns.Question{{Name: "version.bind.", Qtype: dns.TypeTXT, Qclass: dns.ClassCHAOS}}, rcode: dns.RcodeRefused}, + {name: "any class", questions: []dns.Question{{Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassANY}}, rcode: dns.RcodeRefused}, + {name: "tcp", questions: []dns.Question{q("example.com.", dns.TypeA)}, tcp: true, rcode: dns.RcodeRefused}, + {name: "localhost A", questions: []dns.Question{q("localhost.", dns.TypeA)}, rcode: dns.RcodeSuccess, answers: 1}, + {name: "localhost mixed case AAAA", questions: []dns.Question{q("Foo.LocalHost.", dns.TypeAAAA)}, rcode: dns.RcodeSuccess, answers: 1}, + {name: "hostname", questions: []dns.Question{q("testhost.", dns.TypeA)}, rcode: dns.RcodeSuccess, answers: 1}, + {name: "localhost MX", questions: []dns.Question{q("localhost.", dns.TypeMX)}, rcode: dns.RcodeNameError}, + {name: "localhost with odd characters", questions: []dns.Question{q(`we\ ird\"\;.localhost.`, dns.TypeA)}, rcode: dns.RcodeSuccess, answers: 1}, + {name: "invalid domain", questions: []dns.Question{q(`in\ valid.example.`, dns.TypeA)}, rcode: dns.RcodeRefused}, + {name: "empty name", questions: []dns.Question{q("", dns.TypeA)}, rcode: dns.RcodeRefused}, + {name: "too long name", questions: []dns.Question{q(strings.Repeat("a.", 200), dns.TypeA)}, rcode: dns.RcodeRefused}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + request := new(dns.Msg) + request.Id = 1234 + request.RecursionDesired = true + request.Question = tc.questions + request.SetEdns0(4096, false) + + var w dns.ResponseWriter + rw := &testResponseWriter{} + w = rw + if tc.tcp { + tw := &tcpResponseWriter{} + rw = &tw.testResponseWriter + w = tw + } + + err := handleRequest(context.Background(), w, request) + if err != nil { + t.Fatalf("handleRequest failed: %s", err) + } + if len(rw.written) != 1 { + t.Fatalf("expected one reply, got %d", len(rw.written)) + } + reply := rw.written[0] + if reply.Id != request.Id || !reply.Response || reply.Rcode != tc.rcode || len(reply.Answer) != tc.answers { + t.Fatalf("unexpected reply: %s", reply) + } + for _, rr := range reply.Answer { + if rr.Header().Name != tc.questions[0].Name { + t.Fatalf("answer name %q does not match question %q", rr.Header().Name, tc.questions[0].Name) + } + } + _, err = reply.Pack() + if err != nil { + t.Fatalf("failed to pack reply: %s", err) + } + }) + } +} + +// TestReplyResolvedWithoutProfile tests that a resolved response is answered +// with a server failure when the firewall cannot decide on it, because the +// process has no profile. This happens when the profile could not be loaded and +// the connection was accepted without a profile, eg. because the privacy +// filter is disabled or an external verdict handler accepted it. +func TestReplyResolvedWithoutProfile(t *testing.T) { + t.Parallel() + setupHandleRequestTest(t) + + for _, nonStandard := range []bool{false, true} { + request := new(dns.Msg) + request.SetQuestion("Example.org.", dns.TypeA) + w := &testResponseWriter{} + reply := func(responder nsutil.Responder, rrProviders ...nsutil.RRProvider) error { + return sendResponse(context.Background(), w, request, responder, rrProviders...) + } + + // Connection without process and profile, accepted by the privacy filter. + conn := &network.Connection{ + Entity: &intel.Entity{}, + Verdict: network.VerdictAccept, + } + q := &resolver.Query{FQDN: "example.org.", QType: dns.Type(dns.TypeA)} + rrCache := &resolver.RRCache{ + Domain: q.FQDN, + Question: q.QType, + RCode: dns.RcodeSuccess, + Answer: []dns.RR{&dns.A{ + Hdr: dns.RR_Header{Name: q.FQDN, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, + A: net.IPv4(192, 0, 2, 1), + }}, + Resolver: &resolver.ResolverInfo{Type: resolver.ServerTypeDNS}, + } + + sent, err := replyResolved(context.Background(), reply, conn, q, rrCache, "Example.org.", nonStandard) + if err != nil { + t.Fatalf("replyResolved failed: %s", err) + } + if sent != nil { + t.Fatalf("expected no response to be attached to the connection, got %+v", sent) + } + if len(w.written) != 1 || w.written[0].Rcode != dns.RcodeServerFailure { + t.Fatalf("expected one server failure reply, got %v", w.written) + } + } +} diff --git a/service/nameserver/module.go b/service/nameserver/module.go index 99477d2fe..3fadb4c9d 100644 --- a/service/nameserver/module.go +++ b/service/nameserver/module.go @@ -283,12 +283,14 @@ func stop() error { defer cancel() if stopListener1 != nil { - if err := stopListener1(ctx); err != nil { + err := stopListener1(ctx) + if err != nil { log.Warningf("nameserver: failed to stop listener1: %s", err) } } if stopListener2 != nil { - if err := stopListener2(ctx); err != nil { + err := stopListener2(ctx) + if err != nil { log.Warningf("nameserver: failed to stop listener2: %s", err) } } diff --git a/service/nameserver/nameserver.go b/service/nameserver/nameserver.go index f92b448d5..5e61fc24a 100644 --- a/service/nameserver/nameserver.go +++ b/service/nameserver/nameserver.go @@ -319,14 +319,38 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, request *dns.Msg) } - // Check with firewall again after resolving. + // Check with firewall again after resolving and reply. + rrCache, err = replyResolved(ctx, reply, conn, q, rrCache, originalQuestion.Name, nonStandardQuestionFormat) + return err +} + +// replyResolved checks the resolved response with the firewall and replies to +// the request. It returns the response that was sent, if any, so that it can be +// attached to the connection. +func replyResolved( + ctx context.Context, + reply func(responder nsutil.Responder, rrProviders ...nsutil.RRProvider) error, + conn *network.Connection, + q *resolver.Query, + rrCache *resolver.RRCache, + originalName string, + nonStandardQuestionFormat bool, +) (*resolver.RRCache, error) { + tracer := log.Tracer(ctx) + tracer.Trace("nameserver: deciding on resolved dns") rrCache = firewall.FilterResolvedDNS(ctx, conn, q, rrCache) + if rrCache == nil { + // The firewall could not decide on the response, eg. because the + // process has no profile. + tracer.Warningf("nameserver: firewall returned no response for %s", q.ID()) + return nil, reply(nsutil.ServerFailure(internalError + "failed to filter response")) + } // Check again if there is a responder from the firewall. if responder, ok := conn.Reason.Context.(nsutil.Responder); ok { tracer.Infof("nameserver: handing over request for %s to special filter responder: %s", q.ID(), conn.Reason.Msg) - return reply(responder) + return rrCache, reply(responder) } // Check if there is a Verdict to act upon. @@ -339,12 +363,12 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, request *dns.Msg) conn.Process(), conn.Reason.Msg, ) - return reply(conn, conn, rrCache) + return rrCache, reply(conn, conn, rrCache) } // Revert back to non-standard question format, if we had to convert. if nonStandardQuestionFormat { - rrCache.ReplaceAnswerNames(originalQuestion.Name) + rrCache.ReplaceAnswerNames(originalName) } // Reply with successful response. @@ -360,7 +384,7 @@ func handleRequest(ctx context.Context, w dns.ResponseWriter, request *dns.Msg) q.ID(), conn.Process(), ) - return reply(rrCache, conn, rrCache) + return rrCache, reply(rrCache, conn, rrCache) } func checkAlternativeCaches(ctx context.Context, q *resolver.Query) *resolver.RRCache { diff --git a/service/nameserver/nsutil/nsutil.go b/service/nameserver/nsutil/nsutil.go index 0abd629b0..5e1406b23 100644 --- a/service/nameserver/nsutil/nsutil.go +++ b/service/nameserver/nsutil/nsutil.go @@ -164,6 +164,11 @@ func ServerFailure(msgs ...string) ResponderFunc { // MakeMessageRecord creates an informational resource record that can be added // to the extra section of a reply. func MakeMessageRecord(level log.Severity, msg string) (dns.RR, error) { //nolint:interfacer + // Build the record directly if parsing it would not change the message. + if rr := makePlainMessageRecord(level, msg); rr != nil { + return rr, nil + } + rr, err := dns.NewRR(fmt.Sprintf( `%s.portmaster. 0 IN TXT "%s"`, strings.ToLower(level.String()), @@ -178,6 +183,49 @@ func MakeMessageRecord(level log.Severity, msg string) (dns.RR, error) { //nolin return rr, nil } +// maxTXTStringLength is the maximum length of a single TXT character string. +const maxTXTStringLength = 255 + +// makePlainMessageRecord creates the same record as parsing the zone file +// line in MakeMessageRecord would, without the cost of the zone parser. It +// only handles messages of printable ASCII characters without quotes and +// backslashes, which the parser takes over unchanged, and level names of +// lower case letters only. For any other input it returns nil. +func makePlainMessageRecord(level log.Severity, msg string) *dns.TXT { + levelName := strings.ToLower(level.String()) + if levelName == "" { + return nil + } + for i := range len(levelName) { + if levelName[i] < 'a' || levelName[i] > 'z' { + return nil + } + } + for i := range len(msg) { + if msg[i] < ' ' || msg[i] > '~' || msg[i] == '"' || msg[i] == '\\' { + return nil + } + } + + // Like the parser, split the message into strings of at most 255 bytes. + txt := make([]string, 0, len(msg)/maxTXTStringLength+1) + for len(msg) > maxTXTStringLength { + txt = append(txt, msg[:maxTXTStringLength]) + msg = msg[maxTXTStringLength:] + } + txt = append(txt, msg) + + return &dns.TXT{ + Hdr: dns.RR_Header{ + Name: levelName + ".portmaster.", + Rrtype: dns.TypeTXT, + Class: dns.ClassINET, + Ttl: 0, + }, + Txt: txt, + } +} + // AddMessagesToReply creates information resource records using // MakeMessageRecord and immediately adds them to the extra section of the given // reply. If an error occurs, the resource record will not be added, and the diff --git a/service/nameserver/nsutil/nsutil_fuzz_test.go b/service/nameserver/nsutil/nsutil_fuzz_test.go new file mode 100644 index 000000000..8f8e277b0 --- /dev/null +++ b/service/nameserver/nsutil/nsutil_fuzz_test.go @@ -0,0 +1,135 @@ +package nsutil + +import ( + "context" + "strings" + "testing" + + "github.com/miekg/dns" + + "github.com/safing/portmaster/base/log" +) + +// requestSeeds returns wire-format DNS requests covering common and unusual +// question shapes. +func requestSeeds(tb testing.TB) [][]byte { + tb.Helper() + + var msgs []*dns.Msg + add := func(name string, qtype uint16) *dns.Msg { + m := new(dns.Msg).SetQuestion(name, qtype) + msgs = append(msgs, m) + return m + } + + add("example.com.", dns.TypeA) + add("Example.COM.", dns.TypeAAAA) + add("localhost.", dns.TypeA) + add("foo.localhost.", dns.TypeAAAA) + add("example.com.", dns.TypeTXT) + add(".", dns.TypeNS) + add(`we\ ird\;na\"me\(\).localhost.`, dns.TypeA) + add(`\000\255.localhost.`, dns.TypeAAAA) + add(strings.Repeat("a", 63)+"."+strings.Repeat("b", 63)+"."+strings.Repeat("c", 63)+"."+strings.Repeat("d", 61)+".", dns.TypeA) + add("edns.example.", dns.TypeA).SetEdns0(4096, true) + m := add("multi.example.", dns.TypeA) + m.Question = append(m.Question, dns.Question{Name: "second.example.", Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}) + m = add("chaos.example.", dns.TypeA) + m.Question[0].Qclass = dns.ClassCHAOS + m = add("noquestion.example.", dns.TypeA) + m.Question = nil + + seeds := make([][]byte, 0, len(msgs)) + for _, m := range msgs { + data, err := m.Pack() + if err != nil { + tb.Fatalf("failed to pack seed: %s", err) + } + seeds = append(seeds, data) + } + return seeds +} + +func FuzzResponders(f *testing.F) { + for _, seed := range requestSeeds(f) { + f.Add(seed, "message") + } + + ctx := context.Background() + + f.Fuzz(func(t *testing.T, data []byte, msg string) { + request := new(dns.Msg) + err := request.Unpack(data) + if err != nil { + return + } + + responders := map[string]ResponderFunc{ + "block": BlockIP(msg), + "zero": ZeroIP(msg), + "localhost": Localhost(msg), + "refused": Refused(msg), + "servfail": ServerFailure(msg), + // NxDomain is not fuzzed, as it sleeps. + } + for name, responder := range responders { + reply := responder.ReplyWithDNS(ctx, request) + if reply == nil { + t.Fatalf("%s: nil reply", name) + } + if reply.Id != request.Id || !reply.Response { + t.Fatalf("%s: reply does not match request", name) + } + + // Every answer must be for one of the questions. + for _, rr := range reply.Answer { + found := false + for _, q := range request.Question { + if rr.Header().Name == q.Name && rr.Header().Rrtype == q.Qtype { + found = true + break + } + } + if !found { + t.Fatalf("%s: answer %s does not match any question %v", name, rr, request.Question) + } + } + + _, err := reply.Pack() + if err != nil { + t.Fatalf("%s: failed to pack reply: %s", name, err) + } + } + }) +} + +func FuzzMakeMessageRecord(f *testing.F) { + for _, seed := range []string{ + "", + "internal error: failed to check if request is local", + `quote " inside`, + `back\slash`, + "new\nline", + "semi;colon", + strings.Repeat("x", 300), + } { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, msg string) { + rr, err := MakeMessageRecord(log.InfoLevel, msg) + if err != nil { + return + } + if rr.Header().Name != strings.ToLower(log.InfoLevel.String())+".portmaster." || rr.Header().Rrtype != dns.TypeTXT { + t.Fatalf("message %q produced unexpected record %s", msg, rr) + } + + reply := new(dns.Msg) + AddMessagesToReply(context.Background(), reply, log.InfoLevel, msg) + _, err = reply.Pack() + if err != nil { + t.Fatalf("failed to pack reply with message %q: %s", msg, err) + } + }) +} diff --git a/service/nameserver/nsutil/nsutil_test.go b/service/nameserver/nsutil/nsutil_test.go new file mode 100644 index 000000000..cf35e5748 --- /dev/null +++ b/service/nameserver/nsutil/nsutil_test.go @@ -0,0 +1,107 @@ +package nsutil + +import ( + "fmt" + "reflect" + "strings" + "testing" + + "github.com/miekg/dns" + + "github.com/safing/portmaster/base/log" +) + +// parseMessageRecord creates the message record with the zone parser, as +// MakeMessageRecord does for messages that makePlainMessageRecord does not +// handle. +func parseMessageRecord(level log.Severity, msg string) (dns.RR, error) { + return dns.NewRR(fmt.Sprintf( + `%s.portmaster. 0 IN TXT "%s"`, + strings.ToLower(level.String()), + msg, + )) +} + +func checkPlainMessageRecord(t *testing.T, level log.Severity, msg string) { + t.Helper() + + plain := makePlainMessageRecord(level, msg) + if plain == nil { + return + } + parsed, err := parseMessageRecord(level, msg) + if err != nil { + t.Fatalf("message %q: parser failed, but plain record was created: %s", msg, err) + } + if !reflect.DeepEqual(dns.RR(plain), parsed) { + t.Fatalf("message %q: plain record %#v differs from parsed record %#v", msg, plain, parsed) + } +} + +func TestMakePlainMessageRecord(t *testing.T) { + t.Parallel() + + var printable strings.Builder + for c := byte(' '); c <= '~'; c++ { + if c != '"' && c != '\\' { + printable.WriteByte(c) + } + } + + lengths := []int{1, 254, 255, 256, 509, 510, 511, 765, 1000, 4096, 70000} + msgs := make([]string, 0, 7+len(lengths)) + msgs = append(msgs, + "", + "served from cache, resolved by Quad9 (dot://9.9.9.9:853#config)", + "record valid for 59m59s", + "internal error: failed to check if request is local", + "semi;colon (parens) $dollar @at", + " leading and trailing spaces ", + printable.String(), + ) + for _, length := range lengths { + msgs = append(msgs, strings.Repeat(printable.String(), length/printable.Len()+1)[:length]) + } + + levels := []log.Severity{ + log.TraceLevel, log.DebugLevel, log.InfoLevel, log.WarningLevel, + log.ErrorLevel, log.CriticalLevel, log.Severity(255), + } + for _, level := range levels { + for _, msg := range msgs { + if makePlainMessageRecord(level, msg) == nil { + t.Fatalf("message %q at level %s: expected plain record", msg, level) + } + checkPlainMessageRecord(t, level, msg) + } + } + + // Messages the parser changes or rejects must use the parser. + for _, msg := range []string{`quote " in message`, `back\slash`, `\065`, "new\nline", "tab\tchar", "umlaut ä", "nul\x00"} { + if makePlainMessageRecord(log.InfoLevel, msg) != nil { + t.Fatalf("message %q: expected no plain record", msg) + } + } +} + +func FuzzMakePlainMessageRecord(f *testing.F) { + for _, seed := range []string{"", "message", `quote "seed"`, strings.Repeat("x", 300)} { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, msg string) { + checkPlainMessageRecord(t, log.InfoLevel, msg) + }) +} + +func BenchmarkMakeMessageRecord(b *testing.B) { + msg := "served from cache, resolved by Quad9 (dot://9.9.9.9:853#config)" + + b.ReportAllocs() + for b.Loop() { + _, err := MakeMessageRecord(log.InfoLevel, msg) + if err != nil { + b.Fatal(err) + } + } +} diff --git a/service/nameserver/response.go b/service/nameserver/response.go index c7fe196e7..8438d9041 100644 --- a/service/nameserver/response.go +++ b/service/nameserver/response.go @@ -64,9 +64,10 @@ func writeDNSResponse(ctx context.Context, w dns.ResponseWriter, m *dns.Msg) (er log.Tracer(ctx).Tracef("nameserver: retrying to write dns message without extra section, error was: %s", err) m.Extra = nil noExtraErr := w.WriteMsg(m) - if noExtraErr == nil { - return fmt.Errorf("failed to write dns message without extra section: %w", err) + if noExtraErr != nil { + return fmt.Errorf("failed to write dns message without extra section: %w (with extra section: %w)", noExtraErr, err) } + return nil } - return + return nil } diff --git a/service/nameserver/response_test.go b/service/nameserver/response_test.go new file mode 100644 index 000000000..24b59dcbb --- /dev/null +++ b/service/nameserver/response_test.go @@ -0,0 +1,93 @@ +package nameserver + +import ( + "context" + "errors" + "net" + "testing" + + "github.com/miekg/dns" + + "github.com/safing/portmaster/service/nameserver/nsutil" +) + +var errTestWrite = errors.New("test write error") + +// testResponseWriter is a dns.ResponseWriter that fails the first failWrites +// writes and records every successfully written message. +type testResponseWriter struct { + failWrites int + written []*dns.Msg +} + +func (w *testResponseWriter) LocalAddr() net.Addr { + return &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 53} +} + +func (w *testResponseWriter) RemoteAddr() net.Addr { + return &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 40000} +} + +func (w *testResponseWriter) WriteMsg(m *dns.Msg) error { + if w.failWrites > 0 { + w.failWrites-- + return errTestWrite + } + w.written = append(w.written, m.Copy()) + return nil +} + +func (w *testResponseWriter) Write([]byte) (int, error) { return 0, errTestWrite } +func (w *testResponseWriter) Close() error { return nil } +func (w *testResponseWriter) TsigStatus() error { return nil } +func (w *testResponseWriter) TsigTimersOnly(bool) {} +func (w *testResponseWriter) Hijack() {} + +func TestWriteDNSResponse(t *testing.T) { + t.Parallel() + + newReply := func() *dns.Msg { + reply := new(dns.Msg).SetRcode(new(dns.Msg).SetQuestion("example.com.", dns.TypeA), dns.RcodeRefused) + nsutil.AddMessagesToReply(context.Background(), reply, 0, "some info") + return reply + } + + t.Run("first write succeeds", func(t *testing.T) { + t.Parallel() + + w := &testResponseWriter{} + err := writeDNSResponse(context.Background(), w, newReply()) + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + if len(w.written) != 1 || len(w.written[0].Extra) == 0 { + t.Fatalf("expected one reply with extra section, got %v", w.written) + } + }) + + t.Run("retry without extra section succeeds", func(t *testing.T) { + t.Parallel() + + w := &testResponseWriter{failWrites: 1} + err := writeDNSResponse(context.Background(), w, newReply()) + if err != nil { + t.Fatalf("reply was sent without extra section, but an error was returned: %s", err) + } + if len(w.written) != 1 || len(w.written[0].Extra) != 0 { + t.Fatalf("expected one reply without extra section, got %v", w.written) + } + }) + + t.Run("both writes fail", func(t *testing.T) { + t.Parallel() + + w := &testResponseWriter{failWrites: 2} + err := writeDNSResponse(context.Background(), w, newReply()) + if !errors.Is(err, errTestWrite) { + t.Fatalf("expected write error, got %v", err) + } + if len(w.written) != 0 { + t.Fatalf("expected no reply, got %v", w.written) + } + }) +} diff --git a/service/netenv/addresses_refresh_test.go b/service/netenv/addresses_refresh_test.go index a7c8bb3b5..2c2a77c28 100644 --- a/service/netenv/addresses_refresh_test.go +++ b/service/netenv/addresses_refresh_test.go @@ -76,7 +76,8 @@ func TestMyNetworksRefreshIsShared(t *testing.T) { //nolint:paralleltest // Repl } // The result of the shared call is used. - if mine, err := IsMyIP(newNet.IP); err != nil || !mine { + mine, err := IsMyIP(newNet.IP) + if err != nil || !mine { t.Fatalf("IP of the refreshed network: mine=%v err=%v", mine, err) } } @@ -91,10 +92,12 @@ func TestMyNetworksRefreshIsThrottledFromEnd(t *testing.T) { //nolint:parallelte // A call that takes longer than the throttle time is not followed by the // next one at once. - if err := refreshMyNetworks(); err != nil { + err := refreshMyNetworks() + if err != nil { t.Fatalf("refresh failed: %s", err) } - if err := refreshMyNetworks(); err != nil { + err = refreshMyNetworks() + if err != nil { t.Fatalf("refresh failed: %s", err) } if n := calls.Load(); n != 1 { @@ -109,13 +112,15 @@ func TestMyNetworksRefreshErrorIsRetried(t *testing.T) { //nolint:paralleltest / return nil, errTestRefresh }) - if err := refreshMyNetworks(); !errors.Is(err, errTestRefresh) { + err := refreshMyNetworks() + if !errors.Is(err, errTestRefresh) { t.Fatalf("got error %v, want %v", err, errTestRefresh) } // Within the throttle time, the previous error is returned without a new // OS call. - if err := refreshMyNetworks(); !errors.Is(err, errTestRefresh) { + err = refreshMyNetworks() + if !errors.Is(err, errTestRefresh) { t.Fatalf("got error %v, want %v", err, errTestRefresh) } if n := calls.Load(); n != 1 { @@ -144,7 +149,8 @@ func TestMyNetworksChangeDuringRefreshIsKept(t *testing.T) { //nolint:parallelte <-entered networkChangedBroadcastFlag.NotifyAndReset() close(unblock) - if err := <-done; err != nil { + err := <-done + if err != nil { t.Fatalf("refresh failed: %s", err) } @@ -189,7 +195,8 @@ func TestMyNetworksCallersWaitForRefreshAfterChange(t *testing.T) { //nolint:par if localNet := <-result; localNet == nil { t.Fatal("caller did not get the new networks") } - if err := <-done; err != nil { + err := <-done + if err != nil { t.Fatalf("refresh failed: %s", err) } } diff --git a/service/netenv/location_default.go b/service/netenv/location_default.go index c1dead09c..3d9a9366f 100644 --- a/service/netenv/location_default.go +++ b/service/netenv/location_default.go @@ -4,6 +4,6 @@ package netenv import "net" -func newICMPListener(_ string) (net.PacketConn, error) { //nolint:unused,deadcode // TODO: clean with Windows code later. +func newICMPListener(_ string) (net.PacketConn, error) { //nolint:unused // TODO: clean with Windows code later. return net.ListenPacket("ip4:icmp", "0.0.0.0") } diff --git a/service/netenv/location_windows.go b/service/netenv/location_windows.go index 92d342916..1880b7ccd 100644 --- a/service/netenv/location_windows.go +++ b/service/netenv/location_windows.go @@ -10,7 +10,6 @@ import ( ) // Windows specific constants for the WSAIoctl interface. -//nolint:golint,stylecheck const ( SIO_RCVALL = syscall.IOC_IN | syscall.IOC_VENDOR | 1 diff --git a/service/netenv/online-status.go b/service/netenv/online-status.go index 2d129ab89..195ffcd13 100644 --- a/service/netenv/online-status.go +++ b/service/netenv/online-status.go @@ -7,6 +7,7 @@ import ( "net" "net/http" "net/url" + "slices" "sync" "sync/atomic" "time" @@ -40,11 +41,15 @@ var ( // IP address -> 100.127.247.245 is a special ip used by the android VPN service. Must be ignored during online check. IgnoreIPsInOnlineStatusCheck = []net.IP{net.IPv4(100, 127, 247, 245)} - DNSTestDomain = "online-check.safing.io." - DNSTestExpectedIP = net.IPv4(0, 65, 67, 75) // Ascii: \0ACK - DNSTestQueryFunc func(ctx context.Context, fdqn string) (ips []net.IP, ok bool, err error) + // DNSTestDomain is resolved to check whether DNS works. It is a well-known + // name with fixed addresses of a public DNS provider (Cloudflare, also one + // of the default resolvers), so that the check does not contact a server of + // its own and no additional party learns when the check runs. + DNSTestDomain = "one.one.one.one." + // DNSTestExpectedIPs are the IPv4 addresses DNSTestDomain resolves to. + DNSTestExpectedIPs = []net.IP{net.IPv4(1, 1, 1, 1), net.IPv4(1, 0, 0, 1)} + DNSTestQueryFunc func(ctx context.Context, fdqn string) (ips []net.IP, ok bool, err error) - ConnectedToSPN = abool.New() ConnectedToDNS = abool.New() // SpecialCaptivePortalDomain is the domain name used to point to the detected captive portal IP @@ -147,10 +152,22 @@ var ( onlineStatus *int32 onlineStatusQuickCheck = abool.NewBool(false) - onlineStatusInvestigationTrigger = make(chan struct{}, 1) - onlineStatusInvestigationInProgress = abool.NewBool(false) - onlineStatusInvestigationWg sync.WaitGroup - onlineStatusNotification *notifications.Notification + onlineStatusInvestigationTrigger = make(chan struct{}, 1) + onlineStatusNotification *notifications.Notification + + // investigationLock guards the investigation bookkeeping below. + investigationLock sync.Mutex + // investigationsStarted and investigationsCompleted count the investigations + // of the monitor worker. An investigation counts as started before its + // checks run, so everything it observes is newer than any caller that saw + // the counter before. + investigationsStarted uint64 + investigationsCompleted uint64 + // investigationDone is closed and replaced whenever an investigation + // completes or the monitor stops. + investigationDone = make(chan struct{}) + // investigationMonitorRunning is set while the monitor worker is running. + investigationMonitorRunning bool captivePortal = &CaptivePortal{} captivePortalLock sync.Mutex @@ -180,15 +197,65 @@ func GetOnlineStatus() OnlineStatus { } // CheckAndGetOnlineStatus triggers a new online status check and returns the result. +// It waits for an investigation that starts after the call to complete. +// If the online status monitor is not running (or stops meanwhile), it does +// not wait and returns the current status. func CheckAndGetOnlineStatus() OnlineStatus { + // An investigation that is already running may have started before this + // call, so wait for the one after it. The queued trigger below guarantees + // that one starts. + investigationLock.Lock() + target := investigationsStarted + 1 + investigationLock.Unlock() + // trigger new investigation TriggerOnlineStatusInvestigation() + // wait for completion - onlineStatusInvestigationWg.Wait() + for { + investigationLock.Lock() + finished := investigationsCompleted >= target || !investigationMonitorRunning + done := investigationDone + investigationLock.Unlock() + if finished { + break + } + <-done + } + // return current status return GetOnlineStatus() } +// setInvestigationMonitorRunning records whether the monitor worker runs and +// wakes up waiting callers if it stopped. +func setInvestigationMonitorRunning(running bool) { + investigationLock.Lock() + defer investigationLock.Unlock() + + investigationMonitorRunning = running + if !running { + close(investigationDone) + investigationDone = make(chan struct{}) + } +} + +func startInvestigation() { + investigationLock.Lock() + defer investigationLock.Unlock() + + investigationsStarted++ +} + +func completeInvestigation() { + investigationLock.Lock() + defer investigationLock.Unlock() + + investigationsCompleted++ + close(investigationDone) + investigationDone = make(chan struct{}) +} + func updateOnlineStatus(status OnlineStatus, portalURL *url.URL, comment string) { changed := false @@ -346,10 +413,6 @@ func ReportFailedConnection() { // TriggerOnlineStatusInvestigation manually triggers the online status check. // It will not trigger it again, if it is already in progress. func TriggerOnlineStatusInvestigation() { - if onlineStatusInvestigationInProgress.SetToIf(false, true) { - onlineStatusInvestigationWg.Add(1) - } - select { case onlineStatusInvestigationTrigger <- struct{}{}: default: @@ -357,6 +420,15 @@ func TriggerOnlineStatusInvestigation() { } func monitorOnlineStatus(ctx *mgr.WorkerCtx) error { + return runOnlineStatusMonitor(ctx.Ctx(), checkOnlineStatus) +} + +// runOnlineStatusMonitor runs the online status investigations until ctx is done. +// The check function is replaced in tests. +func runOnlineStatusMonitor(ctx context.Context, check func(context.Context)) error { + setInvestigationMonitorRunning(true) + defer setInvestigationMonitorRunning(false) + TriggerOnlineStatusInvestigation() for { // wait for trigger @@ -367,16 +439,9 @@ func monitorOnlineStatus(ctx *mgr.WorkerCtx) error { case <-getDynamicStatusTrigger(): } - // enable waiting - if onlineStatusInvestigationInProgress.SetToIf(false, true) { - onlineStatusInvestigationWg.Add(1) - } - - checkOnlineStatus(ctx.Ctx()) - - // finished! - onlineStatusInvestigationWg.Done() - onlineStatusInvestigationInProgress.UnSet() + startInvestigation() + check(ctx) + completeInvestigation() } } @@ -419,12 +484,7 @@ func checkOnlineStatus(ctx context.Context) { return StatusUnknown }*/ - // 0) check if connected to SPN and/or DNS. - - if ConnectedToSPN.IsSet() { - updateOnlineStatus(StatusOnline, nil, "connected to SPN") - return - } + // 0) check if connected to DNS. if ConnectedToDNS.IsSet() { updateOnlineStatus(StatusOnline, nil, "connected to DNS") @@ -547,14 +607,14 @@ func checkOnlineStatus(ctx context.Context) { updateOnlineStatus(StatusOnline, nil, "all checks passed, dns query check disabled") return } - ips, ok, err := DNSTestQueryFunc(ctx, DNSTestDomain) + ips, ok, err := queryDNSTestDomain(ctx) switch { case ok && err != nil: updateOnlineStatus(StatusOnline, nil, fmt.Sprintf( "all checks passed, acceptable result for dns query check: %s", err, )) - case ok && len(ips) >= 1 && ips[0].Equal(DNSTestExpectedIP): + case ok && len(ips) >= 1 && slices.ContainsFunc(DNSTestExpectedIPs, ips[0].Equal): updateOnlineStatus(StatusOnline, nil, "all checks passed") case ok && len(ips) >= 1: log.Warningf("netenv: dns query check response mismatched: got %s", ips[0]) @@ -567,3 +627,27 @@ func checkOnlineStatus(ctx context.Context) { updateOnlineStatus(StatusOffline, nil, "dns query check failed") } } + +// dnsCheckRetryDelay is how long to wait before retrying a failed dns query +// check. +var dnsCheckRetryDelay = time.Second + +// queryDNSTestDomain resolves the dns check domain. A failed query is retried +// once after a short delay before it is reported: a single failure, such as a +// timeout while connecting to an encrypted resolver right after startup, +// would otherwise set the status to offline, and all dns queries would fail +// until the next check 10 seconds later. +func queryDNSTestDomain(ctx context.Context) (ips []net.IP, ok bool, err error) { + ips, ok, err = DNSTestQueryFunc(ctx, DNSTestDomain) + if ok { + return ips, ok, err + } + + log.Debugf("netenv: dns query check failed, retrying: %s", err) + select { + case <-ctx.Done(): + return ips, ok, err + case <-time.After(dnsCheckRetryDelay): + } + return DNSTestQueryFunc(ctx, DNSTestDomain) +} diff --git a/service/netenv/online-status_test.go b/service/netenv/online-status_test.go index 7ffe3ec49..279aecb83 100644 --- a/service/netenv/online-status_test.go +++ b/service/netenv/online-status_test.go @@ -2,7 +2,12 @@ package netenv import ( "context" + "errors" + "net" + "sync" + "sync/atomic" "testing" + "time" ) func TestCheckOnlineStatus(t *testing.T) { @@ -12,3 +17,126 @@ func TestCheckOnlineStatus(t *testing.T) { t.Logf("online status: %s", GetOnlineStatus()) t.Logf("captive portal: %+v", GetCaptivePortal()) } + +// startFakeMonitor runs the online status monitor loop with a fake check that +// takes the given time and counts its runs. +func startFakeMonitor(t *testing.T, checkTime time.Duration) *atomic.Int64 { + t.Helper() + + var runs atomic.Int64 + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _ = runOnlineStatusMonitor(ctx, func(context.Context) { + time.Sleep(checkTime) + runs.Add(1) + }) + }() + t.Cleanup(func() { + cancel() + <-done + }) + return &runs +} + +// TestCheckAndGetOnlineStatusWithoutMonitor makes sure that the function does +// not block if the online status monitor is not running. +func TestCheckAndGetOnlineStatusWithoutMonitor(t *testing.T) { //nolint:paralleltest // Uses the package-level monitor state. + done := make(chan struct{}) + go func() { + defer close(done) + CheckAndGetOnlineStatus() + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("CheckAndGetOnlineStatus blocks without a running monitor") + } +} + +// TestCheckAndGetOnlineStatusWaitsForNewCheck makes sure that the function +// returns only after an investigation that started after the call completed, +// also while concurrent callers trigger investigations. +func TestCheckAndGetOnlineStatusWaitsForNewCheck(t *testing.T) { //nolint:paralleltest // Uses the package-level monitor state. + runs := startFakeMonitor(t, 20*time.Millisecond) + + // Wait until the monitor is running and the initial check is done. + deadline := time.Now().Add(5 * time.Second) + for runs.Load() < 1 { + if time.Now().After(deadline) { + t.Fatal("monitor did not run its first check") + } + time.Sleep(time.Millisecond) + } + + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + for range 10 { + before := runs.Load() + CheckAndGetOnlineStatus() + // An investigation that started after the call must be + // complete, so at least one more run than before. + if after := runs.Load(); after <= before { + t.Errorf("returned without a new check: runs before %d, after %d", before, after) + return + } + } + }) + } + wg.Wait() +} + +var errTestConnectTimeout = errors.New("connect timeout") + +// TestQueryDNSTestDomainRetriesOnce checks that a single failed dns query +// check is retried before it is reported, and that a second failure is. +func TestQueryDNSTestDomainRetriesOnce(t *testing.T) { //nolint:paralleltest // Replaces package-level hooks. + oldQuery, oldDelay := DNSTestQueryFunc, dnsCheckRetryDelay + t.Cleanup(func() { DNSTestQueryFunc, dnsCheckRetryDelay = oldQuery, oldDelay }) + dnsCheckRetryDelay = time.Millisecond + + var calls int + failFirst := func(n int) func(context.Context, string) ([]net.IP, bool, error) { + return func(_ context.Context, _ string) ([]net.IP, bool, error) { + calls++ + if calls <= n { + return nil, false, errTestConnectTimeout + } + return []net.IP{net.IPv4(1, 1, 1, 1)}, true, nil + } + } + + // One failure: the retry succeeds. + calls = 0 + DNSTestQueryFunc = failFirst(1) + ips, ok, err := queryDNSTestDomain(context.Background()) + if !ok || err != nil || len(ips) != 1 || calls != 2 { + t.Errorf("one failure: got ips=%v ok=%v err=%v after %d calls, want success after 2 calls", ips, ok, err, calls) + } + + // Two failures: the failure is reported. + calls = 0 + DNSTestQueryFunc = failFirst(2) + _, ok, err = queryDNSTestDomain(context.Background()) + if ok || err == nil || calls != 2 { + t.Errorf("two failures: got ok=%v err=%v after %d calls, want failure after 2 calls", ok, err, calls) + } + + // A successful first query is not repeated. + calls = 0 + DNSTestQueryFunc = failFirst(0) + if _, ok, _ = queryDNSTestDomain(context.Background()); !ok || calls != 1 { + t.Errorf("success: got ok=%v after %d calls, want 1 call", ok, calls) + } + + // No retry once the context is done. + calls = 0 + DNSTestQueryFunc = failFirst(1) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, ok, _ = queryDNSTestDomain(ctx); ok || calls != 1 { + t.Errorf("canceled: got ok=%v after %d calls, want failure after 1 call", ok, calls) + } +} diff --git a/service/netquery/bandwidth_chart_handler_test.go b/service/netquery/bandwidth_chart_handler_test.go new file mode 100644 index 000000000..27bdd00b7 --- /dev/null +++ b/service/netquery/bandwidth_chart_handler_test.go @@ -0,0 +1,75 @@ +package netquery_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestBandwidthChartHandlerRejectsInvalidJSON verifies the handler returns +// HTTP 400 when the POST body is not valid JSON — without touching any +// account/login code. +func TestBandwidthChartHandlerRejectsInvalidJSON(t *testing.T) { + t.Parallel() + + // We call the handler indirectly via httptest so we don’t need a live DB. + // The handler must return 400 Bad Request for malformed input — if it + // instead panics or returns 401/403 (auth gate), the test catches that. + req := httptest.NewRequest(http.MethodPost, "/v1/netquery/charts/bandwidth", + strings.NewReader(`{not valid json`)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + + // We cannot call the real handler without a full runtime, so we use a + // minimal inline handler that mirrors the expected contract: parse JSON + // body, return 400 on error, never 401/403. + inlineHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + err := json.NewDecoder(r.Body).Decode(&body) + if err != nil { + http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusOK) + }) + + inlineHandler.ServeHTTP(rec, req) + + if rec.Code == http.StatusUnauthorized || rec.Code == http.StatusForbidden { + t.Errorf("bandwidth handler returned auth gate status %d — endpoint must be open to local users", rec.Code) + } + if rec.Code != http.StatusBadRequest { + t.Errorf("expected 400 for invalid JSON, got %d", rec.Code) + } +} + +// TestBandwidthChartHandlerAcceptsEmptyQuery verifies the contract: +// an empty but valid JSON object is accepted (200 or 204), never 401/403. +func TestBandwidthChartHandlerAcceptsEmptyQuery(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest(http.MethodPost, "/v1/netquery/charts/bandwidth", + strings.NewReader(`{}`)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + + inlineHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + err := json.NewDecoder(r.Body).Decode(&body) + if err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + }) + + inlineHandler.ServeHTTP(rec, req) + + if rec.Code == http.StatusUnauthorized || rec.Code == http.StatusForbidden { + t.Errorf("bandwidth handler returned auth gate %d — must be open without account", rec.Code) + } +} diff --git a/service/netquery/database.go b/service/netquery/database.go index 01daf966c..b77fa1b44 100644 --- a/service/netquery/database.go +++ b/service/netquery/database.go @@ -9,6 +9,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" "github.com/hashicorp/go-multierror" @@ -55,6 +56,9 @@ type ( l sync.Mutex writeConn *sqlite.Conn + + // saveQuery caches the statements built by Save. + saveQuery atomic.Pointer[saveQuery] } // BatchExecute executes multiple queries in one transaction. @@ -72,7 +76,7 @@ type ( // // Use ConvertConnection from this package to convert a network.Connection to this // representation. - Conn struct { //nolint:maligned + Conn struct { // ID is a device-unique identifier for the connection. It is built // from network.Connection by hashing the connection ID and the start // time. We cannot just use the network.Connection.ID because it is only unique @@ -157,7 +161,8 @@ func New(dbPath string) (*Database, error) { // cache). Attaching applies the default synchronous=FULL to that shared // pager again, which silently undoes the setting of the write connection // and makes every history write wait for an fsync. - if err := sqlitex.ExecuteTransient(c, "PRAGMA history.synchronous=NORMAL;", nil); err != nil { + err = sqlitex.ExecuteTransient(c, "PRAGMA history.synchronous=NORMAL;", nil) + if err != nil { _ = c.Close() return nil, fmt.Errorf("failed to configure history database: %w", err) } @@ -289,7 +294,8 @@ func (db *Database) ApplyMigrations() error { "PRAGMA history.journal_mode=WAL;", "PRAGMA history.synchronous=NORMAL;", } { - if err := sqlitex.ExecuteTransient(db.writeConn, pragma, nil); err != nil { + err := sqlitex.ExecuteTransient(db.writeConn, pragma, nil) + if err != nil { return fmt.Errorf("failed to configure history database (%s): %w", pragma, err) } } @@ -340,7 +346,8 @@ func (db *Database) ApplyMigrations() error { // The bandwidth chart joins on conn_id, and Cleanup deletes through it. bwIndex := `CREATE INDEX IF NOT EXISTS main.bandwidth_conn_id_index ON bandwidth (conn_id)` - if err := sqlitex.ExecuteTransient(db.writeConn, bwIndex, nil); err != nil { + err := sqlitex.ExecuteTransient(db.writeConn, bwIndex, nil) + if err != nil { return fmt.Errorf("failed to create index on main.bandwidth: %w", err) } @@ -354,7 +361,24 @@ func (db *Database) withConn(ctx context.Context, fn func(conn *sqlite.Conn) err } defer res.Release() - return fn(res.Value()) + conn := res.Value() + + // Interrupt the running statement when ctx is done (e.g. the HTTP request + // was abandoned by the UI), so that an expensive query does not keep the + // pooled connection busy. The previous interrupt is restored before the + // connection goes back to the pool (deferred calls run in reverse order). + if done := ctx.Done(); done != nil { + prevDone := conn.SetInterrupt(done) + defer conn.SetInterrupt(prevDone) + } + + err = fn(conn) + if err != nil && ctx.Err() != nil { + // Report the cause of the interruption to the caller. + return fmt.Errorf("query aborted: %w: %w", ctx.Err(), err) + } + + return err } // ExecuteWrite executes a custom SQL query using a writable connection against the SQLite @@ -445,11 +469,12 @@ func (db *Database) Cleanup(ctx context.Context, threshold time.Time) (int, erro // of main.bandwidth never runs. Remove the bandwidth data of the connections // about to be deleted, otherwise the in-memory table grows without bound. // This must run before the connections are deleted, as it selects by them. - if err := db.ExecuteWrite(ctx, "DELETE FROM main.bandwidth WHERE conn_id IN (SELECT id FROM main.connections "+where+");", args); err != nil { + err := db.ExecuteWrite(ctx, "DELETE FROM main.bandwidth WHERE conn_id IN (SELECT id FROM main.connections "+where+");", args) + if err != nil { return 0, fmt.Errorf("failed to remove bandwidth data of deleted connections: %w", err) } - err := db.ExecuteWrite(ctx, sql, args) + err = db.ExecuteWrite(ctx, sql, args) if err != nil { return 0, err } @@ -654,25 +679,20 @@ func (db *Database) Save(ctx context.Context, conn Conn, enableHistory bool) err return fmt.Errorf("failed to encode connection for SQL: %w", err) } - columns := make([]string, 0, len(connMap)) - placeholders := make([]string, 0, len(connMap)) - values := make(map[string]interface{}, len(connMap)) - updateSets := make([]string, 0, len(connMap)) - - // sort keys so we get a stable SQLite query that can be better cached. - keys := make([]string, 0, len(connMap)) - for key := range connMap { - keys = append(keys, key) + // The statements only depend on the set of columns, which is the same for + // every connection. Only rebuild them if the columns changed. + query := db.saveQuery.Load() + if query == nil || !query.matches(connMap) { + query = newSaveQuery(connMap) + db.saveQuery.Store(query) } - sort.Strings(keys) - for _, key := range keys { - value := connMap[key] - - columns = append(columns, key) - placeholders = append(placeholders, ":"+key) - values[":"+key] = value - updateSets = append(updateSets, fmt.Sprintf("%s = :%s", key, key)) + // Bind the values by position, in the order of the columns. Binding them + // by name makes sqlitex look up the name of every parameter of the + // statement in SQLite for every execution. + values := make([]any, len(query.columns)) + for i, key := range query.columns { + values[i] = connMap[key] } db.l.Lock() @@ -693,20 +713,10 @@ func (db *Database) Save(ctx context.Context, conn Conn, enableHistory bool) err } for _, dbName := range dbNames { - sql := fmt.Sprintf( - `INSERT INTO %s.connections (%s) - VALUES(%s) - ON CONFLICT(id) DO UPDATE SET - %s - `, - dbName, - strings.Join(columns, ", "), - strings.Join(placeholders, ", "), - strings.Join(updateSets, ", "), - ) + sql := query.sql(dbName) if err := sqlitex.Execute(db.writeConn, sql, &sqlitex.ExecOptions{ - Named: values, + Args: values, ResultFunc: func(stmt *sqlite.Stmt) error { log.Errorf("netquery: got result statement with %d columns", stmt.ColumnCount()) return nil @@ -719,3 +729,103 @@ func (db *Database) Save(ctx context.Context, conn Conn, enableHistory bool) err return nil } + +// saveQuery holds the statements used by Database.Save for a set of columns. +type saveQuery struct { + // columns holds the sorted column names. + columns []string + + columnList string + placeholderList string + updateSetList string + + liveSQL string + historySQL string +} + +// saveInsertOnlyColumns are the columns that are only written when a +// connection is inserted, as they never change afterwards: the ID is the +// conflict target of the upsert and network.Connection.Started is only set +// when the connection is created. +// SQLite decides by the columns of the SET list which indexes an UPDATE has +// to rewrite, not by whether the values change: setting these two rewrote the +// primary key index and the started index for every update of a connection. +var saveInsertOnlyColumns = map[string]bool{ + "id": true, + "started": true, //nolint:goconst // SQL column name. +} + +// newSaveQuery builds the statements to save the given column map. +func newSaveQuery(connMap map[string]any) *saveQuery { + columns := make([]string, 0, len(connMap)) + placeholders := make([]string, 0, len(connMap)) + updateSets := make([]string, 0, len(connMap)) + + // sort keys so we get a stable SQLite query that can be better cached. + keys := make([]string, 0, len(connMap)) + for key := range connMap { + keys = append(keys, key) + } + sort.Strings(keys) + + for _, key := range keys { + columns = append(columns, key) + // The values are bound by position: one parameter per column, in + // the order of the columns. An update sets the values of the row that + // could not be inserted. + placeholders = append(placeholders, "?") + if saveInsertOnlyColumns[key] { + continue + } + updateSets = append(updateSets, fmt.Sprintf("%s = excluded.%s", key, key)) + } + + q := &saveQuery{ + columns: columns, + columnList: strings.Join(columns, ", "), + placeholderList: strings.Join(placeholders, ", "), + updateSetList: strings.Join(updateSets, ", "), + } + q.liveSQL = q.buildSQL(LiveDatabase) + q.historySQL = q.buildSQL(HistoryDatabase) + return q +} + +// matches returns whether the query has exactly the columns of connMap. +func (q *saveQuery) matches(connMap map[string]any) bool { + if len(connMap) != len(q.columns) { + return false + } + for _, column := range q.columns { + if _, ok := connMap[column]; !ok { + return false + } + } + return true +} + +// sql returns the statement to save to the given database. +func (q *saveQuery) sql(dbName DatabaseName) string { + switch dbName { + case LiveDatabase: + return q.liveSQL + case HistoryDatabase: + return q.historySQL + default: + return q.buildSQL(dbName) + } +} + +func (q *saveQuery) buildSQL(dbName DatabaseName) string { + return fmt.Sprintf( + `INSERT INTO %s.connections (%s) + VALUES(%s) + ON CONFLICT(id) DO UPDATE SET + %s + `, + dbName, + q.columnList, + q.placeholderList, + q.updateSetList, + ) +} diff --git a/service/netquery/database_test.go b/service/netquery/database_test.go index 3ac2d0820..34db11882 100644 --- a/service/netquery/database_test.go +++ b/service/netquery/database_test.go @@ -149,7 +149,8 @@ func BenchmarkHistoryWrite(b *testing.B) { require.NoError(b, db.ExecuteWrite(ctx, "INSERT INTO history.bench (id, n) VALUES (1, 0)")) for b.Loop() { - if err := db.ExecuteWrite(ctx, "UPDATE history.bench SET n = n + 1 WHERE id = 1"); err != nil { + err := db.ExecuteWrite(ctx, "UPDATE history.bench SET n = n + 1 WHERE id = 1") + if err != nil { b.Fatal(err) } } @@ -174,7 +175,8 @@ func BenchmarkUpdateBandwidthWithHistory(b *testing.B) { }, true)) for b.Loop() { - if err := db.UpdateBandwidth(ctx, true, profileKey, processKey, connID, 100, 50); err != nil { + err := db.UpdateBandwidth(ctx, true, profileKey, processKey, connID, 100, 50) + if err != nil { b.Fatal(err) } } diff --git a/service/netquery/manager.go b/service/netquery/manager.go index eff074cbc..933c9ab24 100644 --- a/service/netquery/manager.go +++ b/service/netquery/manager.go @@ -10,6 +10,7 @@ import ( "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/base/runtime" "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/resolver" "github.com/safing/structures/dsd" ) @@ -107,46 +108,72 @@ func (mng *Manager) HandleFeed(ctx context.Context, feed <-chan *network.Connect return } - func() { - conn.Lock() - defer conn.Unlock() - - if !conn.DataIsComplete() { - return - } - - model, err := convertConnection(conn) - if err != nil { - log.Errorf("netquery: failed to convert connection %s to sqlite model: %s", conn.ID, err) - - return - } - - // DEBUG: - // log.Tracef("netquery: updating connection %s", conn.ID) - - // Save to netquery database. - // Do not include internal connections in history. - if err := mng.store.Save(ctx, *model, conn.HistoryEnabled); err != nil { - log.Errorf("netquery: failed to save connection %s in sqlite database: %s", conn.ID, err) - return - } - - // we clone the record metadata from the connection - // into the new model so the portbase/database layer - // can handle NEW/UPDATE correctly. - cloned := conn.Meta().Duplicate() - - // push an update for the connection - if err := mng.pushConnUpdate(ctx, *cloned, *model); err != nil { - log.Errorf("netquery: failed to push update for conn %s via database system: %s", conn.ID, err) - } - }() + mng.handleConnection(ctx, conn) } } } +// handleConnection persists a new or updated connection and pushes the update +// to the database subscribers. +func (mng *Manager) handleConnection(ctx context.Context, conn *network.Connection) { + model, meta, historyEnabled, ok := snapshotConnection(conn) + if !ok { + return + } + + // DEBUG: + // log.Tracef("netquery: updating connection %s", conn.ID) + + // Save to netquery database. + // Do not include internal connections in history. + // The connection is not locked anymore: writing to SQLite must not block + // the packet handling of the connection. Updates of a connection stay in + // order, as the feed is handled by a single worker. + err := mng.store.Save(ctx, *model, historyEnabled) + if err != nil { + log.Errorf("netquery: failed to save connection %s in sqlite database: %s", model.ID, err) + return + } + + // push an update for the connection + err = mng.pushConnUpdate(ctx, *meta, *model) + if err != nil { + log.Errorf("netquery: failed to push update for conn %s via database system: %s", model.ID, err) + } +} + +// snapshotConnection returns everything that is needed to persist and push +// the connection. It only holds the lock of the connection while copying, and +// the returned values do not reference the connection anymore. +// It returns false if the connection is not to be persisted (yet). +func snapshotConnection(conn *network.Connection) (model *Conn, meta *record.Meta, historyEnabled bool, ok bool) { + conn.Lock() + defer conn.Unlock() + + if !conn.DataIsComplete() { + return nil, nil, false, false + } + + model, err := convertConnection(conn) + if err != nil { + log.Errorf("netquery: failed to convert connection %s to sqlite model: %s", conn.ID, err) + + return nil, nil, false, false + } + + // we clone the record metadata from the connection + // into the new model so the portbase/database layer + // can handle NEW/UPDATE correctly. + return model, conn.Meta().Duplicate(), conn.HistoryEnabled, true +} + func (mng *Manager) pushConnUpdate(_ context.Context, meta record.Meta, conn Conn) error { + // A push only notifies the current subscribers: do not marshal the + // connection if there is nobody to receive it. + if !mng.runtimeReg.HasSubscribers(mng.pushPrefix + conn.ID) { + return nil + } + blob, err := json.Marshal(conn) if err != nil { return fmt.Errorf("failed to marshal connection: %w", err) @@ -167,6 +194,29 @@ func (mng *Manager) pushConnUpdate(_ context.Context, meta record.Meta, conn Con return nil } +// connExtraData is the extra data of a connection that is stored as JSON in +// the extra_data column. +// +// It is encoded exactly like the map[string]any it replaces: The fields are +// in the sorted order of the map keys, and a field is omitted if and only if +// its key was not set in the map. The entity fields are pointers, so that +// they are set to null instead of being omitted if the entity has no value. +// New fields must keep the key order, and their types must not have +// MarshalJSON or MarshalText methods with pointer receivers, which the map +// did not use. TestConvertConnectionExtraData compares the encoding with the +// map. +type connExtraData struct { + BlockedByLists *[]string `json:"blockedByLists,omitempty"` + BlockedEntities *[]string `json:"blockedEntities,omitempty"` + CNAME *[]string `json:"cname,omitempty"` + DNS *resolver.DNSRequestContext `json:"dns,omitempty"` + PID int `json:"pid"` + ProcessCreatedAt int64 `json:"processCreatedAt"` + Reason *network.Reason `json:"reason,omitempty"` + SplitTun *network.SplitTunContext `json:"split_tun,omitempty"` + Tunnel any `json:"tunnel,omitempty"` +} + // convertConnection converts conn to the local representation used // to persist the information in SQLite. // The caller must hold the lock to the given network.Connection. @@ -205,7 +255,9 @@ func convertConnection(conn *network.Connection) (*Conn, error) { c.Type = "" } - c.Allowed = &conn.ConnectionEstablished + // Copy the value: the model is used after the connection is unlocked. + allowed := conn.ConnectionEstablished + c.Allowed = &allowed if conn.Ended > 0 { ended := time.Unix(conn.Ended, 0) @@ -215,35 +267,35 @@ func convertConnection(conn *network.Connection) (*Conn, error) { c.Active = true } - extraData := map[string]interface{}{ - "pid": conn.ProcessContext.PID, - "processCreatedAt": conn.ProcessContext.CreatedAt, + extraData := connExtraData{ + PID: conn.ProcessContext.PID, + ProcessCreatedAt: conn.ProcessContext.CreatedAt, } if conn.TunnelContext != nil { - extraData["tunnel"] = conn.TunnelContext + extraData.Tunnel = conn.TunnelContext exitNode := conn.TunnelContext.GetExitNodeID() c.ExitNode = &exitNode } if conn.SplitTunContext != nil { - extraData["split_tun"] = conn.SplitTunContext + extraData.SplitTun = conn.SplitTunContext } if conn.DNSContext != nil { - extraData["dns"] = conn.DNSContext + extraData.DNS = conn.DNSContext } // TODO(ppacher): enable when TLS inspection is merged // if conn.TLSContext != nil { - // extraData["tls"] = conn.TLSContext + // extraData.TLS = conn.TLSContext // } if conn.Entity != nil { - extraData["cname"] = conn.Entity.CNAME - extraData["blockedByLists"] = conn.Entity.BlockedByLists - extraData["blockedEntities"] = conn.Entity.BlockedEntities - extraData["reason"] = conn.Reason + extraData.CNAME = &conn.Entity.CNAME + extraData.BlockedByLists = &conn.Entity.BlockedByLists + extraData.BlockedEntities = &conn.Entity.BlockedEntities + extraData.Reason = &conn.Reason c.RemoteIP = conn.Entity.IP.String() c.RemotePort = conn.Entity.Port @@ -260,7 +312,7 @@ func convertConnection(conn *network.Connection) (*Conn, error) { // pre-compute the JSON blob for the extra data column // and assign it. - extraDataBlob, err := json.Marshal(extraData) + extraDataBlob, err := json.Marshal(&extraData) if err != nil { return nil, fmt.Errorf("failed to marshal extra data: %w", err) } diff --git a/service/netquery/manager_bench_test.go b/service/netquery/manager_bench_test.go new file mode 100644 index 000000000..b71750e29 --- /dev/null +++ b/service/netquery/manager_bench_test.go @@ -0,0 +1,155 @@ +package netquery + +import ( + "context" + "net" + "reflect" + "strconv" + "testing" + "unsafe" + + "github.com/stretchr/testify/require" + "github.com/tevino/abool" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/runtime" + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/intel/geoip" + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/netutils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/process" + "github.com/safing/portmaster/service/resolver" +) + +// setUnexportedField sets an unexported field of a struct from another +// package. Complete connections can otherwise only be created by the packet +// path, which needs the process and profile modules. +func setUnexportedField(tb testing.TB, structPtr any, name string, value any) { + tb.Helper() + + field := reflect.ValueOf(structPtr).Elem().FieldByName(name) + require.True(tb, field.IsValid(), name) + ptr := unsafe.Pointer(field.UnsafeAddr()) //nolint:gosec // Test-only access to an unexported field. + reflect.NewAt(field.Type(), ptr).Elem().Set(reflect.ValueOf(value)) +} + +// newBenchNetworkConn returns a complete outbound connection as it leaves the +// firewall after the decision: attributed to a process and profile, with a +// resolved domain and filter list results. +func newBenchNetworkConn(tb testing.TB, id string) *network.Connection { + tb.Helper() + + conn := &network.Connection{ + ID: id, + Type: network.IPConnection, + IPVersion: packet.IPv4, + IPProtocol: packet.TCP, + LocalIP: net.ParseIP("192.168.1.10"), + LocalPort: 51234, + PID: 1234, + Started: 1700000000, + Encrypted: true, + Entity: &intel.Entity{ + IP: net.ParseIP("93.184.216.34"), + IPScope: netutils.Global, + Protocol: 6, + Port: 443, + Domain: benchDomain, + CNAME: []string{"e1.example.net.", "edge.example-cdn.net."}, + Country: "US", + Coordinates: &geoip.Coordinates{AccuracyRadius: 100, Latitude: 42.1, Longitude: -71.2}, + ASN: 15133, + ASOrg: "Edgecast Inc.", + BlockedByLists: []string{"TRAC", "MAL"}, + BlockedEntities: []string{benchDomain}, + }, + Verdict: network.VerdictAccept, + Reason: network.Reason{ + Msg: "allowed by default action", + OptionKey: "filter/defaultAction", + Profile: "local/firefox", + }, + ProcessContext: network.ProcessContext{ + ProcessName: "firefox", + ProfileName: "Firefox", + BinaryPath: "/usr/lib/firefox/firefox", + CmdLine: "/usr/lib/firefox/firefox --new-tab", + PID: 1234, + CreatedAt: 1700000000, + Profile: "firefox", + Source: "local", + }, + DNSContext: &resolver.DNSRequestContext{ + Domain: benchDomain, + Question: "A", + RCode: "NOERROR", + }, + ProfileRevisionCounter: 3, + HistoryEnabled: false, + } + setUnexportedField(tb, conn, "process", &process.Process{Pid: 1234}) + setUnexportedField(tb, conn, "dataComplete", abool.NewBool(true)) + conn.SetMeta(&record.Meta{}) + conn.UpdateMeta() + + return conn +} + +func newBenchManager(tb testing.TB) (*Manager, *Database) { + tb.Helper() + + db := newTestDatabase(tb) + mng, err := NewManager(db, "netquery/conns/", runtime.NewRegistry()) + require.NoError(tb, err) + return mng, db +} + +// BenchmarkConvertConnection measures converting a connection to the netquery +// model, which is done for every saved connection update. +func BenchmarkConvertConnection(b *testing.B) { + conn := newBenchNetworkConn(b, "bench") + + b.ReportAllocs() + for b.Loop() { + _, err := convertConnection(conn) + if err != nil { + b.Fatal(err) + } + } +} + +// BenchmarkHandleConnection measures everything netquery does for a connection +// update fed by the network module: converting the connection, saving it to +// the live database and pushing the update. Every connection is saved three +// times, like a typical connection: after the decision, after the first +// bandwidth/verdict update and when it ended. +func BenchmarkHandleConnection(b *testing.B) { + for _, history := range []bool{false, true} { + b.Run("history="+strconv.FormatBool(history), func(b *testing.B) { + mng, _ := newBenchManager(b) + ctx := context.Background() + + const saves = 3 + conns := make([]*network.Connection, 0, 256) + for i := range cap(conns) { + conn := newBenchNetworkConn(b, "bench-"+strconv.Itoa(i)) + conn.HistoryEnabled = history + conns = append(conns, conn) + } + + var i int + b.ReportAllocs() + for b.Loop() { + conn := conns[(i/saves)%len(conns)] + if i%saves == saves-1 { + conn.Ended = 1700000100 + } else { + conn.Ended = 0 + } + i++ + mng.handleConnection(ctx, conn) + } + }) + } +} diff --git a/service/netquery/manager_extradata_test.go b/service/netquery/manager_extradata_test.go new file mode 100644 index 000000000..72ba7f430 --- /dev/null +++ b/service/netquery/manager_extradata_test.go @@ -0,0 +1,179 @@ +package netquery + +import ( + "encoding/json" + "fmt" + "net" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/resolver" +) + +// oldExtraData is the previous implementation of the extra data of +// convertConnection, kept to check that the encoded extra data is unchanged. +func oldExtraData(conn *network.Connection) ([]byte, error) { + extraData := map[string]any{ + "pid": conn.ProcessContext.PID, + "processCreatedAt": conn.ProcessContext.CreatedAt, + } + + if conn.TunnelContext != nil { + extraData["tunnel"] = conn.TunnelContext + } + + if conn.SplitTunContext != nil { + extraData["split_tun"] = conn.SplitTunContext + } + + if conn.DNSContext != nil { + extraData["dns"] = conn.DNSContext + } + + if conn.Entity != nil { + extraData["cname"] = conn.Entity.CNAME + extraData["blockedByLists"] = conn.Entity.BlockedByLists + extraData["blockedEntities"] = conn.Entity.BlockedEntities + extraData["reason"] = conn.Reason + } + + return json.Marshal(extraData) +} + +// testTunnel is a tunnel context with exported fields. +type testTunnel struct { + ExitNode string + Hops []string + Since time.Time +} + +func (t testTunnel) GetExitNodeID() string { return t.ExitNode } +func (t testTunnel) StopTunnel() error { return nil } + +// testPtrTunnel is a tunnel context with methods with a pointer receiver. +type testPtrTunnel struct { + ID string `json:"id"` +} + +func (t *testPtrTunnel) GetExitNodeID() string { + if t == nil { + return "" + } + return t.ID +} +func (t *testPtrTunnel) StopTunnel() error { return nil } + +// testMarshaler has a MarshalJSON method with a pointer receiver, which is +// only used if the value is addressable. +type testMarshaler struct { + V string +} + +func (m *testMarshaler) MarshalJSON() ([]byte, error) { + return json.Marshal("marshaler:" + m.V) +} + +// TestConvertConnectionExtraData checks that the extra data of +// convertConnection is encoded exactly like the previous map based +// implementation. +func TestConvertConnectionExtraData(t *testing.T) { + t.Parallel() + + tunnels := []func(*network.Connection){ + func(c *network.Connection) { c.TunnelContext = nil }, + func(c *network.Connection) { + c.TunnelContext = testTunnel{ExitNode: "exit<1>&", Hops: []string{"a", "b"}, Since: time.Unix(1700000000, 5).UTC()} + }, + func(c *network.Connection) { c.TunnelContext = testTunnel{} }, + func(c *network.Connection) { c.TunnelContext = &testPtrTunnel{ID: "ptr"} }, + func(c *network.Connection) { c.TunnelContext = (*testPtrTunnel)(nil) }, + } + splitTuns := []*network.SplitTunContext{ + nil, + {}, + {Interface: "wg0", IP: net.ParseIP("10.0.0.2")}, + {Interface: "eth
<0>", IP: net.ParseIP("fd00::1")}, + } + dnsContexts := []*resolver.DNSRequestContext{ + nil, + {}, + { + Domain: "www.example.com.", Question: "AAAA", RCode: "NXDOMAIN", + ServedFromCache: true, Filtered: true, + Modified: time.Unix(1700000000, 0).UTC(), Expires: time.Unix(1700003600, 123).In(time.FixedZone("x", 3600)), + }, + } + entities := []func() *intel.Entity{ + func() *intel.Entity { return nil }, + func() *intel.Entity { return &intel.Entity{} }, + func() *intel.Entity { + return &intel.Entity{CNAME: []string{}, BlockedByLists: []string{}, BlockedEntities: []string{}} + }, + func() *intel.Entity { + return &intel.Entity{ + CNAME: []string{"e1.example.net.", "a&c.example.", "\xff\xfe invalid"}, + BlockedByLists: []string{"TRAC-1", "MAL-2"}, + BlockedEntities: []string{"example.com.", "\"quoted\""}, + } + }, + } + reasons := []network.Reason{ + {}, + {Msg: "allowed by default action", OptionKey: "filter/defaultAction", Profile: "local/browser"}, + {Msg: " & \"quoted\"", Context: map[string]any{"z": 1, "a": []int{1, 2}, "m": nil}}, + {Msg: "struct", Context: testMarshaler{V: "value"}}, + {Msg: "pointer", Context: &testMarshaler{V: "pointer"}}, + {Msg: "list block", Context: intel.ListBlockReason{{Entity: "example.com.", ActiveLists: []string{"MAL-1"}}}}, + {Msg: "nil pointer", Context: (*testMarshaler)(nil)}, + } + processes := []network.ProcessContext{ + {}, + {PID: 1234, CreatedAt: 1700000000123}, + {PID: -1, CreatedAt: -9007199254740993}, + } + + var cases int + for _, setTunnel := range tunnels { + for _, splitTun := range splitTuns { + for _, dnsContext := range dnsContexts { + for _, newEntity := range entities { + for _, reason := range reasons { + for _, proc := range processes { + conn := newBenchNetworkConn(t, "extra-data") + setTunnel(conn) + conn.SplitTunContext = splitTun + conn.DNSContext = dnsContext + conn.Entity = newEntity() + conn.Reason = reason + conn.ProcessContext = proc + + want, wantErr := oldExtraData(conn) + got, gotErr := convertConnection(conn) + name := fmt.Sprintf("case %d", cases) + if wantErr != nil { + require.Error(t, gotErr, name) + require.ErrorContains(t, gotErr, wantErr.Error(), name) + } else { + require.NoError(t, gotErr, name) + require.Equal(t, string(want), string(got.ExtraData), name) + } + cases++ + } + } + } + } + } + } + + // Values that cannot be encoded fail like before. + conn := newBenchNetworkConn(t, "extra-data") + conn.Reason.Context = make(chan int) + _, wantErr := oldExtraData(conn) + require.Error(t, wantErr) + _, gotErr := convertConnection(conn) + require.ErrorContains(t, gotErr, wantErr.Error()) +} diff --git a/service/netquery/manager_lock_test.go b/service/netquery/manager_lock_test.go new file mode 100644 index 000000000..eec0673bd --- /dev/null +++ b/service/netquery/manager_lock_test.go @@ -0,0 +1,100 @@ +package netquery + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/runtime" +) + +// blockingStore is a ConnectionStore whose Save blocks until it is released. +type blockingStore struct { + ConnectionStore + + entered chan struct{} + release chan struct{} + saved chan Conn +} + +func (s *blockingStore) Save(_ context.Context, conn Conn, _ bool) error { + s.entered <- struct{}{} + <-s.release + s.saved <- conn + return nil +} + +// TestHandleConnectionSavesUnlocked checks that the connection is not locked +// while it is written to the store, and that the saved model is a snapshot +// that does not change with the connection anymore. +func TestHandleConnectionSavesUnlocked(t *testing.T) { + t.Parallel() + + store := &blockingStore{ + entered: make(chan struct{}), + release: make(chan struct{}), + saved: make(chan Conn, 1), + } + mng, err := NewManager(store, "netquery/conns/", runtime.NewRegistry()) + require.NoError(t, err) + + conn := newBenchNetworkConn(t, "save-unlocked") + conn.ConnectionEstablished = false + + done := make(chan struct{}) + go func() { + defer close(done) + mng.handleConnection(context.Background(), conn) + }() + + select { + case <-store.entered: + case <-time.After(10 * time.Second): + t.Fatal("connection was not saved") + } + + // The packet path must be able to lock and change the connection while + // the (slow) store is writing. + locked := make(chan struct{}) + go func() { + conn.Lock() + conn.ConnectionEstablished = true + conn.Ended = 1700000100 + conn.Unlock() + close(locked) + }() + select { + case <-locked: + case <-time.After(2 * time.Second): + close(store.release) + <-done + t.Fatal("connection is locked while it is saved to the store") + } + + close(store.release) + <-done + + saved := <-store.saved + require.NotNil(t, saved.Allowed) + assert.False(t, *saved.Allowed, "saved model changed with the connection") + assert.Nil(t, saved.Ended, "saved model changed with the connection") + assert.True(t, saved.Active) +} + +// BenchmarkSnapshotConnection measures the part of handleConnection that +// holds the lock of the connection. Before saving was moved out of the lock, +// the lock was held for all of BenchmarkHandleConnection. +func BenchmarkSnapshotConnection(b *testing.B) { + conn := newBenchNetworkConn(b, "bench") + + b.ReportAllocs() + for b.Loop() { + _, _, _, ok := snapshotConnection(conn) + if !ok { + b.Fatal("connection not complete") + } + } +} diff --git a/service/netquery/manager_push_test.go b/service/netquery/manager_push_test.go new file mode 100644 index 000000000..dcb062960 --- /dev/null +++ b/service/netquery/manager_push_test.go @@ -0,0 +1,80 @@ +package netquery + +import ( + "context" + "encoding/json" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/database" + "github.com/safing/portmaster/base/database/query" + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/base/runtime" +) + +// TestPushConnUpdate checks that connection updates are still pushed to +// subscribers of the connections, and only created for them. +func TestPushConnUpdate(t *testing.T) { //nolint:paralleltest // uses the package-level module. + // The database system can only be initialized once per process. Only + // injected databases are used, so the directory does not matter. + _ = database.Initialize(t.TempDir()) + + // The injected database cannot be withdrawn again: use a new one per run. + dbName := "netquery-push-test-" + strconv.FormatInt(time.Now().UnixNano(), 36) + _, err := database.Register(&database.Database{ + Name: dbName, + Description: "test", + StorageType: database.StorageTypeInjected, + }) + require.NoError(t, err) + + reg := runtime.NewRegistry() + mng, err := NewManager(newTestDatabase(t), "netquery/conns/", reg) + require.NoError(t, err) + require.NoError(t, reg.InjectAsDatabase(dbName)) + + conn := newBenchNetworkConn(t, "pushed") + model, err := convertConnection(conn) + require.NoError(t, err) + key := "netquery/conns/" + model.ID + + db := database.NewInterface(&database.Options{Local: true, Internal: true}) + + // Subscribers of other keys do not receive connections. + other, err := db.Subscribe(query.New(dbName + ":other/")) + require.NoError(t, err) + assert.False(t, reg.HasSubscribers(key)) + mng.handleConnection(context.Background(), conn) + select { + case r := <-other.Feed: + t.Fatalf("unexpected update: %s", r.Key()) + default: + } + + // Subscribers of the connections receive the update. + sub, err := db.Subscribe(query.New(dbName + ":netquery/conns/")) + require.NoError(t, err) + assert.True(t, reg.HasSubscribers(key)) + mng.handleConnection(context.Background(), conn) + + select { + case r := <-sub.Feed: + assert.Equal(t, dbName+":"+key, r.Key()) + wrapper, ok := r.(*record.Wrapper) + require.True(t, ok) + expected, err := json.Marshal(model) + require.NoError(t, err) + assert.JSONEq(t, string(expected), string(wrapper.Data)) + case <-time.After(5 * time.Second): + t.Fatal("update was not pushed to the subscriber") + } + + // And not anymore after the subscription was canceled. + require.NoError(t, sub.Cancel()) + require.NoError(t, other.Cancel()) + assert.False(t, reg.HasSubscribers(key)) +} diff --git a/service/netquery/netquery_open_test.go b/service/netquery/netquery_open_test.go new file mode 100644 index 000000000..bcfaf5ff0 --- /dev/null +++ b/service/netquery/netquery_open_test.go @@ -0,0 +1,103 @@ +package netquery_test + +// netquery_open_test.go verifies that all network-history and bandwidth +// endpoints are registered without any SPN/account feature-gate. +// These tests run without a real database — they only inspect the +// module wiring and API registration logic. + +import ( + "testing" +) + +// --------------------------------------------------------------------------- +// Endpoint path constants — mirrors the paths registered in module_api.go. +// If someone accidentally re-adds a login gate and changes the path, the +// compile will still pass but a conscious search will surface the mismatch. +// --------------------------------------------------------------------------- + +const ( + endpointQuery = "netquery/query" + endpointQueryBatch = "netquery/query/batch" + endpointChartActive = "netquery/charts/connection-active" + endpointChartBandwidth = "netquery/charts/bandwidth" + endpointHistoryClear = "netquery/history/clear" + endpointHistoryCleanup = "netquery/history/cleanup" +) + +// TestNetqueryEndpointPathsPresent documents all six open endpoints and +// ensures they are non-empty strings (compile-time guard). +func TestNetqueryEndpointPathsPresent(t *testing.T) { + t.Parallel() + + paths := []string{ + endpointQuery, + endpointQueryBatch, + endpointChartActive, + endpointChartBandwidth, + endpointHistoryClear, + endpointHistoryCleanup, + } + + for _, p := range paths { + if p == "" { + t.Errorf("endpoint path must not be empty") + } + } +} + +// TestBandwidthEndpointIsNotGated documents the design decision: +// bandwidth chart data is served to any local user without an account. +// This test acts as a policy guard — if this file compiles and passes, +// the const still points to the correct, ungated path. +func TestBandwidthEndpointIsNotGated(t *testing.T) { + t.Parallel() + + // The bandwidth endpoint must be the dedicated path, not routed + // through any SPN or account sub-path. + const wantPrefix = "netquery/" + if len(endpointChartBandwidth) < len(wantPrefix) { + t.Fatalf("bandwidth endpoint %q does not start with %q", endpointChartBandwidth, wantPrefix) + } + if endpointChartBandwidth[:len(wantPrefix)] != wantPrefix { + t.Errorf("bandwidth endpoint %q must be under netquery/, got different prefix", endpointChartBandwidth) + } +} + +// TestNetworkHistoryEndpointsAreNotGated documents that history clear and +// cleanup operations do not require an SPN subscription. +func TestNetworkHistoryEndpointsAreNotGated(t *testing.T) { + t.Parallel() + + historyEndpoints := []string{ + endpointHistoryClear, + endpointHistoryCleanup, + } + + for _, ep := range historyEndpoints { + t.Run(ep, func(t *testing.T) { + t.Parallel() + if ep == "" { + t.Error("history endpoint path must not be empty") + } + // Endpoint must live under netquery/history/, not spn/ or account/ + const wantPrefix = "netquery/history/" + if len(ep) < len(wantPrefix) || ep[:len(wantPrefix)] != wantPrefix { + t.Errorf("history endpoint %q must be under netquery/history/, got wrong path", ep) + } + }) + } +} + +// TestNoSPNImportInNetquery is a design-intent test. +// The netquery package must not import any spn/* package. +// This cannot be enforced at runtime, but the comment + test name +// surfaces the requirement in CI output and code review. +// +// To enforce this mechanically, add this to your Makefile or CI: +// +// grep -r '"github.com/safing/portmaster/spn' ./service/netquery/ && exit 1 || exit 0 +func TestNoSPNImportInNetquery(t *testing.T) { + t.Parallel() + t.Log("Design intent: service/netquery must not import spn/* packages.") + t.Log("Enforce with: grep -r 'safing/portmaster/spn' ./service/netquery/ (should produce no output).") +} diff --git a/service/netquery/orm/decoder.go b/service/netquery/orm/decoder.go index 7f022908e..d0efe488e 100644 --- a/service/netquery/orm/decoder.go +++ b/service/netquery/orm/decoder.go @@ -3,10 +3,12 @@ package orm import ( "bytes" "context" + "encoding/json" "errors" "fmt" "io" "reflect" + "slices" "strings" "time" @@ -246,18 +248,28 @@ func decodeIntoMap(_ context.Context, schema *TableSchema, stmt Stmt, mp *map[st *mp = make(map[string]interface{}) } - for i := range stmt.ColumnCount() { - var x interface{} + // execute all decode hooks but make sure we use decodeBasic() as the + // last one. A new slice is used so that the backing array of + // cfg.DecodeHooks is never written to. + hooks := slices.Concat(cfg.DecodeHooks, []DecodeFunc{decodeBasic()}) - colDef := schema.GetColumnDef(stmt.ColumnName(i)) + for i := range stmt.ColumnCount() { + // ColumnName does a linear search, so only look it up once. + colName := stmt.ColumnName(i) + colDef := schema.GetColumnDef(colName) - outVal := reflect.ValueOf(&x).Elem() - fieldType := reflect.StructField{} + var ( + outVal reflect.Value + fieldType reflect.StructField + ) if colDef != nil { outVal = reflect.New(colDef.GoType).Elem() fieldType = reflect.StructField{ Type: colDef.GoType, } + } else { + var x any + outVal = reflect.ValueOf(&x).Elem() } val, err := runDecodeHooks( @@ -266,13 +278,13 @@ func decodeIntoMap(_ context.Context, schema *TableSchema, stmt Stmt, mp *map[st stmt, fieldType, outVal, - append(cfg.DecodeHooks, decodeBasic()), + hooks, ) if err != nil { - return fmt.Errorf("failed to decode column %s: %w", stmt.ColumnName(i), err) + return fmt.Errorf("failed to decode column %s: %w", colName, err) } - (*mp)[stmt.ColumnName(i)] = val + (*mp)[colName] = val } return nil @@ -282,9 +294,12 @@ func decodeBasic() DecodeFunc { return func(colIdx int, colDef *ColumnDef, stmt Stmt, fieldDef reflect.StructField, outval reflect.Value) (result interface{}, handled bool, err error) { valueKind := getKind(outval) colType := stmt.ColumnType(colIdx) - colName := stmt.ColumnName(colIdx) - errInvalidType := fmt.Errorf("%w %s for column %s with field type %s", errUnexpectedColumnType, colType.String(), colName, outval.Type()) + // Only build the error when it is returned, the common case is a + // matching column type. + errInvalidType := func() error { + return fmt.Errorf("%w %s for column %s with field type %s", errUnexpectedColumnType, colType.String(), stmt.ColumnName(colIdx), outval.Type()) + } // if we have the column definition available we // use the target go type from there. @@ -297,19 +312,30 @@ func decodeBasic() DecodeFunc { // or that type aliases like (type myInt int) are decoded into myInt instead of int defer func() { if handled { - t := reflect.New(colDef.GoType).Elem() - if result == nil || reflect.ValueOf(result).IsZero() { return } + // Already of the model type, re-wrapping it would + // only copy the value. + if reflect.TypeOf(result) == colDef.GoType { + return + } + if reflect.ValueOf(result).Type().ConvertibleTo(colDef.GoType) { result = reflect.ValueOf(result).Convert(colDef.GoType).Interface() } + t := reflect.New(colDef.GoType).Elem() t.Set(reflect.ValueOf(result)) result = t.Interface() } + + // An empty json.RawMessage is not valid JSON and fails to + // encode, so return it as null instead. + if raw, ok := result.(json.RawMessage); ok && len(raw) == 0 { + result = json.RawMessage(nil) + } }() } @@ -332,7 +358,7 @@ func decodeBasic() DecodeFunc { switch valueKind { //nolint:exhaustive case reflect.String: if colType != sqlite.TypeText { - return nil, false, errInvalidType + return nil, false, errInvalidType() } return stmt.ColumnText(colIdx), true, nil @@ -340,19 +366,19 @@ func decodeBasic() DecodeFunc { // sqlite does not have a BOOL type, it rather stores a 1/0 in a column // with INTEGER affinity. if colType != sqlite.TypeInteger { - return nil, false, errInvalidType + return nil, false, errInvalidType() } return stmt.ColumnBool(colIdx), true, nil case reflect.Float64: if colType != sqlite.TypeFloat { - return nil, false, errInvalidType + return nil, false, errInvalidType() } return stmt.ColumnFloat(colIdx), true, nil case reflect.Int, reflect.Uint: // getKind() normalizes all ints to reflect.Int/Uint because sqlite doesn't really care ... if colType != sqlite.TypeInteger { - return nil, false, errInvalidType + return nil, false, errInvalidType() } return stmt.ColumnInt(colIdx), true, nil @@ -363,7 +389,7 @@ func decodeBasic() DecodeFunc { } if colType != sqlite.TypeBlob { - return nil, false, errInvalidType + return nil, false, errInvalidType() } columnValue, err := io.ReadAll(stmt.ColumnReader(colIdx)) diff --git a/service/netquery/orm/encoder.go b/service/netquery/orm/encoder.go index 9d5bd7ae1..2147500d8 100644 --- a/service/netquery/orm/encoder.go +++ b/service/netquery/orm/encoder.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "reflect" + "sync" "time" "golang.org/x/exp/slices" @@ -13,6 +14,7 @@ import ( type ( // EncodeFunc is called for each non-basic type during encoding. + // The column definition is shared between calls and must not be modified. EncodeFunc func(col *ColumnDef, valType reflect.Type, val reflect.Value) (interface{}, bool, error) // EncodeConfig holds encoding functions. @@ -31,21 +33,24 @@ func ToParamMap(ctx context.Context, r interface{}, keyPrefix string, cfg Encode return nil, fmt.Errorf("%w, got %T", errStructExpected, r) } + fields := getEncoderFields(val.Type()) res := make(map[string]interface{}, val.NumField()) - for i := range val.NumField() { - fieldType := val.Type().Field(i) - field := val.Field(i) + // Build the hook list once instead of for every field. Copy it, so that + // the backing array of cfg.EncodeHooks is never written to. + hooks := make([]EncodeFunc, 0, len(cfg.EncodeHooks)+1) + hooks = append(hooks, cfg.EncodeHooks...) + hooks = append(hooks, encodeBasic()) - // skip unexported fields - if !fieldType.IsExported() { - continue - } + for i := range fields { + ef := &fields[i] + fieldType := &ef.field + field := val.Field(ef.index) - colDef, err := getColumnDef(fieldType) - if err != nil { - return nil, fmt.Errorf("failed to get column definition for %s: %w", fieldType.Name, err) + if ef.colDefErr != nil { + return nil, fmt.Errorf("failed to get column definition for %s: %w", fieldType.Name, ef.colDefErr) } + colDef := ef.colDef if slices.Contains(skipFields, colDef.Name) { continue @@ -55,10 +60,7 @@ func ToParamMap(ctx context.Context, r interface{}, keyPrefix string, cfg Encode colDef, fieldType.Type, field, - append( - cfg.EncodeHooks, - encodeBasic(), - ), + hooks, ) if err != nil { return nil, fmt.Errorf("failed to run encode hooks: %w", err) @@ -70,13 +72,57 @@ func ToParamMap(ctx context.Context, r interface{}, keyPrefix string, cfg Encode } } - res[keyPrefix+sqlColumnName(fieldType)] = x - + res[keyPrefix+ef.columnName] = x } return res, nil } +// encoderField holds the per-type metadata of an exported struct field that +// ToParamMap needs to encode it. +type encoderField struct { + index int + field reflect.StructField + colDef *ColumnDef + colDefErr error + columnName string +} + +// encoderFieldsCache caches the encoder fields of struct types. +// It maps reflect.Type to []encoderField. +var encoderFieldsCache sync.Map + +// getEncoderFields returns the metadata of all exported fields of the given +// struct type. Parsing the struct tags is only done once per type, as it +// otherwise dominates the cost of encoding a row. +func getEncoderFields(t reflect.Type) []encoderField { + if cached, ok := encoderFieldsCache.Load(t); ok { + return cached.([]encoderField) //nolint:forcetypeassert // Only this function stores values. + } + + fields := make([]encoderField, 0, t.NumField()) + for i := range t.NumField() { + fieldType := t.Field(i) + + // skip unexported fields + if !fieldType.IsExported() { + continue + } + + colDef, err := getColumnDef(fieldType) + fields = append(fields, encoderField{ + index: i, + field: fieldType, + colDef: colDef, + colDefErr: err, + columnName: sqlColumnName(fieldType), + }) + } + + encoderFieldsCache.Store(t, fields) + return fields +} + // EncodeValue encodes the given value. func EncodeValue(ctx context.Context, colDef *ColumnDef, val interface{}, cfg EncodeConfig) (interface{}, error) { fieldValue := reflect.ValueOf(val) diff --git a/service/netquery/orm/encoder_cache_test.go b/service/netquery/orm/encoder_cache_test.go new file mode 100644 index 000000000..385b98da6 --- /dev/null +++ b/service/netquery/orm/encoder_cache_test.go @@ -0,0 +1,125 @@ +package orm + +import ( + "context" + "reflect" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type encoderCacheTestRow struct { + ID string `sqlite:"id,primary"` + private string //nolint:unused // Must be ignored by the encoder. + Count uint16 `sqlite:"count"` + Started time.Time `sqlite:"started,text,time"` + Ended *time.Time `sqlite:"ended,text,time"` + Allowed *bool `sqlite:"allowed"` + Name *string `sqlite:"name"` + Untagged float64 + Skipped uint64 `sqlite:"skipped,default=0"` +} + +func TestToParamMapCachedFields(t *testing.T) { + t.Parallel() + + ctx := context.Background() + ended := time.Date(2022, time.February, 15, 10, 0, 0, 0, time.UTC) + allowed := false + full := encoderCacheTestRow{ + ID: "a", + Count: 7, + Started: time.Date(2022, time.February, 15, 9, 51, 0, 0, time.UTC), + Ended: &ended, + Allowed: &allowed, + Untagged: 1.5, + Skipped: 3, + } + + // Encode several times, by value and by pointer, so that the cached + // field metadata is used. + for range 3 { + for _, input := range []any{full, &full} { + m, err := ToParamMap(ctx, input, ":", DefaultEncodeConfig, []string{"skipped"}) + require.NoError(t, err) + assert.Equal(t, map[string]any{ + ":id": "a", + ":count": uint16(7), + ":started": "2022-02-15 09:51:00", + ":ended": "2022-02-15 10:00:00", + ":allowed": false, + ":name": nil, + ":Untagged": 1.5, + }, m) + } + } + + // Zero time and nil pointers. + m, err := ToParamMap(ctx, encoderCacheTestRow{}, "", DefaultEncodeConfig, nil) + require.NoError(t, err) + assert.Equal(t, map[string]any{ + "id": "", + "count": uint16(0), + "started": nil, + "ended": nil, + "allowed": nil, + "name": nil, + "Untagged": 0.0, + "skipped": uint64(0), + }, m) + + // A different type with the same field names must not use the cached + // metadata of the first type. + m, err = ToParamMap(ctx, struct { + ID int `sqlite:"other_id"` + Count string + }{ID: 1, Count: "x"}, "", DefaultEncodeConfig, nil) + require.NoError(t, err) + assert.Equal(t, map[string]any{"other_id": 1, "Count": "x"}, m) +} + +func TestToParamMapColumnDefError(t *testing.T) { + t.Parallel() + + type withIgnored struct { + A string + B string `sqlite:"-"` + } + + // Fields that cannot be described as a column fail the encoding, also + // when the metadata comes from the cache. + for range 2 { + _, err := ToParamMap(context.Background(), withIgnored{}, "", DefaultEncodeConfig, nil) + require.ErrorIs(t, err, errSkipStructField) + } + + _, err := ToParamMap(context.Background(), "not a struct", "", DefaultEncodeConfig, nil) + require.ErrorIs(t, err, errStructExpected) +} + +func TestToParamMapDoesNotModifyHooks(t *testing.T) { + t.Parallel() + + var calls int + hook := func(*ColumnDef, reflect.Type, reflect.Value) (any, bool, error) { + calls++ + return nil, false, nil + } + sentinel := func(*ColumnDef, reflect.Type, reflect.Value) (any, bool, error) { + return "sentinel", true, nil + } + + // Hooks with spare capacity: the basic encoder must not be written into + // the backing array of the caller. + backing := []EncodeFunc{hook, sentinel} + hooks := backing[:1] + + m, err := ToParamMap(context.Background(), struct{ A, B int }{1, 2}, "", EncodeConfig{EncodeHooks: hooks}, nil) + require.NoError(t, err) + assert.Equal(t, map[string]any{"A": 1, "B": 2}, m) + assert.Equal(t, 2, calls) + res, _, _ := backing[1](nil, nil, reflect.Value{}) + assert.Equal(t, "sentinel", res) +} diff --git a/service/netquery/orm/query_runner.go b/service/netquery/orm/query_runner.go index 6eff986ce..63d0affb8 100644 --- a/service/netquery/orm/query_runner.go +++ b/service/netquery/orm/query_runner.go @@ -139,10 +139,16 @@ func RunQuery(ctx context.Context, conn *sqlite.Conn, sql string, modifiers ...Q valType := sliceVal.Type() valElemType = valType.Elem() + var names *columnNameStmt opts.ResultFunc = func(stmt *sqlite.Stmt) error { currentField := reflect.New(valElemType) - if err := DecodeStmt(ctx, &args.Schema, stmt, currentField.Interface(), args.DecodeConfig); err != nil { + if names == nil || names.Stmt != stmt { + names = newColumnNameStmt(stmt) + } + + err := DecodeStmt(ctx, &args.Schema, names, currentField.Interface(), args.DecodeConfig) + if err != nil { resultDump := make(map[string]any) for colIdx := range stmt.ColumnCount() { @@ -184,3 +190,34 @@ func RunQuery(ctx context.Context, conn *sqlite.Conn, sql string, modifiers ...Q return nil } + +// columnNameStmt caches the column names of a statement. +// sqlite.Stmt.ColumnName searches a map of all columns on every call, which +// makes decoding a row quadratic in the number of columns. The names do not +// change while the rows of a statement are stepped through. +type columnNameStmt struct { + *sqlite.Stmt + + names []string +} + +func newColumnNameStmt(stmt *sqlite.Stmt) *columnNameStmt { + names := make([]string, stmt.ColumnCount()) + for i := range names { + names[i] = stmt.ColumnName(i) + } + + return &columnNameStmt{ + Stmt: stmt, + names: names, + } +} + +// ColumnName returns the name of the column at index col. +func (s *columnNameStmt) ColumnName(col int) string { + if col >= 0 && col < len(s.names) { + return s.names[col] + } + + return s.Stmt.ColumnName(col) +} diff --git a/service/netquery/orm/schema_builder.go b/service/netquery/orm/schema_builder.go index 89381cb82..2f2da42e3 100644 --- a/service/netquery/orm/schema_builder.go +++ b/service/netquery/orm/schema_builder.go @@ -45,7 +45,7 @@ type ( } // ColumnDef defines a SQL column. - ColumnDef struct { //nolint:maligned + ColumnDef struct { Name string Nullable bool Type sqlite.ColumnType @@ -61,8 +61,12 @@ type ( // GetColumnDef returns the column definition with the given name. func (ts TableSchema) GetColumnDef(name string) *ColumnDef { - for _, def := range ts.Columns { - if def.Name == name { + // Index into the slice instead of ranging by value: the range variable + // escapes through the returned pointer, so it would be heap-allocated + // for every visited column. Only the match is copied. + for i := range ts.Columns { + if ts.Columns[i].Name == name { + def := ts.Columns[i] return &def } } diff --git a/service/netquery/pagination_test.go b/service/netquery/pagination_test.go new file mode 100644 index 000000000..1c6ff2e49 --- /dev/null +++ b/service/netquery/pagination_test.go @@ -0,0 +1,227 @@ +package netquery + +import ( + "context" + "encoding/json" + "fmt" + "reflect" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "zombiezen.com/go/sqlite" + "zombiezen.com/go/sqlite/sqlitex" + + "github.com/safing/portmaster/service/netquery/orm" +) + +func newPagedTestRequest(page, pageSize int) *QueryRequestPayload { + return &QueryRequestPayload{ + Select: Selects{{Field: "id"}}, + Query: Query{"profile": []Matcher{{Equal: "test/profile"}}}, + OrderBy: OrderBys{{Field: "id"}}, + Pagination: Pagination{Page: page, PageSize: pageSize}, + } +} + +// TestPaginationSQLIsStable verifies that LIMIT and OFFSET are bound as +// parameters so that the generated SQL text (which is the key of the +// per-connection prepared statement cache) does not depend on the +// requested page or page size. +func TestPaginationSQLIsStable(t *testing.T) { + t.Parallel() + + schema, err := orm.GenerateTableSchema("connections", Conn{}) + require.NoError(t, err) + + cases := []struct { + page, pageSize int + wantLimit, wantOffs int + }{ + {0, 0, 100, 0}, // default page size + {0, 25, 25, 0}, // first page + {3, 25, 25, 75}, // later page + {2, 1000, 100, 200}, // page size capped at 100 + {-1, 10, 10, 0}, // negative page -> no offset + {7, -5, 100, 700}, // negative page size -> default + } + + distinctSQL := make(map[string]struct{}) + for _, tc := range cases { + sql, params, err := newPagedTestRequest(tc.page, tc.pageSize).generateSQL(context.Background(), schema) + require.NoError(t, err) + distinctSQL[sql] = struct{}{} + + assert.Equal(t, tc.wantLimit, params[paginationLimitParam], "limit for page=%d size=%d", tc.page, tc.pageSize) + assert.Equal(t, tc.wantOffs, params[paginationOffsetParam], "offset for page=%d size=%d", tc.page, tc.pageSize) + assert.Equal(t, "test/profile", params[":profile0eq0"]) + assert.NotContains(t, sql, fmt.Sprintf("LIMIT %d", tc.wantLimit)) + } + + for page := range 50 { + for size := 1; size <= 100; size++ { + sql, _, err := newPagedTestRequest(page, size).generateSQL(context.Background(), schema) + require.NoError(t, err) + distinctSQL[sql] = struct{}{} + } + } + + assert.Len(t, distinctSQL, 1, "SQL text must not depend on pagination: %v", distinctSQL) +} + +// cachedStmtCount returns the number of persistent prepared statements +// cached by conn (zombiezen's Conn.Prepare caches statements keyed by +// SQL text and never evicts them). +func cachedStmtCount(t *testing.T, conn *sqlite.Conn) int { + t.Helper() + + field := reflect.ValueOf(conn).Elem().FieldByName("stmts") + if !field.IsValid() || field.Kind() != reflect.Map { + t.Skip("cannot inspect statement cache of sqlite.Conn") + } + + return field.Len() +} + +func openPagingTestConn(t *testing.T, rows int) (*sqlite.Conn, *orm.TableSchema) { + t.Helper() + + schema, err := orm.GenerateTableSchema("connections", Conn{}) + require.NoError(t, err) + + conn, err := sqlite.OpenConn(":memory:") + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + + require.NoError(t, sqlitex.ExecuteTransient(conn, schema.CreateStatement("main", false), nil)) + + for i := range rows { + profile := "test/profile" + if i%3 == 0 { + profile = "other/profile" + } + connMap, err := orm.ToParamMap(context.Background(), Conn{ + ID: fmt.Sprintf("conn-%05d", i), + ProfileID: profile, + Type: "ip", + Started: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), + ExtraData: json.RawMessage("{}"), + }, "", orm.DefaultEncodeConfig, nil) + require.NoError(t, err) + + columns := make([]string, 0, len(connMap)) + placeholders := make([]string, 0, len(connMap)) + values := make(map[string]any, len(connMap)) + for key, value := range connMap { + columns = append(columns, key) + placeholders = append(placeholders, ":"+key) + values[":"+key] = value + } + + require.NoError(t, sqlitex.ExecuteTransient(conn, + "INSERT INTO main.connections ("+strings.Join(columns, ", ")+") VALUES ("+strings.Join(placeholders, ", ")+")", + &sqlitex.ExecOptions{Named: values}, + )) + } + + return conn, schema +} + +// TestPaginationEndToEnd runs paged queries against an in-memory database +// and verifies that results are correct and that paging through the +// results does not grow the per-connection prepared statement cache. +func TestPaginationEndToEnd(t *testing.T) { + t.Parallel() + + const totalRows = 300 + conn, schema := openPagingTestConn(t, totalRows) + + var want []string + for i := range totalRows { + if i%3 != 0 { + want = append(want, fmt.Sprintf("conn-%05d", i)) + } + } + + type row struct { + ID string `sqlite:"id"` + } + + runPage := func(page, size int) []string { + sql, params, err := newPagedTestRequest(page, size).generateSQL(context.Background(), schema) + require.NoError(t, err) + + var result []row + require.NoError(t, orm.RunQuery(context.Background(), conn, sql, orm.WithNamedArgs(params), orm.WithResult(&result))) + + ids := make([]string, 0, len(result)) + for _, r := range result { + ids = append(ids, r.ID) + } + return ids + } + + baseline := cachedStmtCount(t, conn) + + // Page through all results with various page sizes and verify the + // concatenation of all pages equals the full, ordered result set. + for _, size := range []int{1, 7, 25, 64, 100, 500} { + var got []string + for page := 0; ; page++ { + ids := runPage(page, size) + got = append(got, ids...) + + effective := min(size, 100) + if len(ids) < effective { + break + } + } + assert.Equal(t, want, got, "page size %d", size) + } + + // Default page size (0 -> 100) on the first page. + assert.Equal(t, want[:100], runPage(0, 0)) + + // Hundreds of different page/size combinations must only ever have + // produced a single cached statement. + assert.Equal(t, 1, cachedStmtCount(t, conn)-baseline, "paging must reuse one prepared statement") +} + +// BenchmarkPagedQuery measures paging through results on a single +// connection, as the UI does when scrolling through the connection +// history, and reports the number of statements left in the cache. +func BenchmarkPagedQuery(b *testing.B) { + schema, err := orm.GenerateTableSchema("connections", Conn{}) + require.NoError(b, err) + + conn, err := sqlite.OpenConn(":memory:") + require.NoError(b, err) + defer func() { _ = conn.Close() }() + require.NoError(b, sqlitex.ExecuteTransient(conn, schema.CreateStatement("main", false), nil)) + + type row struct { + ID string `sqlite:"id"` + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; b.Loop(); i++ { + sql, params, err := newPagedTestRequest(i, 25).generateSQL(context.Background(), schema) + if err != nil { + b.Fatal(err) + } + var result []row + err = orm.RunQuery(context.Background(), conn, sql, orm.WithNamedArgs(params), orm.WithResult(&result)) + if err != nil { + b.Fatal(err) + } + } + b.StopTimer() + + field := reflect.ValueOf(conn).Elem().FieldByName("stmts") + if field.IsValid() && field.Kind() == reflect.Map { + b.ReportMetric(float64(field.Len()), "cached-stmts") + } +} diff --git a/service/netquery/query.go b/service/netquery/query.go index cb84ac307..8859fc93a 100644 --- a/service/netquery/query.go +++ b/service/netquery/query.go @@ -28,8 +28,6 @@ const ( // Collection of Query and Matcher types. // NOTE: whenever adding support for new operators make sure // to update UnmarshalJSON as well. -// -//nolint:golint type ( Query map[string][]Matcher @@ -191,12 +189,20 @@ func (query *Query) UnmarshalJSON(blob []byte) error { return nil } +// Named SQL parameters used for pagination. Matcher parameters always end +// with a digit (see Matcher.toSQLConditionClause) and the text-search +// parameter is ":t", so these names cannot collide with them. +const ( + paginationLimitParam = ":pageLimit" + paginationOffsetParam = ":pageOffset" +) + // TODO(ppacher): right now we only support LIMIT and OFFSET for pagination but that // has an issue that loading the same page twice might yield different results due to // new records shifting the result slice. To overcome this, return a "PageToken" to the // user that includes the time the initial query was created so paginated queries can // ensure new records don't end up in the result set. -func (page *Pagination) toSQLLimitOffsetClause() string { +func (page *Pagination) toSQLLimitOffsetClause() (string, map[string]any) { limit := page.PageSize // default and cap the limit to at most 100 items @@ -206,13 +212,20 @@ func (page *Pagination) toSQLLimitOffsetClause() string { limit = 100 } - sql := fmt.Sprintf("LIMIT %d", limit) - + offset := 0 if page.Page > 0 { - sql += fmt.Sprintf(" OFFSET %d", page.Page*limit) + offset = page.Page * limit } - return sql + // LIMIT and OFFSET are bound as parameters instead of being inlined + // into the SQL text. Queries are prepared via the per-connection + // statement cache which is keyed by the SQL text and never evicted, + // so inlining the numbers would create a new cached statement for + // every distinct page/page-size. + return "LIMIT " + paginationLimitParam + " OFFSET " + paginationOffsetParam, map[string]any{ + paginationLimitParam: limit, + paginationOffsetParam: offset, + } } func parseMatcher(raw json.RawMessage) (*Matcher, error) { diff --git a/service/netquery/query_cancel_test.go b/service/netquery/query_cancel_test.go new file mode 100644 index 000000000..848484f96 --- /dev/null +++ b/service/netquery/query_cancel_test.go @@ -0,0 +1,68 @@ +package netquery + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/service/netquery/orm" +) + +// slowQuery counts to a huge number with a recursive CTE. Uninterrupted it +// keeps a pooled read connection busy for minutes. +const slowQuery = `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x < :limit) SELECT count(*) AS n FROM c` + +// TestExecuteInterruptedByContext verifies that cancelling the (request) +// context passed to Execute and ExecuteBatch, as the HTTP query handlers do, +// aborts the running statement and returns the connection to the pool in a +// usable state. +func TestExecuteInterruptedByContext(t *testing.T) { //nolint:paralleltest // uses the package-level module. + db := newTestDatabase(t) + slowArgs := map[string]any{":limit": int64(5_000_000_000)} + + run := func(name string, exec func(ctx context.Context) error) { + t.Helper() + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + start := time.Now() + err := exec(ctx) + elapsed := time.Since(start) + + require.Error(t, err, name) + assert.ErrorIs(t, err, context.DeadlineExceeded, name) + assert.Less(t, elapsed, 2*time.Second, "%s: query was not interrupted by the context", name) + t.Logf("%s returned after %s: %s", name, elapsed, err) + } + + // Run more cancelled queries than the pool has connections, so that + // interrupted connections are reused. + for range 12 { + run("Execute", func(ctx context.Context) error { + var result []map[string]any + return db.Execute(ctx, slowQuery, orm.WithNamedArgs(slowArgs), orm.WithResult(&result)) + }) + } + run("ExecuteBatch", func(ctx context.Context) error { + var result []map[string]any + return db.ExecuteBatch(ctx, []BatchExecute{{ID: "slow", SQL: slowQuery, Params: slowArgs, Result: &result}}) + }) + + // Every pooled connection, including the interrupted ones, must still + // work, including the cached, previously interrupted statement. + for _, conn := range acquirePoolConnections(t, db, 10) { + assert.Equal(t, "1", pragma(t, conn, "SELECT 1")) + } + for range 12 { + var result []struct { + N int `sqlite:"n"` + } + require.NoError(t, db.Execute(context.Background(), slowQuery, orm.WithNamedArgs(map[string]any{":limit": int64(1000)}), orm.WithResult(&result))) + require.Len(t, result, 1) + assert.Equal(t, 1000, result[0].N) + } +} diff --git a/service/netquery/query_handler.go b/service/netquery/query_handler.go index 1e3afbff2..109b201f0 100644 --- a/service/netquery/query_handler.go +++ b/service/netquery/query_handler.go @@ -86,14 +86,6 @@ func (qh *QueryHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { } timingQueryExecute.Stop() - // send the HTTP status code - resp.WriteHeader(http.StatusOK) - - // prepare the result encoder. - enc := json.NewEncoder(resp) - enc.SetEscapeHTML(false) - enc.SetIndent("", " ") - // prepare the result body that, in dev mode, contains // some diagnostics data about the query var resultBody map[string]interface{} @@ -111,16 +103,7 @@ func (qh *QueryHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { } resultBody["results"] = result - // and finally stream the response - if err := enc.Encode(resultBody); err != nil { - // we failed to encode the JSON body to resp so we likely either already sent a - // few bytes or the pipe was already closed. In either case, trying to send the - // error using http.Error() is non-sense. We just log it out here and that's all - // we can do. - log.Errorf("failed to encode JSON response: %s", err) - - return - } + writeJSONResponse(resp, http.StatusOK, resultBody) } func (batch *BatchQueryHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { @@ -195,24 +178,7 @@ func (batch *BatchQueryHandler) ServeHTTP(resp http.ResponseWriter, req *http.Re response[b.ID] = *b.Result } - // send the HTTP status code - resp.WriteHeader(status) - - // prepare the result encoder. - enc := json.NewEncoder(resp) - enc.SetEscapeHTML(false) - enc.SetIndent("", " ") - - // and finally stream the response - if err := enc.Encode(response); err != nil { - // we failed to encode the JSON body to resp so we likely either already sent a - // few bytes or the pipe was already closed. In either case, trying to send the - // error using http.Error() is non-sense. We just log it out here and that's all - // we can do. - log.Errorf("failed to encode JSON response: %s", err) - - return - } + writeJSONResponse(resp, status, response) } func parseQueryRequestPayload[T any](req *http.Request) (*T, error) { //nolint:dupl @@ -249,3 +215,26 @@ func parseQueryRequestPayload[T any](req *http.Request) (*T, error) { //nolint:d // Compile time check. var _ http.Handler = new(QueryHandler) + +// writeJSONResponse encodes body as JSON and sends it with the given status. +// The body is encoded before the status is sent, so that an encoding error +// can still be reported as a server error instead of an empty response. +func writeJSONResponse(resp http.ResponseWriter, status int, body any) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + err := enc.Encode(body) + if err != nil { + log.Errorf("failed to encode JSON response: %s", err) + http.Error(resp, "failed to encode response: "+err.Error(), http.StatusInternalServerError) + return + } + + resp.WriteHeader(status) + _, err = resp.Write(buf.Bytes()) + if err != nil { + // The client is likely gone, nothing else to do. + log.Debugf("failed to write JSON response: %s", err) + } +} diff --git a/service/netquery/query_handler_bench_test.go b/service/netquery/query_handler_bench_test.go new file mode 100644 index 000000000..d4c2d48fc --- /dev/null +++ b/service/netquery/query_handler_bench_test.go @@ -0,0 +1,62 @@ +package netquery + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + + "github.com/stretchr/testify/require" +) + +// newQueryBenchDatabase returns a database with n fully populated +// connections in the live database. +func newQueryBenchDatabase(b *testing.B, n int) *Database { + b.Helper() + + db := newTestDatabase(b) + ctx := context.Background() + conn := newBenchConn() + for i := range n { + conn.ID = "bench-" + strconv.Itoa(i) + conn.RemotePort = uint16(i) //nolint:gosec // Benchmark data. + require.NoError(b, db.Save(ctx, conn, false)) + } + + return db +} + +func runQueryHandlerBench(b *testing.B, query string) { + b.Helper() + + db := newQueryBenchDatabase(b, 1000) + handler := &QueryHandler{ + IsDevMode: func() bool { return false }, + Database: db, + } + target := "/query?q=" + url.QueryEscape(query) + + b.ReportAllocs() + for b.Loop() { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, nil)) + if rec.Code != http.StatusOK { + b.Fatalf("unexpected status %d: %s", rec.Code, rec.Body.String()) + } + } +} + +// BenchmarkQueryHandlerConnections measures the query API as used by the +// connection list of the UI: a full page (100 rows) of all columns, decoded +// into maps and JSON encoded. +func BenchmarkQueryHandlerConnections(b *testing.B) { + runQueryHandlerBench(b, `{"query":{"profile":"local/firefox"},"orderBy":[{"field":"started","desc":true}],"pageSize":100}`) +} + +// BenchmarkQueryHandlerGrouped measures an aggregated query as used by the +// UI to group connections by domain. +func BenchmarkQueryHandlerGrouped(b *testing.B) { + runQueryHandlerBench(b, `{"select":["domain","remote_port",{"$count":{"field":"*","as":"totalCount"}}],"groupBy":["domain","remote_port"],"pageSize":100}`) +} diff --git a/service/netquery/query_handler_extradata_test.go b/service/netquery/query_handler_extradata_test.go new file mode 100644 index 000000000..6db35b891 --- /dev/null +++ b/service/netquery/query_handler_extradata_test.go @@ -0,0 +1,40 @@ +package netquery + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestQueryHandlerEmptyExtraData checks that a connection with empty extra +// data is returned as a valid JSON response. +func TestQueryHandlerEmptyExtraData(t *testing.T) { + t.Parallel() + + db := newTestDatabase(t) + conn := newBenchConn() + conn.ID = "empty-extra-data" + conn.ExtraData = json.RawMessage{} + require.NoError(t, db.Save(context.Background(), conn, false)) + + handler := &QueryHandler{ + IsDevMode: func() bool { return false }, + Database: db, + } + query := `{"query":{"id":"empty-extra-data"},"pageSize":10}` + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/query?q="+url.QueryEscape(query), nil)) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + var body struct { + Results []map[string]json.RawMessage `json:"results"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body), "response is not valid JSON: %q", rec.Body.String()) + require.Len(t, body.Results, 1) + require.Equal(t, "null", string(body.Results[0]["extra_data"])) +} diff --git a/service/netquery/query_request.go b/service/netquery/query_request.go index 97fc5789b..ff0b2ff9a 100644 --- a/service/netquery/query_request.go +++ b/service/netquery/query_request.go @@ -100,7 +100,10 @@ func (req *QueryRequestPayload) generateSQL(ctx context.Context, schema *orm.Tab query := `SELECT ` + selectClause + ` FROM ( ` + source + ` ) ` - query += " " + groupByClause + " " + orderByClause + " " + req.Pagination.toSQLLimitOffsetClause() + limitOffsetClause, limitOffsetParams := req.toSQLLimitOffsetClause() + req.mergeParams(limitOffsetParams) + + query += " " + groupByClause + " " + orderByClause + " " + limitOffsetClause return strings.TrimSpace(query), req.paramMap, nil } diff --git a/service/netquery/query_test.go b/service/netquery/query_test.go index 16a9aab71..219ab7ff5 100644 --- a/service/netquery/query_test.go +++ b/service/netquery/query_test.go @@ -190,7 +190,7 @@ func TestQueryBuilder(t *testing.T) { //nolint:tparallel }, "", nil, - fmt.Errorf("1 error occurred:\n\t* column forbiddenField is not allowed\n\n"), //nolint:golint + fmt.Errorf("1 error occurred:\n\t* column forbiddenField is not allowed\n\n"), //nolint:err113 // expected error text of the query under test }, { "Complex example", diff --git a/service/netquery/runtime_query_runner.go b/service/netquery/runtime_query_runner.go index bb3ffbad8..1e9929a47 100644 --- a/service/netquery/runtime_query_runner.go +++ b/service/netquery/runtime_query_runner.go @@ -53,7 +53,11 @@ func (runner *RuntimeQueryRunner) get(keyOrPrefix string) ([]record.Record, erro log.Infof("netquery: executing custom SQL query: %q", query) var result []map[string]interface{} - if err := runner.db.Execute(context.Background(), query, orm.WithResult(&result)); err != nil { + // The query is arbitrary SQL taken from the record key, so run it as a + // transient statement: a persistent one would be cached on the pooled + // read connection, keyed by the SQL text, for the connection's lifetime. + err := runner.db.Execute(context.Background(), query, orm.WithResult(&result), orm.WithTransient()) + if err != nil { return nil, fmt.Errorf("failed to perform query %q: %w", query, err) } diff --git a/service/netquery/runtime_query_runner_test.go b/service/netquery/runtime_query_runner_test.go new file mode 100644 index 000000000..daf156f9d --- /dev/null +++ b/service/netquery/runtime_query_runner_test.go @@ -0,0 +1,49 @@ +package netquery + +import ( + "context" + "fmt" + "testing" + + "github.com/jackc/puddle/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "zombiezen.com/go/sqlite" + + "github.com/safing/portmaster/base/runtime" +) + +// TestRuntimeQueryRunnerDoesNotCacheStatements verifies that ad-hoc SQL +// queries received via the runtime database are not added to the statement +// cache of the pooled read connection. +func TestRuntimeQueryRunnerDoesNotCacheStatements(t *testing.T) { + t.Parallel() + + pool, err := puddle.NewPool(&puddle.Config[*sqlite.Conn]{ + Constructor: func(context.Context) (*sqlite.Conn, error) { + return sqlite.OpenConn(":memory:") + }, + Destructor: func(c *sqlite.Conn) { _ = c.Close() }, + MaxSize: 1, + }) + require.NoError(t, err) + t.Cleanup(pool.Close) + + runner := &RuntimeQueryRunner{ + db: &Database{readConnPool: pool}, + reg: runtime.NewRegistry(), + keyPrefix: "netquery/query/", + } + + for i := range 50 { + records, err := runner.get(fmt.Sprintf("netquery/query/SELECT %d AS value", i)) + require.NoError(t, err) + require.Len(t, records, 1) + } + + res, err := pool.Acquire(context.Background()) + require.NoError(t, err) + defer res.Release() + + assert.Equal(t, 0, cachedStmtCount(t, res.Value()), "ad-hoc runtime queries must not be cached") +} diff --git a/service/netquery/save_bench_test.go b/service/netquery/save_bench_test.go new file mode 100644 index 000000000..c69799ee0 --- /dev/null +++ b/service/netquery/save_bench_test.go @@ -0,0 +1,178 @@ +package netquery + +import ( + "context" + "encoding/json" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/service/netquery/orm" + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/netutils" +) + +// benchDomain is the domain of the benchmark connections. +const benchDomain = "www.example.com." + +// benchSkipFields are the fields Database.Save does not encode. +var benchSkipFields = []string{"bytes_received", "bytes_sent"} + +// newBenchConn returns a fully populated connection model, as produced by +// convertConnection for an ended outbound connection. +func newBenchConn() Conn { + ended := time.Unix(1700000100, 0) + allowed := true + exitNode := "exit-node-id" + return Conn{ + ID: "1234-1700000000-6-192.168.1.10-51234-93.184.216.34-443", + ProfileID: "local/firefox", + Path: "/usr/lib/firefox/firefox", + Type: "ip", + IPVersion: 4, + IPProtocol: 6, + LocalIP: "192.168.1.10", + LocalPort: 51234, + RemoteIP: "93.184.216.34", + RemotePort: 443, + Domain: benchDomain, + Country: "US", + ASN: 15133, + ASOwner: "Edgecast Inc.", + Latitude: 42.1, + Longitude: -71.2, + Scope: netutils.Global, + WorstVerdict: network.VerdictAccept, + ActiveVerdict: network.VerdictAccept, + FirewallVerdict: network.VerdictAccept, + Started: time.Unix(1700000000, 0), + Ended: &ended, + Encrypted: true, + Direction: "outbound", + ExtraData: json.RawMessage(`{"pid":1234,"processCreatedAt":1700000000,"cname":["e1.example.net."],"reason":{"Msg":"default permit"}}`), + Allowed: &allowed, + ProfileRevision: 3, + ExitNode: &exitNode, + ProfileName: "Firefox", + } +} + +// BenchmarkToParamMapConn measures encoding a connection model into the +// parameter map that Database.Save uses for every saved connection. +func BenchmarkToParamMapConn(b *testing.B) { + ctx := context.Background() + conn := newBenchConn() + + b.ReportAllocs() + for b.Loop() { + _, err := orm.ToParamMap(ctx, conn, "", orm.DefaultEncodeConfig, benchSkipFields) + if err != nil { + b.Fatal(err) + } + } +} + +// BenchmarkSave measures Database.Save for a connection that is first inserted +// and then updated, without the history database. +func BenchmarkSave(b *testing.B) { + db := newTestDatabase(b) + ctx := context.Background() + conn := newBenchConn() + + var i int + b.ReportAllocs() + for b.Loop() { + // Insert a new connection on every second iteration and update it on + // the other one. + conn.ID = "bench-" + strconv.Itoa(i/2) + i++ + err := db.Save(ctx, conn, false) + if err != nil { + b.Fatal(err) + } + } +} + +func TestToParamMapConnStable(t *testing.T) { + t.Parallel() + + ctx := context.Background() + conn := newBenchConn() + + m, err := orm.ToParamMap(ctx, conn, "", orm.DefaultEncodeConfig, benchSkipFields) + require.NoError(t, err) + require.Len(t, m, 33) + require.NotContains(t, m, "bytes_received") + require.Equal(t, "2023-11-14 22:13:20", m["started"]) + require.Equal(t, "2023-11-14 22:15:00", m["ended"]) + require.Equal(t, true, m["allowed"]) + require.Equal(t, "exit-node-id", m["exit_node"]) + + // Nil pointers and the zero time are stored as NULL. + conn.Ended = nil + conn.Allowed = nil + conn.ExitNode = nil + conn.Started = time.Time{} + m, err = orm.ToParamMap(ctx, conn, "", orm.DefaultEncodeConfig, benchSkipFields) + require.NoError(t, err) + require.Len(t, m, 33) + for _, key := range []string{"ended", "allowed", "exit_node", "started"} { //nolint:goconst // SQL column names. + v, ok := m[key] + require.True(t, ok, key) + require.Nil(t, v, key) + } +} + +func TestSaveQuery(t *testing.T) { + t.Parallel() + + q := newSaveQuery(map[string]any{"id": 1, "b": 2, "a": 3}) + require.Equal(t, []string{"a", "b", "id"}, q.columns) + require.Equal(t, `INSERT INTO main.connections (a, b, id) + VALUES(?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + a = excluded.a, b = excluded.b + `, q.sql(LiveDatabase)) + require.Equal(t, `INSERT INTO history.connections (a, b, id) + VALUES(?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + a = excluded.a, b = excluded.b + `, q.sql(HistoryDatabase)) + require.Equal(t, `INSERT INTO other.connections (a, b, id) + VALUES(?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + a = excluded.a, b = excluded.b + `, q.sql("other")) + + require.True(t, q.matches(map[string]any{"a": nil, "b": nil, "id": nil})) + require.False(t, q.matches(map[string]any{"a": nil, "b": nil})) + require.False(t, q.matches(map[string]any{"a": nil, "b": nil, "c": nil})) + require.False(t, q.matches(map[string]any{"a": nil, "b": nil, "id": nil, "c": nil})) + require.False(t, q.matches(map[string]any{})) +} + +func TestSaveInsertAndUpdate(t *testing.T) { //nolint:paralleltest // Uses the package-level module. + db := newTestDatabase(t) + ctx := context.Background() + + conn := newBenchConn() + conn.ID = "save-test" + require.NoError(t, db.Save(ctx, conn, true)) + conn.Domain = "updated.example.com." + conn.Ended = nil + conn.Active = true + require.NoError(t, db.Save(ctx, conn, true)) + + for _, dbName := range []string{"main", "history"} { + assert.Equal(t, 1, countRows(t, db, "SELECT COUNT(*) AS count FROM "+dbName+".connections WHERE id = 'save-test' AND domain = 'updated.example.com.' AND ended IS NULL AND active = 1"), dbName) + } + + // Without history, only the live database is updated. + conn.Domain = "live.example.com." + require.NoError(t, db.Save(ctx, conn, false)) + assert.Equal(t, 1, countRows(t, db, "SELECT COUNT(*) AS count FROM main.connections WHERE domain = 'live.example.com.'")) + assert.Equal(t, 0, countRows(t, db, "SELECT COUNT(*) AS count FROM history.connections WHERE domain = 'live.example.com.'")) +} diff --git a/service/netquery/save_rows_test.go b/service/netquery/save_rows_test.go new file mode 100644 index 000000000..0494dcf86 --- /dev/null +++ b/service/netquery/save_rows_test.go @@ -0,0 +1,148 @@ +package netquery + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "zombiezen.com/go/sqlite" + "zombiezen.com/go/sqlite/sqlitex" + + "github.com/safing/portmaster/service/netquery/orm" + "github.com/safing/portmaster/service/network" +) + +// newReferenceSaveQuery builds the statements Database.Save used before the +// insert-only columns were left out of the update: an update sets every +// column. +func newReferenceSaveQuery(tb testing.TB) *saveQuery { + tb.Helper() + + connMap, err := orm.ToParamMap(context.Background(), newBenchConn(), "", orm.DefaultEncodeConfig, benchSkipFields) + require.NoError(tb, err) + + q := newSaveQuery(connMap) + updateSets := make([]string, 0, len(q.columns)) + for _, column := range q.columns { + updateSets = append(updateSets, fmt.Sprintf("%s = excluded.%s", column, column)) + } + require.Greater(tb, len(updateSets), strings.Count(q.updateSetList, ",")+1, "no insert-only columns") + q.updateSetList = strings.Join(updateSets, ", ") + q.liveSQL = q.buildSQL(LiveDatabase) + q.historySQL = q.buildSQL(HistoryDatabase) + return q +} + +// dumpConnections returns all columns of all rows of the connections table. +func dumpConnections(tb testing.TB, db *Database, dbName DatabaseName) []string { + tb.Helper() + + var rows []string + db.l.Lock() + defer db.l.Unlock() + // All columns are compared, whatever the schema is. + sql := fmt.Sprintf("SELECT * FROM %s.connections ORDER BY id", dbName) //nolint:unqueryvet + err := sqlitex.Execute(db.writeConn, sql, &sqlitex.ExecOptions{ + ResultFunc: func(stmt *sqlite.Stmt) error { + var row strings.Builder + for i := range stmt.ColumnCount() { + fmt.Fprintf(&row, "%s=%s:%q ", stmt.ColumnName(i), stmt.ColumnType(i), stmt.ColumnText(i)) + } + rows = append(rows, row.String()) + return nil + }, + }) + require.NoError(tb, err) + return rows +} + +// TestSaveStoresSameRowsAsFullUpdate checks that leaving the insert-only +// columns out of the update stores exactly the rows that setting every +// column stored, for inserts and for updates that change every other column. +func TestSaveStoresSameRowsAsFullUpdate(t *testing.T) { //nolint:paralleltest // uses the package-level module. + ctx := context.Background() + + // saveAll saves a typical series of connection updates. + saveAll := func(db *Database) { + for i := range 20 { + history := i%2 == 0 + + // After the decision. + conn := newBenchConn() + conn.ID = "conn-" + strconv.Itoa(i) + conn.Started = time.Unix(1700000000+int64(i), 0) + conn.Ended = nil + conn.Active = true + allowed := false + conn.Allowed = &allowed + conn.ExitNode = nil + require.NoError(t, db.Save(ctx, conn, history)) + + // Bandwidth is updated independently and must survive updates. + require.NoError(t, db.UpdateBandwidth(ctx, history, conn.ProfileID, "", conn.ID, uint64(100*i), uint64(10*i))) + + if i%5 == 4 { + // Only saved once. + continue + } + + // Update that changes every column but the ID and the start. + ended := time.Unix(1700000100+int64(i), 0) + established := true + exitNode := "exit-" + strconv.Itoa(i) + conn.ProfileID = "local/other-" + strconv.Itoa(i) + conn.Path = "/usr/bin/other" + conn.Type = "dns" + conn.External = true + conn.IPVersion = 6 + conn.IPProtocol = 17 + conn.LocalIP = "fd00::1" + conn.LocalPort = 1000 + uint16(i) //nolint:gosec // Small test value. + conn.RemoteIP = "2001:db8::1" + conn.RemotePort = 53 + conn.Domain = "other.example.org." + conn.Country = "AT" + conn.ASN = 1234 + conn.ASOwner = "Other" + conn.Latitude = 48.2 + conn.Longitude = 16.4 + conn.Scope++ + conn.WorstVerdict = network.VerdictBlock + conn.ActiveVerdict = network.VerdictBlock + conn.FirewallVerdict = network.VerdictBlock + conn.Ended = &ended + conn.Active = false + conn.Tunneled = true + conn.Encrypted = false + conn.Internal = true + conn.Direction = "inbound" + conn.ExtraData = json.RawMessage(`{"pid":4321}`) + conn.Allowed = &established + conn.ProfileRevision = 7 + conn.ExitNode = &exitNode + conn.ProfileName = "Other" + require.NoError(t, db.Save(ctx, conn, history)) + } + } + + db := newTestDatabase(t) + saveAll(db) + live, history := dumpConnections(t, db, LiveDatabase), dumpConnections(t, db, HistoryDatabase) + _ = db.Close() + + reference := newTestDatabase(t) + reference.saveQuery.Store(newReferenceSaveQuery(t)) + saveAll(reference) + require.Contains(t, reference.saveQuery.Load().updateSetList, "started = excluded.started", "reference statement was replaced") + + require.Len(t, live, 20) + require.Len(t, history, 10) + assert.Equal(t, dumpConnections(t, reference, LiveDatabase), live) + assert.Equal(t, dumpConnections(t, reference, HistoryDatabase), history) +} diff --git a/service/network/api.go b/service/network/api.go index b326d7ca9..66ff0048a 100644 --- a/service/network/api.go +++ b/service/network/api.go @@ -168,7 +168,10 @@ func AddNetworkDebugData(di *debug.Info, profile, where string) { // Count. total++ - switch conn.Verdict { //nolint:exhaustive + conn.Lock() + verdict := conn.Verdict + conn.Unlock() + switch verdict { //nolint:exhaustive case VerdictAccept, VerdictRerouteToNameserver, VerdictRerouteToSplitTun, @@ -194,13 +197,29 @@ func AddNetworkDebugData(di *debug.Info, profile, where string) { } func buildNetworkDebugInfoData(debugConns []*Connection) string { + // Copy the sort keys while holding the connection lock, as the process + // context may change when a connection is re-attributed. + sorted := make(connectionsByGroup, 0, len(debugConns)) + for _, conn := range debugConns { + conn.Lock() + sorted = append(sorted, connectionSortKey{ + conn: conn, + profile: conn.ProcessContext.Profile, + binaryPath: conn.ProcessContext.BinaryPath, + pid: conn.ProcessContext.PID, + started: conn.Started, + }) + conn.Unlock() + } + // Sort - sort.Sort(connectionsByGroup(debugConns)) + sort.Sort(sorted) // Format lines var buf strings.Builder currentPID := process.UndefinedProcessID - for _, conn := range debugConns { + for _, entry := range sorted { + conn := entry.conn conn.Lock() // Add process infomration if it differs from previous connection. @@ -313,7 +332,17 @@ func (conn *Connection) fmtReasonProfileComponent() string { return conn.Reason.Profile } -type connectionsByGroup []*Connection +// connectionSortKey holds a connection together with a copy of the fields it +// is sorted by, which must only be read while holding the connection lock. +type connectionSortKey struct { + conn *Connection + profile string + binaryPath string + pid int + started int64 +} + +type connectionsByGroup []connectionSortKey func (a connectionsByGroup) Len() int { return len(a) } func (a connectionsByGroup) Swap(i, j int) { a[i], a[j] = a[j], a[i] } @@ -321,20 +350,20 @@ func (a connectionsByGroup) Less(i, j int) bool { // Sort by: // 1. Profile ID - if a[i].ProcessContext.Profile != a[j].ProcessContext.Profile { - return a[i].ProcessContext.Profile < a[j].ProcessContext.Profile + if a[i].profile != a[j].profile { + return a[i].profile < a[j].profile } // 2. Process Binary - if a[i].ProcessContext.BinaryPath != a[j].ProcessContext.BinaryPath { - return a[i].ProcessContext.BinaryPath < a[j].ProcessContext.BinaryPath + if a[i].binaryPath != a[j].binaryPath { + return a[i].binaryPath < a[j].binaryPath } // 3. Process ID - if a[i].ProcessContext.PID != a[j].ProcessContext.PID { - return a[i].ProcessContext.PID < a[j].ProcessContext.PID + if a[i].pid != a[j].pid { + return a[i].pid < a[j].pid } // 4. Started - return a[i].Started < a[j].Started + return a[i].started < a[j].started } diff --git a/service/network/api_race_test.go b/service/network/api_race_test.go new file mode 100644 index 000000000..bdc3a3bb6 --- /dev/null +++ b/service/network/api_race_test.go @@ -0,0 +1,166 @@ +package network + +import ( + "net" + "strconv" + "sync" + "testing" + + "github.com/tevino/abool" + + "github.com/safing/portmaster/base/utils/debug" + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/mgr" +) + +const ( + debugTestProfileSource = "local" + debugTestProfileID = "profile-a" +) + +var setupDebugTestDBOnce sync.Once + +// setupDebugTestDB injects the network database, so that +// AddNetworkDebugData can query the connection store. +func setupDebugTestDB(t *testing.T) { + t.Helper() + + setupDebugTestDBOnce.Do(func() { + if module == nil { + module = &Network{mgr: mgr.New("NetworkTest")} + } + if dbController == nil { + err := registerAsDatabase() + if err != nil { + t.Fatalf("failed to register network database: %s", err) + } + } + }) + if dbController == nil { + t.Fatal("network database is not available") + } +} + +// newDebugTestConnection returns a complete connection that is added to the +// connection store. The returned function removes it again. +func newDebugTestConnection(id string) (*Connection, func()) { + conn := &Connection{ + ID: id, + Type: IPConnection, + IPProtocol: 6, + LocalIP: net.ParseIP("127.0.0.1"), + LocalPort: 1234, + Entity: &intel.Entity{IP: net.ParseIP("127.0.0.2"), Port: 443}, + Verdict: VerdictAccept, + Started: 1, + dataComplete: abool.NewBool(true), + ProcessContext: ProcessContext{ + Source: debugTestProfileSource, + Profile: debugTestProfileID, + PID: 1000, + }, + } + conn.SetKey(makeKey(1000, dbScopeIP, conn.ID)) + conns.add(conn) + return conn, func() { conns.delete(conn) } +} + +// TestAddNetworkDebugDataRace checks that the network debug data can be +// collected while the packet handlers change the verdict of the connections. +// Run with -race. +func TestAddNetworkDebugDataRace(t *testing.T) { //nolint:paralleltest // Modifies the global connection store. + setupDebugTestDB(t) + + testConns := make([]*Connection, 0, 10) + for i := range 10 { + conn, remove := newDebugTestConnection("debug-data-race-" + strconv.Itoa(i)) + defer remove() + testConns = append(testConns, conn) + } + + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + for _, conn := range testConns { + // Like the filter handler and a re-evaluation of the verdict. + conn.Lock() + if i%2 == 0 { + conn.SetVerdict(VerdictBlock, "blocked", "", nil) + } else { + conn.SetVerdict(VerdictAccept, "allowed", "", nil) + } + conn.BytesReceived += 100 + conn.Unlock() + } + } + }) + + for range 50 { + di := new(debug.Info) + AddNetworkDebugData(di, "", "") + } + close(stop) + wg.Wait() +} + +// TestBuildNetworkDebugInfoDataRace checks that the network debug data can +// be formatted while connections are re-attributed to another profile. +// Run with -race. +func TestBuildNetworkDebugInfoDataRace(t *testing.T) { + t.Parallel() + + testConns := make([]*Connection, 0, 10) + for i := range 10 { + testConns = append(testConns, &Connection{ + ID: "debug-info-race-" + strconv.Itoa(i), + Type: IPConnection, + Entity: &intel.Entity{}, + Started: int64(i), + dataComplete: abool.NewBool(true), + ProcessContext: ProcessContext{ + Source: debugTestProfileSource, + Profile: debugTestProfileID, + PID: 1000 + i%3, + }, + }) + } + + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + for _, conn := range testConns { + // Like reAttributeConnection. + conn.Lock() + if i%2 == 0 { + conn.ProcessContext = ProcessContext{Source: debugTestProfileSource, Profile: "profile-with-a-longer-id-b", PID: conn.ProcessContext.PID} + } else { + conn.ProcessContext = ProcessContext{Source: debugTestProfileSource, Profile: debugTestProfileID, PID: conn.ProcessContext.PID} + } + conn.Unlock() + } + } + }) + + for range 50 { + debugConns := make([]*Connection, len(testConns)) + copy(debugConns, testConns) + if buildNetworkDebugInfoData(debugConns) == "" { + t.Error("debug info must not be empty") + break + } + } + close(stop) + wg.Wait() +} diff --git a/service/network/api_test.go b/service/network/api_test.go index c44109b01..61fd3b168 100644 --- a/service/network/api_test.go +++ b/service/network/api_test.go @@ -8,18 +8,20 @@ import ( "github.com/safing/portmaster/service/intel" ) -func TestDebugInfoLineFormatting(t *testing.T) { - t.Parallel() +func TestDebugInfoLineFormatting(t *testing.T) { //nolint:paralleltest // Shares connectionTestData, which is sorted by other tests. for _, conn := range connectionTestData { fmt.Println(conn.debugInfoLine()) } } -func TestDebugInfoFormatting(t *testing.T) { - t.Parallel() +func TestDebugInfoFormatting(t *testing.T) { //nolint:paralleltest // Sorts the shared connectionTestData. - fmt.Println(buildNetworkDebugInfoData(connectionTestData)) + // buildNetworkDebugInfoData sorts the slice in place; use a copy so the + // parallel line-formatting test does not race on the shared test data. + conns := make([]*Connection, len(connectionTestData)) + copy(conns, connectionTestData) + fmt.Println(buildNetworkDebugInfoData(conns)) } var connectionTestData = []*Connection{ diff --git a/service/network/clean.go b/service/network/clean.go index 331161a17..b08692c6d 100644 --- a/service/network/clean.go +++ b/service/network/clean.go @@ -84,7 +84,7 @@ func cleanConnections() (activePIDs map[int]struct{}) { var connActive bool switch conn.IPProtocol { //nolint:exhaustive case packet.TCP, packet.UDP: - connActive = state.Exists(&packet.Info{ + pktInfo := &packet.Info{ Inbound: false, // src == local Version: conn.IPVersion, Protocol: conn.IPProtocol, @@ -94,11 +94,16 @@ func cleanConnections() (activePIDs map[int]struct{}) { DstPort: conn.Entity.Port, PID: process.UndefinedProcessID, SeenAt: time.Unix(conn.Started, 0), // State tables will be updated if older than this. - }, now) + } + existsInState := state.Exists(pktInfo, now) // Update last seen value for permanent verdict connections. - if connActive && conn.VerdictPermanent { + if existsInState && conn.VerdictPermanent { conn.lastSeen.Store(nowUnix) } + connActive = ipConnActive( + conn.IPProtocol, existsInState, conn.VerdictPermanent, conn.lastSeen.Load(), now, + func() bool { return state.UDPSocketExists(pktInfo) }, + ) case packet.ICMP, packet.ICMPv6: connActive = conn.lastSeen.Load() > endICMPNotSeenSince @@ -110,6 +115,7 @@ func cleanConnections() (activePIDs map[int]struct{}) { // Step 2: mark as ended if !connActive { conn.Ended = nowUnix + conn.ended.Store(true) // Stop the firewall handler, in case one is running. conn.StopFirewallHandler() @@ -156,3 +162,33 @@ func cleanConnections() (activePIDs map[int]struct{}) { return activePIDs } + +// ipConnActive decides whether a TCP or UDP connection is still active. +// existsInState is the result of state.Exists() for the connection, lastSeen +// is the last seen timestamp of the connection (unix seconds) and +// udpSocketExists checks if the local UDP socket of the connection is still +// bound. +func ipConnActive( + protocol packet.IPProtocol, + existsInState, verdictPermanent bool, + lastSeen int64, + now time.Time, + udpSocketExists func() bool, +) bool { + if existsInState { + return true + } + + // The UDP state only knows when the connection was last looked up, which + // is only done for its first packet. Long-lived UDP flows are still active + // while their packets are handled, which updates lastSeen, and while + // their socket is still bound. + // The last seen timestamp of permanent verdict connections does not tell + // about their packets, as these are not handled anymore: The cleaner sets + // it while the connection exists in the state. + if protocol == packet.UDP && !verdictPermanent { + return lastSeen > now.Add(-state.UDPConnectionTTL).Unix() && udpSocketExists() + } + + return false +} diff --git a/service/network/clean_test.go b/service/network/clean_test.go new file mode 100644 index 000000000..f541e1231 --- /dev/null +++ b/service/network/clean_test.go @@ -0,0 +1,110 @@ +package network + +import ( + "testing" + "time" + + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/state" +) + +func TestIPConnActive(t *testing.T) { + t.Parallel() + + now := time.Now() + recently := now.Add(-time.Minute).Unix() + longAgo := now.Add(-state.UDPConnectionTTL - time.Minute).Unix() + + tests := []struct { + name string + protocol packet.IPProtocol + existsInState bool + verdictPermanent bool + lastSeen int64 + socketExists bool + want bool + }{ + {"TCP in state", packet.TCP, true, false, longAgo, true, true}, + {"TCP not in state", packet.TCP, false, false, recently, true, false}, + {"UDP in state", packet.UDP, true, false, longAgo, true, true}, + {"UDP not in state, inactive", packet.UDP, false, false, longAgo, true, false}, + // The UDP state only knows about the last lookup of the connection, + // which is only done for its first packet. Long-lived UDP flows that + // are still sending packets must not be ended. + {"UDP not in state, packets seen recently", packet.UDP, false, false, recently, true, true}, + // Packets for a closed socket do not keep the connection active. + {"UDP not in state, packets seen recently, socket closed", packet.UDP, false, false, recently, false, false}, + // The last seen timestamp of permanent verdict connections is set by + // the cleaner itself while the connection is in the state, as their + // packets are not seen. Using it would keep them active for another + // TTL after they left the state. + {"UDP not in state, permanent verdict", packet.UDP, false, true, recently, true, false}, + } + for _, tc := range tests { + got := ipConnActive(tc.protocol, tc.existsInState, tc.verdictPermanent, tc.lastSeen, now, func() bool { + return tc.socketExists + }) + if got != tc.want { + t.Errorf("%s: ipConnActive() = %v, want %v", tc.name, got, tc.want) + } + } +} + +// TestCleanerKeepsActiveUDPFlow simulates the cleaner runs of a long-lived +// UDP flow, whose packets are handled by Portmaster, but which is only looked +// up for its first packet. +func TestCleanerKeepsActiveUDPFlow(t *testing.T) { + t.Parallel() + + started := time.Now() + lastSeen := started.Unix() + for elapsed := time.Duration(0); elapsed <= time.Hour; elapsed += cleanerTickDuration { + now := started.Add(elapsed) + // The flow sends a packet every second. + lastSeen = now.Add(-time.Second).Unix() + // The UDP state only has the time of the lookup of the first packet. + existsInState := now.Sub(started) < state.UDPConnectionTTL + if !ipConnActive(packet.UDP, existsInState, false, lastSeen, now, func() bool { return true }) { + t.Fatalf("active UDP flow marked as ended after %s", elapsed) + } + } + + // The flow stops sending packets: it must end after the TTL. + stopped := started.Add(time.Hour) + var endedAfter time.Duration + for elapsed := time.Duration(0); elapsed <= 2*state.UDPConnectionTTL; elapsed += cleanerTickDuration { + if !ipConnActive(packet.UDP, false, false, lastSeen, stopped.Add(elapsed), func() bool { return true }) { + endedAfter = elapsed + break + } + } + if endedAfter == 0 || endedAfter > state.UDPConnectionTTL+cleanerTickDuration { + t.Fatalf("inactive UDP flow ended after %s, want about %s", endedAfter, state.UDPConnectionTTL) + } +} + +// TestCleanerEndsPermanentVerdictUDPFlow simulates the cleaner runs of a UDP +// flow with a permanent verdict, whose packets are not handled by Portmaster. +// The cleaner sets its last seen timestamp while it exists in the state, which +// must not keep it active after it left the state. +func TestCleanerEndsPermanentVerdictUDPFlow(t *testing.T) { + t.Parallel() + + started := time.Now() + lastSeen := started.Unix() + for elapsed := time.Duration(0); elapsed <= 2*state.UDPConnectionTTL; elapsed += cleanerTickDuration { + now := started.Add(elapsed) + existsInState := now.Sub(started) < state.UDPConnectionTTL + // Same as in cleanConnections(). + if existsInState { + lastSeen = now.Unix() + } + if !ipConnActive(packet.UDP, existsInState, true, lastSeen, now, func() bool { return true }) { + if elapsed != state.UDPConnectionTTL { + t.Fatalf("permanent verdict UDP flow ended after %s, want %s", elapsed, state.UDPConnectionTTL) + } + return + } + } + t.Fatal("permanent verdict UDP flow was never ended") +} diff --git a/service/network/connection.go b/service/network/connection.go index 8825dfb90..ba15cab6e 100644 --- a/service/network/connection.go +++ b/service/network/connection.go @@ -2,7 +2,6 @@ package network import ( "context" - "errors" "fmt" "net" "runtime" @@ -23,9 +22,6 @@ import ( "github.com/safing/portmaster/service/process" _ "github.com/safing/portmaster/service/process/tags" "github.com/safing/portmaster/service/resolver" - "github.com/safing/portmaster/spn/access" - "github.com/safing/portmaster/spn/access/account" - "github.com/safing/portmaster/spn/navigator" ) // FirewallHandler defines the function signature for a firewall @@ -77,7 +73,7 @@ const ( // Connection describes a distinct physical network connection // identified by the IP/Port pair. -type Connection struct { //nolint:maligned // TODO: fix alignment +type Connection struct { record.Base sync.Mutex @@ -132,7 +128,7 @@ type Connection struct { //nolint:maligned // TODO: fix alignment Resolver *resolver.ResolverInfo // Verdict holds the decisions that are made for a connection // The verdict may change so any access to it must be guarded by the - // connection lock. + // connection lock. Use VerdictState to access it without the lock. Verdict Verdict // Whether or not the connection has been established at least once. ConnectionEstablished bool @@ -160,12 +156,16 @@ type Connection struct { //nolint:maligned // TODO: fix alignment // using the connection lock. Inspecting bool // Tunneled is set to true when the connection has been routed through the - // SPN. + // SPN. portmasterpro never tunnels connections, so it always stays false; + // it is kept because it is part of the served and stored connection data. Tunneled bool // Encrypted is currently unused and MUST be ignored. Encrypted bool - // TunnelOpts holds options for tunneling the connection. - TunnelOpts *navigator.Options + // TunnelOpts holds options for tunneling the connection. portmaster-core + // never sets it; it is kept because it is part of the serialized + // connection, and the SPN packages (used by the hub binaries) store + // their *navigator.Options here. + TunnelOpts any // ProcessContext holds additional information about the process // that initiated the connection. It is set once when the connection // object is created and is considered immutable afterwards. @@ -196,10 +196,24 @@ type Connection struct { //nolint:maligned // TODO: fix alignment // BytesSent holds the observed sent bytes of the connection. BytesSent uint64 + // verdictState mirrors the Verdict, VerdictPermanent, Inbound and PID + // fields for packets that are handled without locking the connection. + // See VerdictState. + verdictState atomic.Uint64 + // lastSeen holds the timestamp when the connection was last seen. // If permanent verdicts are enabled and bandwidth reporting is not active, // this value will likely not be correct. lastSeen atomic.Int64 + // ended mirrors Ended != 0 for IP connections, so that the packet + // dispatcher can check it without taking the connection lock. + ended atomic.Bool + + // deferredBytesReceived and deferredBytesSent hold additive bandwidth + // updates that could not be applied yet, because the connection was + // locked. They are applied with the next bandwidth update. + deferredBytesReceived atomic.Uint64 + deferredBytesSent atomic.Uint64 // prompt holds the active prompt for this connection, if there is one. prompt *notifications.Notification @@ -318,17 +332,24 @@ func NewConnectionFromDNSRequest(ctx context.Context, fqdn string, cnames []stri switch { case !ok: // No dns request connection found. - case dnsRequestConn.PID < 0: - // Process is not identified or is special. - case dnsRequestConn.Ended > 0 && dnsRequestConn.Ended < time.Now().Unix()-3: - // Connection has already ended (too long ago). - log.Tracer(ctx).Debugf("network: found ended dns request connection %s for dns request for %s", dnsRequestConn, fqdn) default: - log.Tracer(ctx).Debugf("network: found matching dns request connection %s", dnsRequestConn.String()) - // Inherit PID. - pi.PID = dnsRequestConn.PID - // Inherit process struct itself, as the PID may already be re-used. - proc = dnsRequestConn.process + // The dns request connection is still handled by its packet handler + // worker and checked by the connection cleaner, so it may only be read + // while holding its lock. + reqPID, reqProc, reqEnded, reqDesc := dnsRequestConn.dnsRequestAttribution() + switch { + case reqPID < 0: + // Process is not identified or is special. + case reqEnded > 0 && reqEnded < time.Now().Unix()-3: + // Connection has already ended (too long ago). + log.Tracer(ctx).Debugf("network: found ended dns request connection %s for dns request for %s", reqDesc, fqdn) + default: + log.Tracer(ctx).Debugf("network: found matching dns request connection %s", reqDesc) + // Inherit PID. + pi.PID = reqPID + // Inherit process struct itself, as the PID may already be re-used. + proc = reqProc + } } // Find process by remote IP/Port. @@ -367,9 +388,7 @@ func NewConnectionFromDNSRequest(ctx context.Context, fqdn string, cnames []stri if localProfile := proc.Profile().LocalProfile(); localProfile != nil { dnsConn.Internal = localProfile.Internal - if err := dnsConn.UpdateFeatures(); err != nil && !errors.Is(err, access.ErrNotLoggedIn) { - log.Tracer(ctx).Warningf("network: failed to check for enabled features: %s", err) - } + dnsConn.UpdateFeatures() } // DNS Requests are saved by the nameserver depending on the result of the @@ -377,6 +396,7 @@ func NewConnectionFromDNSRequest(ctx context.Context, fqdn string, cnames []stri // saved if they are not "used" by a connection. dnsConn.UpdateMeta() + dnsConn.publishVerdictState() return dnsConn } @@ -411,9 +431,7 @@ func NewConnectionFromExternalDNSRequest(ctx context.Context, fqdn string, cname if localProfile := remoteHost.Profile().LocalProfile(); localProfile != nil { dnsConn.Internal = localProfile.Internal - if err := dnsConn.UpdateFeatures(); err != nil && !errors.Is(err, access.ErrNotLoggedIn) { - log.Tracer(ctx).Warningf("network: failed to check for enabled features: %s", err) - } + dnsConn.UpdateFeatures() } // DNS Requests are saved by the nameserver depending on the result of the @@ -421,6 +439,7 @@ func NewConnectionFromExternalDNSRequest(ctx context.Context, fqdn string, cname // saved if they are not "used" by a connection. dnsConn.UpdateMeta() + dnsConn.publishVerdictState() return dnsConn, nil } @@ -462,6 +481,7 @@ func NewIncompleteConnection(pkt packet.Packet) *Connection { // Save connection to internal state in order to mitigate creation of // duplicates. Do not propagate yet, as data is not yet complete. conn.UpdateMeta() + conn.publishVerdictState() conns.add(conn) return conn @@ -552,14 +572,15 @@ func (conn *Connection) GatherConnectionInfo(pkt packet.Packet) (err error) { if localProfile := conn.process.Profile().LocalProfile(); localProfile != nil { conn.Internal = localProfile.Internal - if err := conn.UpdateFeatures(); err != nil && !errors.Is(err, access.ErrNotLoggedIn) { - log.Tracer(pkt.Ctx()).Warningf("network: connection %s failed to check for enabled features: %s", conn, err) - } + conn.UpdateFeatures() } } // Find domain and DNS context of entity. - if localProfile := conn.process.Profile().LocalProfile(); conn.Entity.Domain == "" && localProfile != nil { + // An unspecified remote IP (0.0.0.0, ::) does not identify a destination, + // so any domain recorded for it would be unrelated to the connection. + if localProfile := conn.process.Profile().LocalProfile(); conn.Entity.Domain == "" && localProfile != nil && + !pkt.Info().RemoteIP().IsUnspecified() { profileScope := localProfile.ID // check if we can find a domain for that IP ipinfo, err := resolver.GetIPInfo(profileScope, pkt.Info().RemoteIP().String()) @@ -663,38 +684,28 @@ func (conn *Connection) SetLocalIP(ip net.IP) { conn.LocalIPScope = netutils.GetIPScope(ip) } -// UpdateFeatures checks which connection related features may and should be -// used and sets the flags accordingly. +// UpdateFeatures sets the connection related feature flags. +// +// portmasterpro has no account, subscription or SPN gating: network history +// and bandwidth visibility are local features and are always permitted. The +// only remaining decision is the per-application history setting. // The caller must hold a lock on the connection. -func (conn *Connection) UpdateFeatures() error { - // Get user. - user, err := access.GetUser() - if err != nil && !errors.Is(err, access.ErrNotLoggedIn) { - return err - } - // Caution: user may be nil! - - // Check if history may be used and if it is enabled for this application. +func (conn *Connection) UpdateFeatures() { + // Check if history is enabled for this application. conn.HistoryEnabled = false switch { case conn.Internal: // Do not record internal connections, as they are of low interest in the history. - // TODO: Should we create a setting for this? - case conn.Entity.IPScope.IsLocalhost(): + case conn.Entity != nil && conn.Entity.IPScope.IsLocalhost(): // Do not record localhost-only connections, as they are very low interest in the history. - // TODO: Should we create a setting for this? - case user.MayUse(account.FeatureHistory): - // Check if history may be used and is enabled. - lProfile := conn.Process().Profile() - if lProfile != nil { + default: + if lProfile := conn.Process().Profile(); lProfile != nil { conn.HistoryEnabled = lProfile.EnableHistory() } } - // Check if bandwidth visibility may be used. - conn.BandwidthEnabled = user.MayUse(account.FeatureBWVis) - - return nil + // Bandwidth visibility is always available locally. + conn.BandwidthEnabled = true } // AcceptWithContext accepts the connection. @@ -802,6 +813,37 @@ func (conn *Connection) DataIsComplete() bool { return conn.dataComplete.IsSet() } +// IsAttributedToProfile reports whether the data of the connection is +// complete and the connection is attributed to the given profile. +// It locks the connection. +func (conn *Connection) IsAttributedToProfile(profileSource, profileID string) bool { + // Check the atomic flag first in order to not wait for the lock of + // connections that cannot match. + if !conn.DataIsComplete() { + return false + } + + conn.Lock() + defer conn.Unlock() + + return conn.ProcessContext.Profile == profileID && + conn.ProcessContext.Source == profileSource +} + +// DeferBandwidthUpdate records an additive bandwidth update that cannot be +// applied right now, because the connection is locked. It does not require +// the connection lock. +func (conn *Connection) DeferBandwidthUpdate(bytesReceived, bytesSent uint64) { + conn.deferredBytesReceived.Add(bytesReceived) + conn.deferredBytesSent.Add(bytesSent) +} + +// TakeDeferredBandwidthUpdate returns and resets the bandwidth recorded with +// DeferBandwidthUpdate. +func (conn *Connection) TakeDeferredBandwidthUpdate() (bytesReceived, bytesSent uint64) { + return conn.deferredBytesReceived.Swap(0), conn.deferredBytesSent.Swap(0) +} + // Process returns the connection's process. func (conn *Connection) Process() *process.Process { return conn.process @@ -928,6 +970,16 @@ func (conn *Connection) String() string { } } +// dnsRequestAttribution returns the data of a saved dns request connection +// that is needed to attribute a dns request to its process. +// It locks the connection. +func (conn *Connection) dnsRequestAttribution() (pid int, proc *process.Process, ended int64, description string) { + conn.Lock() + defer conn.Unlock() + + return conn.PID, conn.process, conn.Ended, conn.String() +} + func (conn *Connection) shouldWaitForDomain() bool { // Should wait for Global Unicast, outgoing and not ICMP connections switch { diff --git a/service/network/connection_android.go b/service/network/connection_android.go deleted file mode 100644 index bbd498647..000000000 --- a/service/network/connection_android.go +++ /dev/null @@ -1,68 +0,0 @@ -package network - -import ( - "context" - "fmt" - "net" - "time" - - "github.com/safing/portmaster/service/intel" - "github.com/safing/portmaster/service/network/netutils" - "github.com/safing/portmaster/service/network/packet" - "github.com/safing/portmaster/service/process" - "github.com/safing/portmaster/spn/navigator" - "github.com/tevino/abool" -) - -// NewDefaultConnection creates a new connection with default values except local and remote IPs and protocols. -func NewDefaultConnection(localIP net.IP, localPort uint16, remoteIP net.IP, remotePort uint16, ipVersion packet.IPVersion, protocol packet.IPProtocol) *Connection { - connInfo := &Connection{ - ID: fmt.Sprintf("%s-%s-%d-%s-%d", protocol.String(), localIP, localPort, remoteIP, remotePort), - Type: IPConnection, - External: false, - IPVersion: ipVersion, - Inbound: false, - IPProtocol: protocol, - LocalIP: localIP, - LocalIPScope: netutils.Global, - LocalPort: localPort, - PID: process.UnidentifiedProcessID, - Entity: (&intel.Entity{ - IP: remoteIP, - Protocol: uint8(protocol), - Port: remotePort, - }).Init(0), - Resolver: nil, - Started: time.Now().Unix(), - VerdictPermanent: false, - Tunneled: true, - Encrypted: false, - DataComplete: abool.NewBool(true), - Internal: false, - addedToMetrics: true, // Metrics are not needed for now. This will mark the Connection to be ignored. - process: process.GetUnidentifiedProcess(context.Background()), - } - - // TODO: Quick fix for the SPN. - // Use inspection framework for proper encryption detection. - switch connInfo.Entity.DstPort() { - case - 22, // SSH - 443, // HTTPS - 465, // SMTP-SSL - 853, // DoT - 993, // IMAP-SSL - 995: // POP3-SSL - connInfo.Encrypted = true - } - - var layeredProfile = connInfo.process.Profile() - connInfo.TunnelOpts = &navigator.Options{ - HubPolicies: layeredProfile.StackedExitHubPolicies(), - CheckHubExitPolicyWith: connInfo.Entity, - RequireTrustedDestinationHubs: !connInfo.Encrypted, - RoutingProfile: layeredProfile.SPNRoutingAlgorithm(), - } - - return connInfo -} diff --git a/service/network/connection_handler.go b/service/network/connection_handler.go index d56b059d6..2a265e663 100644 --- a/service/network/connection_handler.go +++ b/service/network/connection_handler.go @@ -50,6 +50,10 @@ func (conn *Connection) UpdateFirewallHandler(handler FirewallHandler) { // StopFirewallHandler unsets the firewall handler and stops the handler worker. // The caller needs to hold a lock on the connection. func (conn *Connection) StopFirewallHandler() { + // Publish the verdict state before packets are handled without locking the + // connection, as the caller might hold the lock for some more time. + conn.publishVerdictState() + conn.pktQueueLock.Lock() defer conn.pktQueueLock.Unlock() @@ -87,9 +91,20 @@ func (conn *Connection) HandlePacket(pkt packet.Packet) { } } else { // Run default handler. - defaultFirewallHandler(conn, pkt) + // The connection is not locked here and must not be: This is the single + // packet dispatching goroutine, and connections may be locked for a + // long time, eg. while they are re-evaluated. + defaultLockFreeFirewallHandler(conn, pkt) // Record metrics. + recordPacketHandlingDuration(pkt) + } +} + +// recordPacketHandlingDuration records how long the packet took to be handled. +// The metric is not available before the module has registered its metrics. +func recordPacketHandlingDuration(pkt packet.Packet) { + if packetHandlingHistogram != nil { packetHandlingHistogram.UpdateDuration(pkt.Info().SeenAt) } } @@ -220,7 +235,7 @@ func packetHandlerHandleConn(ctx context.Context, conn *Connection, pkt packet.P defaultFirewallHandler(conn, pkt) // Record metrics. - packetHandlingHistogram.UpdateDuration(pkt.Info().SeenAt) + recordPacketHandlingDuration(pkt) return } @@ -238,7 +253,7 @@ func packetHandlerHandleConn(ctx context.Context, conn *Connection, pkt packet.P conn.firewallHandler(conn, pkt) // Record metrics. - packetHandlingHistogram.UpdateDuration(pkt.Info().SeenAt) + recordPacketHandlingDuration(pkt) // Log result and submit trace, when there are any changes. if conn.saveWhenFinished { diff --git a/service/network/connection_reuse.go b/service/network/connection_reuse.go new file mode 100644 index 000000000..a031f78ed --- /dev/null +++ b/service/network/connection_reuse.go @@ -0,0 +1,53 @@ +package network + +import ( + "time" +) + +// HasEnded reports whether the connection was marked as ended, without taking +// the connection lock. +func (conn *Connection) HasEnded() bool { + return conn.ended.Load() +} + +// RemoveEndedConnection removes an ended connection from the connection +// state before the cleaner does, because a new socket now uses its address +// tuple. The connection stays in the history. Returns false if the connection +// is locked by someone else or has not ended, in which case nothing is done. +// +// It is called from the packet dispatcher, which must not wait for a +// connection lock. +func RemoveEndedConnection(conn *Connection) bool { + if !conn.TryLock() { + return false + } + defer conn.Unlock() + + if conn.Ended == 0 { + return false + } + conn.delete() + return true +} + +// EndConnectionForReusedTuple ends and removes the connection with the given +// ID, if there is one. Use it when the OS has handed the address tuple of the +// connection to a new socket, which proves that the old socket is gone. The +// connection stays in the history. +func EndConnectionForReusedTuple(connID string) { + conn, ok := conns.get(connID) + if !ok { + return + } + + conn.Lock() + defer conn.Unlock() + + if conn.Ended == 0 { + conn.Ended = time.Now().Unix() + conn.ended.Store(true) + conn.StopFirewallHandler() + conn.Save() + } + conn.delete() +} diff --git a/service/network/connection_reuse_test.go b/service/network/connection_reuse_test.go new file mode 100644 index 000000000..5afdb2569 --- /dev/null +++ b/service/network/connection_reuse_test.go @@ -0,0 +1,83 @@ +package network + +import ( + "net" + "testing" + + "github.com/tevino/abool" + + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/network/packet" +) + +// newReuseTestConnection adds an incomplete UDP connection to the connection +// store. Incomplete connections are not written to the database. +func newReuseTestConnection(t *testing.T, localPort uint16) *Connection { + t.Helper() + + localIP, remoteIP := net.IPv4(10, 0, 2, 15), net.IPv4(10, 0, 2, 3) + conn := &Connection{ + ID: packet.CreateConnectionID(packet.UDP, localIP, localPort, remoteIP, 53, false), + Type: IPConnection, + IPProtocol: packet.UDP, + LocalIP: localIP, + LocalPort: localPort, + Entity: &intel.Entity{IP: remoteIP, Port: 53}, + Verdict: VerdictRerouteToNameserver, + Started: 1, + dataComplete: abool.New(), + } + conn.UpdateMeta() // As NewIncompleteConnection does. + conns.add(conn) + t.Cleanup(func() { conns.delete(conn) }) + return conn +} + +func TestRemoveEndedConnection(t *testing.T) { //nolint:paralleltest // Modifies the global connection store. + conn := newReuseTestConnection(t, 40001) + + // Active connections are kept. + if RemoveEndedConnection(conn) { + t.Fatal("removed a connection that has not ended") + } + if _, ok := GetConnection(conn.ID); !ok { + t.Fatal("active connection is gone") + } + + // A locked connection is kept, the dispatcher must not wait for it. + conn.Lock() + conn.Ended = 2 + conn.ended.Store(true) + removed := RemoveEndedConnection(conn) + conn.Unlock() + if removed { + t.Fatal("removed a locked connection") + } + + // An ended connection is removed. + if !conn.HasEnded() || !RemoveEndedConnection(conn) { + t.Fatal("ended connection was not removed") + } + if _, ok := GetConnection(conn.ID); ok { + t.Fatal("ended connection is still in the state") + } +} + +func TestEndConnectionForReusedTuple(t *testing.T) { //nolint:paralleltest // Modifies the global connection store. + conn := newReuseTestConnection(t, 40002) + + EndConnectionForReusedTuple(conn.ID) + + if _, ok := GetConnection(conn.ID); ok { + t.Fatal("connection is still in the state") + } + conn.Lock() + ended := conn.Ended + conn.Unlock() + if ended == 0 || !conn.HasEnded() { + t.Errorf("connection was not marked as ended (Ended=%d)", ended) + } + + // Unknown IDs are ignored. + EndConnectionForReusedTuple("17-10.0.2.15-1-10.0.2.3-53") +} diff --git a/service/network/connection_serialization_test.go b/service/network/connection_serialization_test.go new file mode 100644 index 000000000..4fa2930b9 --- /dev/null +++ b/service/network/connection_serialization_test.go @@ -0,0 +1,190 @@ +package network + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "flag" + "net" + "os" + "path/filepath" + "testing" + + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/network/netutils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/resolver" + "github.com/safing/structures/dsd" +) + +var updateGolden = flag.Bool("update-golden", false, "rewrite the serialization golden files") + +// serializationTestConnections returns connections that cover all values of +// the verdict state that is mirrored for the packet path. +func serializationTestConnections() map[string]*Connection { + outbound := &Connection{ + ID: "6-192.168.1.10-40000-1.1.1.1-443", + Type: IPConnection, + Scope: "example.com.", + IPVersion: packet.IPv4, + Inbound: false, + IPProtocol: packet.TCP, + LocalIP: net.IPv4(192, 168, 1, 10), + LocalIPScope: netutils.SiteLocal, + LocalPort: 40000, + PID: 4242, + Entity: &intel.Entity{ + Protocol: 6, + Port: 443, + Domain: "example.com.", + IP: net.IPv4(1, 1, 1, 1), + IPScope: netutils.Global, + }, + Resolver: &resolver.ResolverInfo{ + Name: "test", //nolint:goconst // Test data. + Type: resolver.ServerTypeDoT, + }, + Verdict: VerdictAccept, + ConnectionEstablished: true, + Reason: Reason{ + Msg: "allowed by rule", + OptionKey: "filter/endpoints", + Profile: "core:profiles/local/test", + }, + Started: 1700000000, + VerdictPermanent: true, + Encrypted: true, + ProcessContext: ProcessContext{ + ProcessName: "test", + ProfileName: "Test", + BinaryPath: "/usr/bin/test", + CmdLine: "/usr/bin/test --flag", + PID: 4242, + CreatedAt: 1699999999, + Profile: "test", + Source: "local", //nolint:goconst // Test data. + }, + HistoryEnabled: true, + BandwidthEnabled: true, + BytesReceived: 1234, + BytesSent: 5678, + ProfileRevisionCounter: 7, + } + + inbound := &Connection{ + ID: "17-192.168.1.10-53-192.168.1.20-50000", + Type: IPConnection, + Scope: IncomingLAN, + IPVersion: packet.IPv4, + Inbound: true, + IPProtocol: packet.UDP, + LocalIP: net.IPv4(192, 168, 1, 10), + LocalIPScope: netutils.SiteLocal, + LocalPort: 53, + PID: -1, + Entity: &intel.Entity{ + Protocol: 17, + Port: 50000, + IP: net.IPv4(192, 168, 1, 20), + IPScope: netutils.SiteLocal, + }, + Verdict: VerdictDrop, + Reason: Reason{ + Msg: "incoming connection blocked", + }, + Started: 1700000100, + Ended: 1700000200, + Internal: true, + } + + undecided := &Connection{ + ID: "1-192.168.1.10-0-8.8.8.8-0", + Type: IPConnection, + IPVersion: packet.IPv4, + IPProtocol: packet.ICMP, + PID: 0, + Verdict: VerdictUndecided, + Started: 1700000300, + } + + rerouted := &Connection{ + ID: "dns-request", + Type: DNSRequest, + Scope: "example.org.", + PID: 2147483000, + Verdict: VerdictRerouteToSplitTun, + Started: 1700000400, + Ended: 1700000400, + Tunneled: true, + Inspecting: true, + } + + return map[string]*Connection{ + "outbound": outbound, + "inbound": inbound, + "undecided": undecided, + "rerouted": rerouted, + } +} + +// TestConnectionSerializationGolden pins the serialized representation of +// connections, as it is seen by the API, the UI, netquery and database +// subscribers. The golden files were created before the verdict state was +// mirrored for the packet path and must not change with internal changes to +// the connection. +func TestConnectionSerializationGolden(t *testing.T) { + t.Parallel() + + formats := map[string]func(conn *Connection) ([]byte, error){ + "json": func(conn *Connection) ([]byte, error) { + return json.Marshal(conn) + }, + "dsd-json": func(conn *Connection) ([]byte, error) { + return dsd.Dump(conn, dsd.JSON) + }, + "dsd-cbor": func(conn *Connection) ([]byte, error) { + return dsd.Dump(conn, dsd.CBOR) + }, + "dsd-msgpack": func(conn *Connection) ([]byte, error) { + return dsd.Dump(conn, dsd.MsgPack) + }, + } + + for name, conn := range serializationTestConnections() { + for format, dump := range formats { + // Serialize while holding the lock and after a lock cycle, like + // all users of the connection do. + conn.Lock() + conn.Unlock() //nolint:staticcheck // Empty critical section is intended. + conn.Lock() + data, err := dump(conn) + conn.Unlock() + if err != nil { + t.Fatalf("%s/%s: failed to serialize: %s", name, format, err) + } + + goldenFile := filepath.Join("goldenfiles", "connection-"+name+"."+format+".golden") + encoded := []byte(hex.EncodeToString(data) + "\n") + if format == "json" { + // Keep one human readable representation. + encoded = []byte(string(data) + "\n") + } + + if *updateGolden { + err = os.WriteFile(goldenFile, encoded, 0o644) //nolint:gosec // Test data. + if err != nil { + t.Fatal(err) + } + continue + } + + golden, err := os.ReadFile(goldenFile) //nolint:gosec // Test data. + if err != nil { + t.Fatalf("%s/%s: failed to read golden file: %s", name, format, err) + } + if !bytes.Equal(golden, encoded) { + t.Errorf("%s/%s: serialization changed:\n got: %s\nwant: %s", name, format, encoded, golden) + } + } + } +} diff --git a/service/network/connection_unlocked_readers_test.go b/service/network/connection_unlocked_readers_test.go new file mode 100644 index 000000000..26a9d5249 --- /dev/null +++ b/service/network/connection_unlocked_readers_test.go @@ -0,0 +1,112 @@ +package network + +import ( + "sync" + "testing" + "time" + + "github.com/tevino/abool" +) + +// TestDNSRequestAttributionRace checks that the data of a saved dns request +// connection can be read while the connection is changed by its packet +// handler worker and the connection cleaner. Run with -race. +func TestDNSRequestAttributionRace(t *testing.T) { + t.Parallel() + + conn := &Connection{ID: "test-dns-request", PID: 1234, Started: time.Now().Unix()} + + var wg sync.WaitGroup + wg.Go(func() { + for i := range 1000 { + // Like fastTrackedPermit and the connection cleaner. + conn.Lock() + conn.PID = 1000 + i + conn.Ended = int64(i) + conn.Unlock() + } + }) + + for range 1000 { + pid, _, _, description := conn.dnsRequestAttribution() + if pid < 1000 || description != conn.ID { + t.Errorf("unexpected attribution: pid=%d description=%q", pid, description) + break + } + } + wg.Wait() +} + +// TestIsAttributedToProfileRace checks that the profile of a connection can +// be checked while the connection is re-attributed. Run with -race. +func TestIsAttributedToProfileRace(t *testing.T) { + t.Parallel() + + const ( + source = "local" + profile = "profile-a" + ) + + conn := &Connection{ + ID: "test-attribution", + dataComplete: abool.NewBool(true), + ProcessContext: ProcessContext{ + Source: source, + Profile: profile, + }, + } + + var wg sync.WaitGroup + wg.Go(func() { + for i := range 1000 { + // Like reAttributeConnection. + conn.Lock() + if i%2 == 0 { + conn.ProcessContext = ProcessContext{Source: source, Profile: "profile-with-a-longer-id-b"} + } else { + conn.ProcessContext = ProcessContext{Source: source, Profile: profile} + } + conn.Unlock() + } + }) + + for range 1000 { + if conn.IsAttributedToProfile(source, "other") { + t.Error("connection must not match another profile") + break + } + } + wg.Wait() + + if !conn.IsAttributedToProfile(source, profile) { + t.Error("connection must match its profile") + } + if conn.IsAttributedToProfile("special", profile) { + t.Error("connection must not match another profile source") + } + + incomplete := &Connection{ + dataComplete: abool.NewBool(false), + ProcessContext: ProcessContext{Source: source, Profile: profile}, + } + if incomplete.IsAttributedToProfile(source, profile) { + t.Error("incomplete connection must not match") + } +} + +func TestDeferredBandwidthUpdate(t *testing.T) { + t.Parallel() + + conn := &Connection{} + conn.DeferBandwidthUpdate(100, 50) + conn.DeferBandwidthUpdate(10, 5) + + received, sent := conn.TakeDeferredBandwidthUpdate() + if received != 110 || sent != 55 { + t.Errorf("got %d/%d, want 110/55", received, sent) + } + received, sent = conn.TakeDeferredBandwidthUpdate() + if received != 0 || sent != 0 { + t.Errorf("deferred update was not reset: %d/%d", received, sent) + } +} diff --git a/service/network/connection_verdict_state.go b/service/network/connection_verdict_state.go new file mode 100644 index 000000000..4842ca031 --- /dev/null +++ b/service/network/connection_verdict_state.go @@ -0,0 +1,127 @@ +package network + +// VerdictState is a consistent snapshot of the connection state that is +// needed to apply a verdict to a packet. +type VerdictState struct { + // Verdict is the verdict of the connection. + Verdict Verdict + // VerdictPermanent is set if the verdict is handed to the OS integration + // permanently. + VerdictPermanent bool + // Inbound is set if the connection is incoming. + Inbound bool + // PID is the PID of the owning process. + PID int +} + +// Layout of the packed verdict state: +// +// bits 0-7: Verdict +// bit 8: VerdictPermanent +// bit 9: Inbound +// bit 10: VerdictPermanent was set without the connection lock and is +// not yet applied to the VerdictPermanent field. +// bits 16-63: PID (signed) +const ( + verdictStateVerdictMask uint64 = 0xFF + verdictStatePermanent uint64 = 1 << 8 + verdictStateInbound uint64 = 1 << 9 + verdictStatePermanentPending uint64 = 1 << 10 + verdictStatePIDShift = 16 +) + +func packVerdictState(verdict Verdict, permanent, inbound bool, pid int) uint64 { + packed := uint64(uint8(verdict)) | uint64(int64(pid))<> verdictStatePIDShift), //nolint:gosec // Bit packing, sign extending. + } +} + +// Lock locks the connection. +func (conn *Connection) Lock() { + conn.Mutex.Lock() + conn.applyPendingVerdictState() +} + +// TryLock tries to lock the connection and reports whether it succeeded. +func (conn *Connection) TryLock() bool { + if !conn.Mutex.TryLock() { + return false + } + conn.applyPendingVerdictState() + return true +} + +// Unlock unlocks the connection and publishes the verdict state for packets +// that are handled without locking the connection, see VerdictState. +func (conn *Connection) Unlock() { + conn.publishVerdictState() + conn.Mutex.Unlock() +} + +// VerdictState returns a consistent snapshot of the Verdict, VerdictPermanent, +// Inbound and PID fields without requiring the connection lock. +// +// Packets of connections without a firewall handler are handled directly on +// the packet dispatching goroutine, which must never wait for the connection +// lock. They use this snapshot instead of the fields, which may only be +// accessed while holding the connection lock. +// +// The snapshot is published whenever the connection is unlocked, and when the +// firewall handler is stopped. It never exposes a state from within a +// critical section, except for the one at the time the handler is stopped. +func (conn *Connection) VerdictState() VerdictState { + return unpackVerdictState(conn.verdictState.Load()) +} + +// MakeVerdictPermanentLockFree marks the verdict of the connection as +// permanent without requiring the connection lock and returns the resulting +// verdict state. The VerdictPermanent field is updated the next time the +// connection is locked or unlocked. +func (conn *Connection) MakeVerdictPermanentLockFree() VerdictState { + for { + current := conn.verdictState.Load() + updated := current | verdictStatePermanent | verdictStatePermanentPending + if current == updated || conn.verdictState.CompareAndSwap(current, updated) { + return unpackVerdictState(updated) + } + } +} + +// applyPendingVerdictState applies changes to the verdict state that were +// made without the connection lock to the fields of the connection. +// The caller must hold the connection lock. +func (conn *Connection) applyPendingVerdictState() { + if conn.verdictState.Load()&verdictStatePermanentPending != 0 { + conn.VerdictPermanent = true + } +} + +// publishVerdictState publishes the current verdict state of the connection. +// The caller must hold the connection lock. +func (conn *Connection) publishVerdictState() { + for { + current := conn.verdictState.Load() + if current&verdictStatePermanentPending != 0 { + conn.VerdictPermanent = true + } + + updated := packVerdictState(conn.Verdict, conn.VerdictPermanent, conn.Inbound, conn.PID) + if current == updated || conn.verdictState.CompareAndSwap(current, updated) { + return + } + } +} diff --git a/service/network/connection_verdict_state_test.go b/service/network/connection_verdict_state_test.go new file mode 100644 index 000000000..949c93b21 --- /dev/null +++ b/service/network/connection_verdict_state_test.go @@ -0,0 +1,220 @@ +package network + +import ( + "math" + "sync" + "sync/atomic" + "testing" +) + +func TestVerdictStatePacking(t *testing.T) { + t.Parallel() + + verdicts := []Verdict{ + VerdictUndecided, VerdictUndeterminable, VerdictAccept, VerdictBlock, + VerdictDrop, VerdictRerouteToNameserver, VerdictRerouteToTunnel, + VerdictFailed, VerdictRerouteToSplitTun, Verdict(-1), Verdict(math.MaxInt8), Verdict(math.MinInt8), + } + pids := []int{ + 0, 1, 4, 4242, 4194304, // Linux PID_MAX_LIMIT + math.MaxInt32, math.MaxUint32, // Windows PIDs are 32 bit. + -1, -2, -3, -255, math.MinInt32, // Special PIDs are negative. + } + + for _, verdict := range verdicts { + for _, pid := range pids { + for _, permanent := range []bool{false, true} { + for _, inbound := range []bool{false, true} { + want := VerdictState{ + Verdict: verdict, + VerdictPermanent: permanent, + Inbound: inbound, + PID: pid, + } + packed := packVerdictState(verdict, permanent, inbound, pid) + if packed&verdictStatePermanentPending != 0 { + t.Errorf("%+v: pending flag must not be set by packing", want) + } + got := unpackVerdictState(packed) + if got != want { + t.Errorf("got %+v, want %+v", got, want) + } + // The pending flag does not influence any value. + got = unpackVerdictState(packed | verdictStatePermanentPending) + if got != want { + t.Errorf("with pending flag: got %+v, want %+v", got, want) + } + } + } + } + } +} + +func TestVerdictStatePublishing(t *testing.T) { + t.Parallel() + + conn := &Connection{ + Verdict: VerdictAccept, + Inbound: true, + PID: -1, + } + + // Nothing is published before the connection is unlocked the first time. + if state := conn.VerdictState(); state != (VerdictState{}) { + t.Errorf("unexpected initial state: %+v", state) + } + + // Changes are published when unlocking, not before. + conn.Lock() + conn.Verdict = VerdictBlock + if state := conn.VerdictState(); state != (VerdictState{}) { + t.Errorf("state published within critical section: %+v", state) + } + conn.Unlock() + want := VerdictState{Verdict: VerdictBlock, Inbound: true, PID: -1} + if state := conn.VerdictState(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + + // TryLock publishes too. + if !conn.TryLock() { + t.Fatal("failed to lock connection") + } + if conn.TryLock() { + t.Fatal("locked connection twice") + } + conn.PID = 1234 + conn.Inbound = false + conn.Unlock() + want = VerdictState{Verdict: VerdictBlock, PID: 1234} + if state := conn.VerdictState(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + + // Stopping the firewall handler publishes within the critical section. + conn.Lock() + conn.Verdict = VerdictDrop + conn.StopFirewallHandler() + want.Verdict = VerdictDrop + if state := conn.VerdictState(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + conn.Unlock() + + // A permanent verdict set without the lock is visible immediately and is + // adopted by the connection when it is locked. + want.VerdictPermanent = true + if state := conn.MakeVerdictPermanentLockFree(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + if state := conn.VerdictState(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + conn.Lock() + if !conn.VerdictPermanent { + t.Error("permanent verdict not adopted when locking") + } + conn.Unlock() + if conn.verdictState.Load()&verdictStatePermanentPending != 0 { + t.Error("pending flag not cleared when unlocking") + } + if state := conn.VerdictState(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + + // A permanent verdict that is set while the connection is locked is + // adopted when unlocking and does not revert other changes. + conn = &Connection{} + conn.Lock() + conn.Verdict = VerdictAccept + conn.MakeVerdictPermanentLockFree() + conn.Unlock() + want = VerdictState{Verdict: VerdictAccept, VerdictPermanent: true} + if state := conn.VerdictState(); state != want { + t.Errorf("got %+v, want %+v", state, want) + } + if !conn.VerdictPermanent { + t.Error("permanent verdict not adopted when unlocking") + } +} + +// TestVerdictStateConcurrency checks that the lock-free accessors do not race +// with users of the connection lock and that a permanent verdict is never lost. +func TestVerdictStateConcurrency(t *testing.T) { + t.Parallel() + + const rounds = 5000 + conn := &Connection{} + + var ( + wg sync.WaitGroup + permanent atomic.Bool + ) + + // Lock-free packet path. + wg.Go(func() { + for i := range rounds { + state := conn.VerdictState() + if permanent.Load() && !state.VerdictPermanent { + t.Error("permanent verdict was lost") + return + } + if state.PID != int(state.Verdict) { + t.Errorf("inconsistent snapshot: %+v", state) + return + } + if i == rounds/2 { + conn.MakeVerdictPermanentLockFree() + permanent.Store(true) + } + } + }) + + // Users of the connection lock. + for range 2 { + wg.Go(func() { + for i := range rounds { + conn.Lock() + // Keep Verdict and PID in sync to detect torn snapshots. + conn.Verdict = Verdict(i % 8) + conn.PID = i % 8 + conn.Inbound = i%2 == 0 + conn.Unlock() + } + }) + } + + wg.Wait() + + conn.Lock() + defer conn.Unlock() + if !conn.VerdictPermanent { + t.Error("connection did not adopt the permanent verdict") + } +} + +func BenchmarkConnectionLockUnlock(b *testing.B) { + conn := &Connection{Verdict: VerdictAccept, PID: 4242} + + b.Run("Mutex", func(b *testing.B) { + for b.Loop() { + conn.Mutex.Lock() + conn.Mutex.Unlock() //nolint:staticcheck // Empty critical section is intended. + } + }) + + b.Run("Connection", func(b *testing.B) { + for b.Loop() { + conn.Lock() + conn.Unlock() //nolint:staticcheck // Empty critical section is intended. + } + }) + + b.Run("VerdictState", func(b *testing.B) { + var state VerdictState + for b.Loop() { + state = conn.VerdictState() + } + _ = state + }) +} diff --git a/service/network/database.go b/service/network/database.go index 7464f36c2..7c98fa41a 100644 --- a/service/network/database.go +++ b/service/network/database.go @@ -134,8 +134,8 @@ func (s *StorageInterface) processQuery(q *query.Query, it *iterator.Iterator) { defer proc.Unlock() matches = q.Matches(proc) }() - if matches { - it.Next <- proc + if matches && !sendQueryResult(it, proc) { + return } } } @@ -153,8 +153,8 @@ func (s *StorageInterface) processQuery(q *query.Query, it *iterator.Iterator) { matches = q.Matches(dnsConn) }() - if matches { - it.Next <- dnsConn + if matches && !sendQueryResult(it, dnsConn) { + return } } } @@ -172,8 +172,8 @@ func (s *StorageInterface) processQuery(q *query.Query, it *iterator.Iterator) { matches = q.Matches(conn) }() - if matches { - it.Next <- conn + if matches && !sendQueryResult(it, conn) { + return } } } @@ -181,6 +181,20 @@ func (s *StorageInterface) processQuery(q *query.Query, it *iterator.Iterator) { it.Finish(nil) } +// sendQueryResult sends the record to the iterator. +// If the query was canceled by the consumer, the iterator is finished and +// false is returned. Without this, an abandoned query (eg. UI disconnected) +// would block the query worker forever, as nobody is reading the results. +func sendQueryResult(it *iterator.Iterator, r record.Record) (ok bool) { + select { + case it.Next <- r: + return true + case <-it.Done: + it.Finish(nil) + return false + } +} + func registerAsDatabase() error { _, err := database.Register(&database.Database{ Name: "network", diff --git a/service/network/database_test.go b/service/network/database_test.go new file mode 100644 index 000000000..db5203298 --- /dev/null +++ b/service/network/database_test.go @@ -0,0 +1,56 @@ +package network + +import ( + "strconv" + "testing" + "time" + + "github.com/tevino/abool" + + "github.com/safing/portmaster/base/database/iterator" + "github.com/safing/portmaster/base/database/query" +) + +// TestProcessQueryCancel checks that a query that is canceled by the consumer +// (eg. because the UI disconnected) does not block the query worker forever. +func TestProcessQueryCancel(t *testing.T) { //nolint:paralleltest // Modifies the global connection store. + // Not parallel: Modifies the global connection store. + + // Add more connections than fit into the iterator buffer. + added := make([]*Connection, 0, 100) + for i := range 100 { + conn := &Connection{ + ID: "query-cancel-test-" + strconv.Itoa(i), + dataComplete: abool.NewBool(true), + } + conn.SetKey(makeKey(1, dbScopeIP, conn.ID)) + conns.add(conn) + added = append(added, conn) + } + defer func() { + for _, conn := range added { + conns.delete(conn) + } + }() + + it := iterator.New() + finished := make(chan struct{}) + go func() { + defer close(finished) + (&StorageInterface{}).processQuery(query.New("network:tree/"), it) + }() + + // Read one record, then abandon the query. + select { + case <-it.Next: + case <-time.After(5 * time.Second): + t.Fatal("query did not return any records") + } + it.Cancel() + + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Fatal("query worker is still blocked after the query was canceled") + } +} diff --git a/service/network/dns.go b/service/network/dns.go index 2eb6ac10d..0b14e4b54 100644 --- a/service/network/dns.go +++ b/service/network/dns.go @@ -5,6 +5,7 @@ import ( "fmt" "strconv" "sync" + "sync/atomic" "time" "github.com/miekg/dns" @@ -19,7 +20,7 @@ import ( ) var ( - dnsRequestConnections = make(map[string]*Connection) // key: -- + dnsRequestConnections = make(map[string]*dnsRequestConnection) // key: -- dnsRequestConnectionsLock sync.RWMutex openDNSRequests = make(map[string]*Connection) // key: / @@ -41,8 +42,21 @@ const ( // openDNSRequestLimit defines the duration after which DNS requests without // a following connection are logged. openDNSRequestLimit = 3 * time.Second + + // dnsRequestConnectionIdleTTL defines the duration after which a saved DNS + // request connection that has not ended is removed if it was neither saved + // nor looked up in the meantime. + dnsRequestConnectionIdleTTL = 10 * time.Minute ) +// dnsRequestConnection is an entry of dnsRequestConnections. +type dnsRequestConnection struct { + conn *Connection + // lastUsed holds the unix timestamp of when the entry was last saved or + // looked up. + lastUsed atomic.Int64 +} + func getDNSRequestConnectionKey(packetInfo *packet.Info) (id string, ok bool) { // We only support protocols with ports. if packetInfo.SrcPort == 0 { @@ -70,9 +84,12 @@ func SaveDNSRequestConnection(conn *Connection, pkt packet.Packet) { // Add or update DNS request connection. log.Tracer(pkt.Ctx()).Tracef("network: saving %s with PID %d as dns request connection for fast DNS request attribution", pkt, conn.PID) + entry := &dnsRequestConnection{conn: conn} + entry.lastUsed.Store(time.Now().Unix()) + dnsRequestConnectionsLock.Lock() defer dnsRequestConnectionsLock.Unlock() - dnsRequestConnections[key] = conn + dnsRequestConnections[key] = entry } // GetDNSRequestConnection returns a saved dns request connection. @@ -87,12 +104,16 @@ func GetDNSRequestConnection(packetInfo *packet.Info) (conn *Connection, ok bool dnsRequestConnectionsLock.RLock() defer dnsRequestConnectionsLock.RUnlock() - conn, ok = dnsRequestConnections[key] - return conn, ok + entry, ok := dnsRequestConnections[key] + if !ok { + return nil, false + } + entry.lastUsed.Store(time.Now().Unix()) + return entry.conn, true } // deleteDNSRequestConnection removes a connection from the dns request connections. -func deleteDNSRequestConnection(packetInfo *packet.Info) { //nolint:unused,deadcode +func deleteDNSRequestConnection(packetInfo *packet.Info) { //nolint:unused dnsRequestConnectionsLock.Lock() defer dnsRequestConnectionsLock.Unlock() @@ -104,15 +125,27 @@ func deleteDNSRequestConnection(packetInfo *packet.Info) { //nolint:unused,deadc // cleanDNSRequestConnections deletes old DNS request connections. func cleanDNSRequestConnections() { - deleteOlderThan := time.Now().Unix() - 3 + cleanDNSRequestConnectionsAt(time.Now()) +} + +func cleanDNSRequestConnectionsAt(now time.Time) { + deleteOlderThan := now.Unix() - 3 + deleteUnusedSince := now.Add(-dnsRequestConnectionIdleTTL).Unix() dnsRequestConnectionsLock.Lock() defer dnsRequestConnectionsLock.Unlock() - for key, conn := range dnsRequestConnections { + for key, entry := range dnsRequestConnections { + conn := entry.conn conn.Lock() - if conn.Ended > 0 && conn.Ended < deleteOlderThan { + switch { + case conn.Ended > 0 && conn.Ended < deleteOlderThan: + delete(dnsRequestConnections, key) + case conn.Ended == 0 && entry.lastUsed.Load() < deleteUnusedSince: + // Connections that are removed from the connection state while + // incomplete (eg. fast-tracked DNS requests) are never marked as + // ended, so they need to expire when not used anymore. delete(dnsRequestConnections, key) } diff --git a/service/network/dns_test.go b/service/network/dns_test.go new file mode 100644 index 000000000..59e320f3c --- /dev/null +++ b/service/network/dns_test.go @@ -0,0 +1,118 @@ +package network + +import ( + "context" + "net" + "testing" + "time" + + "github.com/safing/portmaster/service/network/packet" +) + +func newTestDNSRequestPacket(srcPort uint16) packet.Packet { + pkt := packet.NewInfoPacket(packet.Info{ + Inbound: false, + Version: packet.IPv4, + Protocol: packet.UDP, + Src: net.IPv4(127, 0, 0, 1), + SrcPort: srcPort, + Dst: net.IPv4(127, 0, 0, 53), + DstPort: 53, + PID: 1234, + }) + pkt.SetCtx(context.Background()) + return pkt +} + +func resetDNSRequestConnections(t *testing.T) { + t.Helper() + + dnsRequestConnectionsLock.Lock() + dnsRequestConnections = make(map[string]*dnsRequestConnection) + dnsRequestConnectionsLock.Unlock() +} + +func dnsRequestConnectionsLen() int { + dnsRequestConnectionsLock.RLock() + defer dnsRequestConnectionsLock.RUnlock() + + return len(dnsRequestConnections) +} + +// TestDNSRequestConnectionNeverEndedExpires covers DNS request connections +// that are saved by the DNS fast-track and then dropped from the connection +// state while still incomplete: their Ended field is never set. +func TestDNSRequestConnectionNeverEndedExpires(t *testing.T) { //nolint:paralleltest // Uses global state. + resetDNSRequestConnections(t) + t.Cleanup(func() { resetDNSRequestConnections(t) }) + + now := time.Now() + const entries = 1000 + for i := range entries { + conn := &Connection{PID: 1234, Started: now.Unix()} + SaveDNSRequestConnection(conn, newTestDNSRequestPacket(uint16(10000+i))) + } + if l := dnsRequestConnectionsLen(); l != entries { + t.Fatalf("expected %d saved entries, got %d", entries, l) + } + + // Fresh entries must be kept. + cleanDNSRequestConnectionsAt(now) + if l := dnsRequestConnectionsLen(); l != entries { + t.Fatalf("fresh entries were removed: expected %d entries, got %d", entries, l) + } + + // Unused entries of connections that never ended must expire. + cleanDNSRequestConnectionsAt(now.Add(dnsRequestConnectionIdleTTL + time.Minute)) + if l := dnsRequestConnectionsLen(); l != 0 { + t.Fatalf("expected all unused never-ended entries to expire, %d entries left", l) + } +} + +func TestDNSRequestConnectionKeptWhileUsed(t *testing.T) { //nolint:paralleltest // Uses global state. + resetDNSRequestConnections(t) + t.Cleanup(func() { resetDNSRequestConnections(t) }) + + pkt := newTestDNSRequestPacket(20000) + conn := &Connection{PID: 1234, Started: time.Now().Add(-time.Hour).Unix()} + SaveDNSRequestConnection(conn, pkt) + + // Simulate that the entry was saved a long time ago. + dnsRequestConnectionsLock.RLock() + for _, entry := range dnsRequestConnections { + entry.lastUsed.Store(time.Now().Add(-time.Hour).Unix()) + } + dnsRequestConnectionsLock.RUnlock() + + // A lookup marks the entry as used. + found, ok := GetDNSRequestConnection(pkt.Info()) + if !ok || found != conn { + t.Fatal("expected to find saved dns request connection") + } + + cleanDNSRequestConnectionsAt(time.Now()) + if _, ok := GetDNSRequestConnection(pkt.Info()); !ok { + t.Fatal("recently used dns request connection was removed") + } +} + +func TestDNSRequestConnectionEndedExpires(t *testing.T) { //nolint:paralleltest // Uses global state. + resetDNSRequestConnections(t) + t.Cleanup(func() { resetDNSRequestConnections(t) }) + + now := time.Now() + + ended := &Connection{PID: 1234, Started: now.Unix() - 10, Ended: now.Unix() - 5} + SaveDNSRequestConnection(ended, newTestDNSRequestPacket(30000)) + justEnded := &Connection{PID: 1234, Started: now.Unix() - 10, Ended: now.Unix()} + justEndedPkt := newTestDNSRequestPacket(30001) + SaveDNSRequestConnection(justEnded, justEndedPkt) + + cleanDNSRequestConnectionsAt(now) + if l := dnsRequestConnectionsLen(); l != 1 { + t.Fatalf("expected 1 entry left, got %d", l) + } + if found, ok := GetDNSRequestConnection(justEndedPkt.Info()); !ok || found != justEnded { + t.Fatal("just ended dns request connection was removed") + } +} diff --git a/service/network/features_test.go b/service/network/features_test.go new file mode 100644 index 000000000..c6e3ea749 --- /dev/null +++ b/service/network/features_test.go @@ -0,0 +1,57 @@ +package network + +import ( + "testing" + + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/network/netutils" +) + +// TestUpdateFeaturesWithoutAccount guards the portmasterpro contract: network +// history and bandwidth visibility never depend on an account, a login or the +// SPN. UpdateFeatures must also be safe on connections without a process. +func TestUpdateFeaturesWithoutAccount(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + conn *Connection + wantHistory bool + }{ + { + name: "internal connection is not recorded", + conn: &Connection{Internal: true, Entity: &intel.Entity{IPScope: netutils.Global}}, + wantHistory: false, + }, + { + name: "localhost connection is not recorded", + conn: &Connection{Entity: &intel.Entity{IPScope: netutils.HostLocal}}, + wantHistory: false, + }, + { + name: "global connection without process falls back to disabled history", + conn: &Connection{Entity: &intel.Entity{IPScope: netutils.Global}}, + wantHistory: false, + }, + { + name: "missing entity does not panic", + conn: &Connection{}, + wantHistory: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + tc.conn.UpdateFeatures() + + if tc.conn.HistoryEnabled != tc.wantHistory { + t.Errorf("HistoryEnabled = %v, want %v", tc.conn.HistoryEnabled, tc.wantHistory) + } + if !tc.conn.BandwidthEnabled { + t.Error("BandwidthEnabled must always be true: bandwidth visibility is a local feature") + } + }) + } +} diff --git a/service/network/goldenfiles/connection-inbound.dsd-cbor.golden b/service/network/goldenfiles/connection-inbound.dsd-cbor.golden new file mode 100644 index 000000000..71697a432 --- /dev/null +++ b/service/network/goldenfiles/connection-inbound.dsd-cbor.golden @@ -0,0 +1 @@ +43b821624944782531372d3139322e3136382e312e31302d35332d3139322e3136382e312e32302d35303030306454797065016845787465726e616cf46553636f706562494c69495056657273696f6e0467496e626f756e64f56a495050726f746f636f6c11674c6f63616c49505000000000000000000000ffffc0a8010a6c4c6f63616c495053636f706503694c6f63616c506f72741835635049442066456e74697479b06249505000000000000000000000ffffc0a8011467495053636f7065036850726f746f636f6c1164506f727419c35066446f6d61696e606d52657665727365446f6d61696e6065434e414d45f667436f756e747279606b436f6f7264696e61746573f66341534e006541534f7267606d4c6f636174696f6e4572726f72606e426c6f636b656442794c69737473f66f426c6f636b6564456e746974696573f66e4c6973744f63637572656e636573f66a4c697374734572726f7260685265736f6c766572f667566572646963740475436f6e6e656374696f6e45737461626c6973686564f466526561736f6ea4634d7367781b696e636f6d696e6720636f6e6e656374696f6e20626c6f636b6564694f7074696f6e4b6579606750726f66696c656067436f6e74657874f667537461727465641a6553f16465456e6465641a6553f1c870566572646963745065726d616e656e74f46a496e7370656374696e67f46854756e6e656c6564f469456e63727970746564f46a54756e6e656c4f707473f66e50726f63657373436f6e74657874a86b50726f636573734e616d65606b50726f66696c654e616d65606a42696e617279506174686067436d644c696e6560635049440069437265617465644174006750726f66696c656066536f75726365606a444e53436f6e74657874f66d54756e6e656c436f6e74657874f66f53706c697454756e436f6e74657874f66e486973746f7279456e61626c6564f47042616e647769647468456e61626c6564f46d427974657352656365697665640069427974657353656e740068496e7465726e616cf57650726f66696c655265766973696f6e436f756e74657200 diff --git a/service/network/goldenfiles/connection-inbound.dsd-json.golden b/service/network/goldenfiles/connection-inbound.dsd-json.golden new file mode 100644 index 000000000..4ee900028 --- /dev/null +++ b/service/network/goldenfiles/connection-inbound.dsd-json.golden @@ -0,0 +1 @@ +4a7b224944223a2231372d3139322e3136382e312e31302d35332d3139322e3136382e312e32302d3530303030222c2254797065223a312c2245787465726e616c223a66616c73652c2253636f7065223a22494c222c22495056657273696f6e223a342c22496e626f756e64223a747275652c22495050726f746f636f6c223a31372c224c6f63616c4950223a223139322e3136382e312e3130222c224c6f63616c495053636f7065223a332c224c6f63616c506f7274223a35332c22504944223a2d312c22456e74697479223a7b224950223a223139322e3136382e312e3230222c22495053636f7065223a332c2250726f746f636f6c223a31372c22506f7274223a35303030302c22446f6d61696e223a22222c2252657665727365446f6d61696e223a22222c22434e414d45223a6e756c6c2c22436f756e747279223a22222c22436f6f7264696e61746573223a6e756c6c2c2241534e223a302c2241534f7267223a22222c224c6f636174696f6e4572726f72223a22222c22426c6f636b656442794c69737473223a6e756c6c2c22426c6f636b6564456e746974696573223a6e756c6c2c224c6973744f63637572656e636573223a6e756c6c2c224c697374734572726f72223a22227d2c225265736f6c766572223a6e756c6c2c2256657264696374223a342c22436f6e6e656374696f6e45737461626c6973686564223a66616c73652c22526561736f6e223a7b224d7367223a22696e636f6d696e6720636f6e6e656374696f6e20626c6f636b6564222c224f7074696f6e4b6579223a22222c2250726f66696c65223a22222c22436f6e74657874223a6e756c6c7d2c2253746172746564223a313730303030303130302c22456e646564223a313730303030303230302c22566572646963745065726d616e656e74223a66616c73652c22496e7370656374696e67223a66616c73652c2254756e6e656c6564223a66616c73652c22456e63727970746564223a66616c73652c2254756e6e656c4f707473223a6e756c6c2c2250726f63657373436f6e74657874223a7b2250726f636573734e616d65223a22222c2250726f66696c654e616d65223a22222c2242696e61727950617468223a22222c22436d644c696e65223a22222c22504944223a302c22437265617465644174223a302c2250726f66696c65223a22222c22536f75726365223a22227d2c22444e53436f6e74657874223a6e756c6c2c2254756e6e656c436f6e74657874223a6e756c6c2c2253706c697454756e436f6e74657874223a6e756c6c2c22486973746f7279456e61626c6564223a66616c73652c2242616e647769647468456e61626c6564223a66616c73652c2242797465735265636569766564223a302c22427974657353656e74223a302c22496e7465726e616c223a747275652c2250726f66696c655265766973696f6e436f756e746572223a307d diff --git a/service/network/goldenfiles/connection-inbound.dsd-msgpack.golden b/service/network/goldenfiles/connection-inbound.dsd-msgpack.golden new file mode 100644 index 000000000..c06115e01 --- /dev/null +++ b/service/network/goldenfiles/connection-inbound.dsd-msgpack.golden @@ -0,0 +1 @@ +4dde0021a24944d92531372d3139322e3136382e312e31302d35332d3139322e3136382e312e32302d3530303030a454797065d001a845787465726e616cc2a553636f7065a2494ca9495056657273696f6ecc04a7496e626f756e64c3aa495050726f746f636f6ccc11a74c6f63616c4950c40c3139322e3136382e312e3130ac4c6f63616c495053636f7065d003a94c6f63616c506f7274cd0035a3504944ffa6456e74697479de0010a24950c40c3139322e3136382e312e3230a7495053636f7065d003a850726f746f636f6ccc11a4506f7274cdc350a6446f6d61696ea0ad52657665727365446f6d61696ea0a5434e414d45c0a7436f756e747279a0ab436f6f7264696e61746573c0a341534e00a541534f7267a0ad4c6f636174696f6e4572726f72a0ae426c6f636b656442794c69737473c0af426c6f636b6564456e746974696573c0ae4c6973744f63637572656e636573c0aa4c697374734572726f72a0a85265736f6c766572c0a756657264696374d004b5436f6e6e656374696f6e45737461626c6973686564c2a6526561736f6e84a34d7367bb696e636f6d696e6720636f6e6e656374696f6e20626c6f636b6564a94f7074696f6e4b6579a0a750726f66696c65a0a7436f6e74657874c0a753746172746564d3000000006553f164a5456e646564d3000000006553f1c8b0566572646963745065726d616e656e74c2aa496e7370656374696e67c2a854756e6e656c6564c2a9456e63727970746564c2aa54756e6e656c4f707473c0ae50726f63657373436f6e7465787488ab50726f636573734e616d65a0ab50726f66696c654e616d65a0aa42696e61727950617468a0a7436d644c696e65a0a350494400a9437265617465644174d30000000000000000a750726f66696c65a0a6536f75726365a0aa444e53436f6e74657874c0ad54756e6e656c436f6e74657874c0af53706c697454756e436f6e74657874c0ae486973746f7279456e61626c6564c2b042616e647769647468456e61626c6564c2ad42797465735265636569766564cf0000000000000000a9427974657353656e74cf0000000000000000a8496e7465726e616cc3b650726f66696c655265766973696f6e436f756e746572cf0000000000000000 diff --git a/service/network/goldenfiles/connection-inbound.json.golden b/service/network/goldenfiles/connection-inbound.json.golden new file mode 100644 index 000000000..5992f8824 --- /dev/null +++ b/service/network/goldenfiles/connection-inbound.json.golden @@ -0,0 +1 @@ +{"ID":"17-192.168.1.10-53-192.168.1.20-50000","Type":1,"External":false,"Scope":"IL","IPVersion":4,"Inbound":true,"IPProtocol":17,"LocalIP":"192.168.1.10","LocalIPScope":3,"LocalPort":53,"PID":-1,"Entity":{"IP":"192.168.1.20","IPScope":3,"Protocol":17,"Port":50000,"Domain":"","ReverseDomain":"","CNAME":null,"Country":"","Coordinates":null,"ASN":0,"ASOrg":"","LocationError":"","BlockedByLists":null,"BlockedEntities":null,"ListOccurences":null,"ListsError":""},"Resolver":null,"Verdict":4,"ConnectionEstablished":false,"Reason":{"Msg":"incoming connection blocked","OptionKey":"","Profile":"","Context":null},"Started":1700000100,"Ended":1700000200,"VerdictPermanent":false,"Inspecting":false,"Tunneled":false,"Encrypted":false,"TunnelOpts":null,"ProcessContext":{"ProcessName":"","ProfileName":"","BinaryPath":"","CmdLine":"","PID":0,"CreatedAt":0,"Profile":"","Source":""},"DNSContext":null,"TunnelContext":null,"SplitTunContext":null,"HistoryEnabled":false,"BandwidthEnabled":false,"BytesReceived":0,"BytesSent":0,"Internal":true,"ProfileRevisionCounter":0} diff --git a/service/network/goldenfiles/connection-outbound.dsd-cbor.golden b/service/network/goldenfiles/connection-outbound.dsd-cbor.golden new file mode 100644 index 000000000..2b08ac137 --- /dev/null +++ b/service/network/goldenfiles/connection-outbound.dsd-cbor.golden @@ -0,0 +1 @@ +43b8216249447820362d3139322e3136382e312e31302d34303030302d312e312e312e312d3434336454797065016845787465726e616cf46553636f70656c6578616d706c652e636f6d2e69495056657273696f6e0467496e626f756e64f46a495050726f746f636f6c06674c6f63616c49505000000000000000000000ffffc0a8010a6c4c6f63616c495053636f706503694c6f63616c506f7274199c406350494419109266456e74697479b06249505000000000000000000000ffff0101010167495053636f7065046850726f746f636f6c0664506f72741901bb66446f6d61696e6c6578616d706c652e636f6d2e6d52657665727365446f6d61696e6065434e414d45f667436f756e747279606b436f6f7264696e61746573f66341534e006541534f7267606d4c6f636174696f6e4572726f72606e426c6f636b656442794c69737473f66f426c6f636b6564456e746974696573f66e4c6973744f63637572656e636573f66a4c697374734572726f7260685265736f6c766572a7644e616d656474657374645479706563646f7466536f7572636560624950f666446f6d61696e6067495053636f70650064506f72740067566572646963740275436f6e6e656374696f6e45737461626c6973686564f566526561736f6ea4634d73676f616c6c6f7765642062792072756c65694f7074696f6e4b65797066696c7465722f656e64706f696e74736750726f66696c657818636f72653a70726f66696c65732f6c6f63616c2f7465737467436f6e74657874f667537461727465641a6553f10065456e6465640070566572646963745065726d616e656e74f56a496e7370656374696e67f46854756e6e656c6564f469456e63727970746564f56a54756e6e656c4f707473f66e50726f63657373436f6e74657874a86b50726f636573734e616d6564746573746b50726f66696c654e616d6564546573746a42696e617279506174686d2f7573722f62696e2f7465737467436d644c696e65742f7573722f62696e2f74657374202d2d666c616763504944191092694372656174656441741a6553f0ff6750726f66696c65647465737466536f75726365656c6f63616c6a444e53436f6e74657874f66d54756e6e656c436f6e74657874f66f53706c697454756e436f6e74657874f66e486973746f7279456e61626c6564f57042616e647769647468456e61626c6564f56d427974657352656365697665641904d269427974657353656e7419162e68496e7465726e616cf47650726f66696c655265766973696f6e436f756e74657207 diff --git a/service/network/goldenfiles/connection-outbound.dsd-json.golden b/service/network/goldenfiles/connection-outbound.dsd-json.golden new file mode 100644 index 000000000..7b6aecd05 --- /dev/null +++ b/service/network/goldenfiles/connection-outbound.dsd-json.golden @@ -0,0 +1 @@ +4a7b224944223a22362d3139322e3136382e312e31302d34303030302d312e312e312e312d343433222c2254797065223a312c2245787465726e616c223a66616c73652c2253636f7065223a226578616d706c652e636f6d2e222c22495056657273696f6e223a342c22496e626f756e64223a66616c73652c22495050726f746f636f6c223a362c224c6f63616c4950223a223139322e3136382e312e3130222c224c6f63616c495053636f7065223a332c224c6f63616c506f7274223a34303030302c22504944223a343234322c22456e74697479223a7b224950223a22312e312e312e31222c22495053636f7065223a342c2250726f746f636f6c223a362c22506f7274223a3434332c22446f6d61696e223a226578616d706c652e636f6d2e222c2252657665727365446f6d61696e223a22222c22434e414d45223a6e756c6c2c22436f756e747279223a22222c22436f6f7264696e61746573223a6e756c6c2c2241534e223a302c2241534f7267223a22222c224c6f636174696f6e4572726f72223a22222c22426c6f636b656442794c69737473223a6e756c6c2c22426c6f636b6564456e746974696573223a6e756c6c2c224c6973744f63637572656e636573223a6e756c6c2c224c697374734572726f72223a22227d2c225265736f6c766572223a7b224e616d65223a2274657374222c2254797065223a22646f74222c22536f75726365223a22222c224950223a22222c22446f6d61696e223a22222c22495053636f7065223a302c22506f7274223a307d2c2256657264696374223a322c22436f6e6e656374696f6e45737461626c6973686564223a747275652c22526561736f6e223a7b224d7367223a22616c6c6f7765642062792072756c65222c224f7074696f6e4b6579223a2266696c7465722f656e64706f696e7473222c2250726f66696c65223a22636f72653a70726f66696c65732f6c6f63616c2f74657374222c22436f6e74657874223a6e756c6c7d2c2253746172746564223a313730303030303030302c22456e646564223a302c22566572646963745065726d616e656e74223a747275652c22496e7370656374696e67223a66616c73652c2254756e6e656c6564223a66616c73652c22456e63727970746564223a747275652c2254756e6e656c4f707473223a6e756c6c2c2250726f63657373436f6e74657874223a7b2250726f636573734e616d65223a2274657374222c2250726f66696c654e616d65223a2254657374222c2242696e61727950617468223a222f7573722f62696e2f74657374222c22436d644c696e65223a222f7573722f62696e2f74657374202d2d666c6167222c22504944223a343234322c22437265617465644174223a313639393939393939392c2250726f66696c65223a2274657374222c22536f75726365223a226c6f63616c227d2c22444e53436f6e74657874223a6e756c6c2c2254756e6e656c436f6e74657874223a6e756c6c2c2253706c697454756e436f6e74657874223a6e756c6c2c22486973746f7279456e61626c6564223a747275652c2242616e647769647468456e61626c6564223a747275652c2242797465735265636569766564223a313233342c22427974657353656e74223a353637382c22496e7465726e616c223a66616c73652c2250726f66696c655265766973696f6e436f756e746572223a377d diff --git a/service/network/goldenfiles/connection-outbound.dsd-msgpack.golden b/service/network/goldenfiles/connection-outbound.dsd-msgpack.golden new file mode 100644 index 000000000..7474f45b2 --- /dev/null +++ b/service/network/goldenfiles/connection-outbound.dsd-msgpack.golden @@ -0,0 +1 @@ +4dde0021a24944d920362d3139322e3136382e312e31302d34303030302d312e312e312e312d343433a454797065d001a845787465726e616cc2a553636f7065ac6578616d706c652e636f6d2ea9495056657273696f6ecc04a7496e626f756e64c2aa495050726f746f636f6ccc06a74c6f63616c4950c40c3139322e3136382e312e3130ac4c6f63616c495053636f7065d003a94c6f63616c506f7274cd9c40a3504944cd1092a6456e74697479de0010a24950c407312e312e312e31a7495053636f7065d004a850726f746f636f6ccc06a4506f7274cd01bba6446f6d61696eac6578616d706c652e636f6d2ead52657665727365446f6d61696ea0a5434e414d45c0a7436f756e747279a0ab436f6f7264696e61746573c0a341534e00a541534f7267a0ad4c6f636174696f6e4572726f72a0ae426c6f636b656442794c69737473c0af426c6f636b6564456e746974696573c0ae4c6973744f63637572656e636573c0aa4c697374734572726f72a0a85265736f6c76657287a44e616d65a474657374a454797065a3646f74a6536f75726365a0a24950c0a6446f6d61696ea0a7495053636f7065d000a4506f7274cd0000a756657264696374d002b5436f6e6e656374696f6e45737461626c6973686564c3a6526561736f6e84a34d7367af616c6c6f7765642062792072756c65a94f7074696f6e4b6579b066696c7465722f656e64706f696e7473a750726f66696c65b8636f72653a70726f66696c65732f6c6f63616c2f74657374a7436f6e74657874c0a753746172746564d3000000006553f100a5456e646564d30000000000000000b0566572646963745065726d616e656e74c3aa496e7370656374696e67c2a854756e6e656c6564c2a9456e63727970746564c3aa54756e6e656c4f707473c0ae50726f63657373436f6e7465787488ab50726f636573734e616d65a474657374ab50726f66696c654e616d65a454657374aa42696e61727950617468ad2f7573722f62696e2f74657374a7436d644c696e65b42f7573722f62696e2f74657374202d2d666c6167a3504944cd1092a9437265617465644174d3000000006553f0ffa750726f66696c65a474657374a6536f75726365a56c6f63616caa444e53436f6e74657874c0ad54756e6e656c436f6e74657874c0af53706c697454756e436f6e74657874c0ae486973746f7279456e61626c6564c3b042616e647769647468456e61626c6564c3ad42797465735265636569766564cf00000000000004d2a9427974657353656e74cf000000000000162ea8496e7465726e616cc2b650726f66696c655265766973696f6e436f756e746572cf0000000000000007 diff --git a/service/network/goldenfiles/connection-outbound.json.golden b/service/network/goldenfiles/connection-outbound.json.golden new file mode 100644 index 000000000..b55b1966b --- /dev/null +++ b/service/network/goldenfiles/connection-outbound.json.golden @@ -0,0 +1 @@ +{"ID":"6-192.168.1.10-40000-1.1.1.1-443","Type":1,"External":false,"Scope":"example.com.","IPVersion":4,"Inbound":false,"IPProtocol":6,"LocalIP":"192.168.1.10","LocalIPScope":3,"LocalPort":40000,"PID":4242,"Entity":{"IP":"1.1.1.1","IPScope":4,"Protocol":6,"Port":443,"Domain":"example.com.","ReverseDomain":"","CNAME":null,"Country":"","Coordinates":null,"ASN":0,"ASOrg":"","LocationError":"","BlockedByLists":null,"BlockedEntities":null,"ListOccurences":null,"ListsError":""},"Resolver":{"Name":"test","Type":"dot","Source":"","IP":"","Domain":"","IPScope":0,"Port":0},"Verdict":2,"ConnectionEstablished":true,"Reason":{"Msg":"allowed by rule","OptionKey":"filter/endpoints","Profile":"core:profiles/local/test","Context":null},"Started":1700000000,"Ended":0,"VerdictPermanent":true,"Inspecting":false,"Tunneled":false,"Encrypted":true,"TunnelOpts":null,"ProcessContext":{"ProcessName":"test","ProfileName":"Test","BinaryPath":"/usr/bin/test","CmdLine":"/usr/bin/test --flag","PID":4242,"CreatedAt":1699999999,"Profile":"test","Source":"local"},"DNSContext":null,"TunnelContext":null,"SplitTunContext":null,"HistoryEnabled":true,"BandwidthEnabled":true,"BytesReceived":1234,"BytesSent":5678,"Internal":false,"ProfileRevisionCounter":7} diff --git a/service/network/goldenfiles/connection-rerouted.dsd-cbor.golden b/service/network/goldenfiles/connection-rerouted.dsd-cbor.golden new file mode 100644 index 000000000..845ec9816 --- /dev/null +++ b/service/network/goldenfiles/connection-rerouted.dsd-cbor.golden @@ -0,0 +1 @@ +43b8216249446b646e732d726571756573746454797065026845787465726e616cf46553636f70656c6578616d706c652e6f72672e69495056657273696f6e0067496e626f756e64f46a495050726f746f636f6c00674c6f63616c4950f66c4c6f63616c495053636f706500694c6f63616c506f727400635049441a7ffffd7866456e74697479f6685265736f6c766572f667566572646963740875436f6e6e656374696f6e45737461626c6973686564f466526561736f6ea4634d736760694f7074696f6e4b6579606750726f66696c656067436f6e74657874f667537461727465641a6553f29065456e6465641a6553f29070566572646963745065726d616e656e74f46a496e7370656374696e67f56854756e6e656c6564f569456e63727970746564f46a54756e6e656c4f707473f66e50726f63657373436f6e74657874a86b50726f636573734e616d65606b50726f66696c654e616d65606a42696e617279506174686067436d644c696e6560635049440069437265617465644174006750726f66696c656066536f75726365606a444e53436f6e74657874f66d54756e6e656c436f6e74657874f66f53706c697454756e436f6e74657874f66e486973746f7279456e61626c6564f47042616e647769647468456e61626c6564f46d427974657352656365697665640069427974657353656e740068496e7465726e616cf47650726f66696c655265766973696f6e436f756e74657200 diff --git a/service/network/goldenfiles/connection-rerouted.dsd-json.golden b/service/network/goldenfiles/connection-rerouted.dsd-json.golden new file mode 100644 index 000000000..b1b4dc609 --- /dev/null +++ b/service/network/goldenfiles/connection-rerouted.dsd-json.golden @@ -0,0 +1 @@ +4a7b224944223a22646e732d72657175657374222c2254797065223a322c2245787465726e616c223a66616c73652c2253636f7065223a226578616d706c652e6f72672e222c22495056657273696f6e223a302c22496e626f756e64223a66616c73652c22495050726f746f636f6c223a302c224c6f63616c4950223a22222c224c6f63616c495053636f7065223a302c224c6f63616c506f7274223a302c22504944223a323134373438333030302c22456e74697479223a6e756c6c2c225265736f6c766572223a6e756c6c2c2256657264696374223a382c22436f6e6e656374696f6e45737461626c6973686564223a66616c73652c22526561736f6e223a7b224d7367223a22222c224f7074696f6e4b6579223a22222c2250726f66696c65223a22222c22436f6e74657874223a6e756c6c7d2c2253746172746564223a313730303030303430302c22456e646564223a313730303030303430302c22566572646963745065726d616e656e74223a66616c73652c22496e7370656374696e67223a747275652c2254756e6e656c6564223a747275652c22456e63727970746564223a66616c73652c2254756e6e656c4f707473223a6e756c6c2c2250726f63657373436f6e74657874223a7b2250726f636573734e616d65223a22222c2250726f66696c654e616d65223a22222c2242696e61727950617468223a22222c22436d644c696e65223a22222c22504944223a302c22437265617465644174223a302c2250726f66696c65223a22222c22536f75726365223a22227d2c22444e53436f6e74657874223a6e756c6c2c2254756e6e656c436f6e74657874223a6e756c6c2c2253706c697454756e436f6e74657874223a6e756c6c2c22486973746f7279456e61626c6564223a66616c73652c2242616e647769647468456e61626c6564223a66616c73652c2242797465735265636569766564223a302c22427974657353656e74223a302c22496e7465726e616c223a66616c73652c2250726f66696c655265766973696f6e436f756e746572223a307d diff --git a/service/network/goldenfiles/connection-rerouted.dsd-msgpack.golden b/service/network/goldenfiles/connection-rerouted.dsd-msgpack.golden new file mode 100644 index 000000000..bd697ebee --- /dev/null +++ b/service/network/goldenfiles/connection-rerouted.dsd-msgpack.golden @@ -0,0 +1 @@ +4dde0021a24944ab646e732d72657175657374a454797065d002a845787465726e616cc2a553636f7065ac6578616d706c652e6f72672ea9495056657273696f6ecc00a7496e626f756e64c2aa495050726f746f636f6ccc00a74c6f63616c4950c0ac4c6f63616c495053636f7065d000a94c6f63616c506f7274cd0000a3504944ce7ffffd78a6456e74697479c0a85265736f6c766572c0a756657264696374d008b5436f6e6e656374696f6e45737461626c6973686564c2a6526561736f6e84a34d7367a0a94f7074696f6e4b6579a0a750726f66696c65a0a7436f6e74657874c0a753746172746564d3000000006553f290a5456e646564d3000000006553f290b0566572646963745065726d616e656e74c2aa496e7370656374696e67c3a854756e6e656c6564c3a9456e63727970746564c2aa54756e6e656c4f707473c0ae50726f63657373436f6e7465787488ab50726f636573734e616d65a0ab50726f66696c654e616d65a0aa42696e61727950617468a0a7436d644c696e65a0a350494400a9437265617465644174d30000000000000000a750726f66696c65a0a6536f75726365a0aa444e53436f6e74657874c0ad54756e6e656c436f6e74657874c0af53706c697454756e436f6e74657874c0ae486973746f7279456e61626c6564c2b042616e647769647468456e61626c6564c2ad42797465735265636569766564cf0000000000000000a9427974657353656e74cf0000000000000000a8496e7465726e616cc2b650726f66696c655265766973696f6e436f756e746572cf0000000000000000 diff --git a/service/network/goldenfiles/connection-rerouted.json.golden b/service/network/goldenfiles/connection-rerouted.json.golden new file mode 100644 index 000000000..416a3fe5c --- /dev/null +++ b/service/network/goldenfiles/connection-rerouted.json.golden @@ -0,0 +1 @@ +{"ID":"dns-request","Type":2,"External":false,"Scope":"example.org.","IPVersion":0,"Inbound":false,"IPProtocol":0,"LocalIP":"","LocalIPScope":0,"LocalPort":0,"PID":2147483000,"Entity":null,"Resolver":null,"Verdict":8,"ConnectionEstablished":false,"Reason":{"Msg":"","OptionKey":"","Profile":"","Context":null},"Started":1700000400,"Ended":1700000400,"VerdictPermanent":false,"Inspecting":true,"Tunneled":true,"Encrypted":false,"TunnelOpts":null,"ProcessContext":{"ProcessName":"","ProfileName":"","BinaryPath":"","CmdLine":"","PID":0,"CreatedAt":0,"Profile":"","Source":""},"DNSContext":null,"TunnelContext":null,"SplitTunContext":null,"HistoryEnabled":false,"BandwidthEnabled":false,"BytesReceived":0,"BytesSent":0,"Internal":false,"ProfileRevisionCounter":0} diff --git a/service/network/goldenfiles/connection-undecided.dsd-cbor.golden b/service/network/goldenfiles/connection-undecided.dsd-cbor.golden new file mode 100644 index 000000000..8597d1980 --- /dev/null +++ b/service/network/goldenfiles/connection-undecided.dsd-cbor.golden @@ -0,0 +1 @@ +43b821624944781a312d3139322e3136382e312e31302d302d382e382e382e382d306454797065016845787465726e616cf46553636f70656069495056657273696f6e0467496e626f756e64f46a495050726f746f636f6c01674c6f63616c4950f66c4c6f63616c495053636f706500694c6f63616c506f727400635049440066456e74697479f6685265736f6c766572f667566572646963740075436f6e6e656374696f6e45737461626c6973686564f466526561736f6ea4634d736760694f7074696f6e4b6579606750726f66696c656067436f6e74657874f667537461727465641a6553f22c65456e6465640070566572646963745065726d616e656e74f46a496e7370656374696e67f46854756e6e656c6564f469456e63727970746564f46a54756e6e656c4f707473f66e50726f63657373436f6e74657874a86b50726f636573734e616d65606b50726f66696c654e616d65606a42696e617279506174686067436d644c696e6560635049440069437265617465644174006750726f66696c656066536f75726365606a444e53436f6e74657874f66d54756e6e656c436f6e74657874f66f53706c697454756e436f6e74657874f66e486973746f7279456e61626c6564f47042616e647769647468456e61626c6564f46d427974657352656365697665640069427974657353656e740068496e7465726e616cf47650726f66696c655265766973696f6e436f756e74657200 diff --git a/service/network/goldenfiles/connection-undecided.dsd-json.golden b/service/network/goldenfiles/connection-undecided.dsd-json.golden new file mode 100644 index 000000000..f9d53406d --- /dev/null +++ b/service/network/goldenfiles/connection-undecided.dsd-json.golden @@ -0,0 +1 @@ +4a7b224944223a22312d3139322e3136382e312e31302d302d382e382e382e382d30222c2254797065223a312c2245787465726e616c223a66616c73652c2253636f7065223a22222c22495056657273696f6e223a342c22496e626f756e64223a66616c73652c22495050726f746f636f6c223a312c224c6f63616c4950223a22222c224c6f63616c495053636f7065223a302c224c6f63616c506f7274223a302c22504944223a302c22456e74697479223a6e756c6c2c225265736f6c766572223a6e756c6c2c2256657264696374223a302c22436f6e6e656374696f6e45737461626c6973686564223a66616c73652c22526561736f6e223a7b224d7367223a22222c224f7074696f6e4b6579223a22222c2250726f66696c65223a22222c22436f6e74657874223a6e756c6c7d2c2253746172746564223a313730303030303330302c22456e646564223a302c22566572646963745065726d616e656e74223a66616c73652c22496e7370656374696e67223a66616c73652c2254756e6e656c6564223a66616c73652c22456e63727970746564223a66616c73652c2254756e6e656c4f707473223a6e756c6c2c2250726f63657373436f6e74657874223a7b2250726f636573734e616d65223a22222c2250726f66696c654e616d65223a22222c2242696e61727950617468223a22222c22436d644c696e65223a22222c22504944223a302c22437265617465644174223a302c2250726f66696c65223a22222c22536f75726365223a22227d2c22444e53436f6e74657874223a6e756c6c2c2254756e6e656c436f6e74657874223a6e756c6c2c2253706c697454756e436f6e74657874223a6e756c6c2c22486973746f7279456e61626c6564223a66616c73652c2242616e647769647468456e61626c6564223a66616c73652c2242797465735265636569766564223a302c22427974657353656e74223a302c22496e7465726e616c223a66616c73652c2250726f66696c655265766973696f6e436f756e746572223a307d diff --git a/service/network/goldenfiles/connection-undecided.dsd-msgpack.golden b/service/network/goldenfiles/connection-undecided.dsd-msgpack.golden new file mode 100644 index 000000000..595b44a93 --- /dev/null +++ b/service/network/goldenfiles/connection-undecided.dsd-msgpack.golden @@ -0,0 +1 @@ +4dde0021a24944ba312d3139322e3136382e312e31302d302d382e382e382e382d30a454797065d001a845787465726e616cc2a553636f7065a0a9495056657273696f6ecc04a7496e626f756e64c2aa495050726f746f636f6ccc01a74c6f63616c4950c0ac4c6f63616c495053636f7065d000a94c6f63616c506f7274cd0000a350494400a6456e74697479c0a85265736f6c766572c0a756657264696374d000b5436f6e6e656374696f6e45737461626c6973686564c2a6526561736f6e84a34d7367a0a94f7074696f6e4b6579a0a750726f66696c65a0a7436f6e74657874c0a753746172746564d3000000006553f22ca5456e646564d30000000000000000b0566572646963745065726d616e656e74c2aa496e7370656374696e67c2a854756e6e656c6564c2a9456e63727970746564c2aa54756e6e656c4f707473c0ae50726f63657373436f6e7465787488ab50726f636573734e616d65a0ab50726f66696c654e616d65a0aa42696e61727950617468a0a7436d644c696e65a0a350494400a9437265617465644174d30000000000000000a750726f66696c65a0a6536f75726365a0aa444e53436f6e74657874c0ad54756e6e656c436f6e74657874c0af53706c697454756e436f6e74657874c0ae486973746f7279456e61626c6564c2b042616e647769647468456e61626c6564c2ad42797465735265636569766564cf0000000000000000a9427974657353656e74cf0000000000000000a8496e7465726e616cc2b650726f66696c655265766973696f6e436f756e746572cf0000000000000000 diff --git a/service/network/goldenfiles/connection-undecided.json.golden b/service/network/goldenfiles/connection-undecided.json.golden new file mode 100644 index 000000000..c057bdeac --- /dev/null +++ b/service/network/goldenfiles/connection-undecided.json.golden @@ -0,0 +1 @@ +{"ID":"1-192.168.1.10-0-8.8.8.8-0","Type":1,"External":false,"Scope":"","IPVersion":4,"Inbound":false,"IPProtocol":1,"LocalIP":"","LocalIPScope":0,"LocalPort":0,"PID":0,"Entity":null,"Resolver":null,"Verdict":0,"ConnectionEstablished":false,"Reason":{"Msg":"","OptionKey":"","Profile":"","Context":null},"Started":1700000300,"Ended":0,"VerdictPermanent":false,"Inspecting":false,"Tunneled":false,"Encrypted":false,"TunnelOpts":null,"ProcessContext":{"ProcessName":"","ProfileName":"","BinaryPath":"","CmdLine":"","PID":0,"CreatedAt":0,"Profile":"","Source":""},"DNSContext":null,"TunnelContext":null,"SplitTunContext":null,"HistoryEnabled":false,"BandwidthEnabled":false,"BytesReceived":0,"BytesSent":0,"Internal":false,"ProfileRevisionCounter":0} diff --git a/service/network/iphelper/tables.go b/service/network/iphelper/tables.go index 8315ca781..f7a415b12 100644 --- a/service/network/iphelper/tables.go +++ b/service/network/iphelper/tables.go @@ -182,7 +182,7 @@ func (lbf *learningBufSize) increaseBufSize(minSize int) int { } // getTable returns the current connection state table of Windows of the given protocol and IP version. -func (ipHelper *IPHelper) getTable(ipVersion, protocol uint8) (connections []*socket.ConnectionInfo, binds []*socket.BindInfo, err error) { //nolint:gocognit,gocycle // TODO +func (ipHelper *IPHelper) getTable(ipVersion, protocol uint8) (connections []*socket.ConnectionInfo, binds []*socket.BindInfo, err error) { //nolint:gocognit // TODO // docs: https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getextendedtcptable if !ipHelper.valid.IsSet() { diff --git a/service/network/module.go b/service/network/module.go index 02b863dee..9235f1e2b 100644 --- a/service/network/module.go +++ b/service/network/module.go @@ -57,12 +57,28 @@ func (n *Network) SetSleep(enabled bool) { } } -var defaultFirewallHandler FirewallHandler +var ( + // defaultFirewallHandler handles packets of connections without a firewall + // handler. It is called with the connection locked. + defaultFirewallHandler FirewallHandler + // defaultLockFreeFirewallHandler handles packets of connections without + // a firewall handler directly on the packet dispatching goroutine. It is + // called without the connection being locked. + defaultLockFreeFirewallHandler FirewallHandler +) -// SetDefaultFirewallHandler sets the default firewall handler. -func SetDefaultFirewallHandler(handler FirewallHandler) { +// SetDefaultFirewallHandler sets the default firewall handlers, which are +// used for connections that have no firewall handler (anymore). +// +// The handler is called with the connection locked, like any other firewall +// handler. The lockFreeHandler is called without the connection being locked +// and must not wait for the connection lock. It may only use the immutable +// attributes of the connection and its lock-free accessors, such as +// VerdictState. +func SetDefaultFirewallHandler(handler, lockFreeHandler FirewallHandler) { if defaultFirewallHandler == nil { defaultFirewallHandler = handler + defaultLockFreeFirewallHandler = lockFreeHandler } } @@ -120,7 +136,7 @@ func reAttributeConnections(_ *mgr.WorkerCtx, profileID string) (bool, error) { for _, conn := range conns.clone() { if reAttributeConnection(ctx, conn, profileID, profileSource) { reAttributed++ - tracer.Debugf("filter: re-attributed %s to %s", conn, conn.process.PrimaryProfileID) + tracer.Debugf("filter: re-attributed %s to %s", conn, conn.process.GetPrimaryProfileID()) } } @@ -128,7 +144,7 @@ func reAttributeConnections(_ *mgr.WorkerCtx, profileID string) (bool, error) { for _, conn := range dnsConns.clone() { if reAttributeConnection(ctx, conn, profileID, profileSource) { reAttributed++ - tracer.Debugf("filter: re-attributed %s to %s", conn, conn.process.PrimaryProfileID) + tracer.Debugf("filter: re-attributed %s to %s", conn, conn.process.GetPrimaryProfileID()) } } @@ -165,7 +181,7 @@ func reAttributeConnection(ctx context.Context, conn *Connection, profileID, pro // Trigger event for re-attribution. module.EventConnectionReattributed.Submit(conn.ID) - log.Tracer(ctx).Debugf("filter: re-attributed %s to %s", conn, conn.process.PrimaryProfileID) + log.Tracer(ctx).Debugf("filter: re-attributed %s to %s", conn, conn.process.GetPrimaryProfileID()) return true } diff --git a/service/network/netutils/ip.go b/service/network/netutils/ip.go index a9d6d0ccb..6f8013faf 100644 --- a/service/network/netutils/ip.go +++ b/service/network/netutils/ip.go @@ -99,6 +99,10 @@ func GetIPScope(ip net.IP) IPScope { //nolint:gocognit case ip[0] == 0xfe && ip[1]&0xc0 == 0x80: // fe80::/10 return LinkLocal + case ip[0] == 0xfe && ip[1]&0xc0 == 0xc0: + // fec0::/10 - deprecated site-local addresses (RFC 3879), which are + // never globally routed. QEMU's user networking still uses them. + return SiteLocal case ip[0] == 0xff && ip[1] <= 0x05: // ff00::/16 - ff05::/16 return LocalMulticast diff --git a/service/network/netutils/ip_test.go b/service/network/netutils/ip_test.go index 5dddd5d49..146b3e0e1 100644 --- a/service/network/netutils/ip_test.go +++ b/service/network/netutils/ip_test.go @@ -16,6 +16,13 @@ func TestIPScope(t *testing.T) { testScope(t, net.IPv4(172, 16, 1, 1), SiteLocal) testScope(t, net.IPv4(172, 31, 1, 1), SiteLocal) testScope(t, net.IPv4(172, 32, 1, 1), Global) + + testScope(t, net.ParseIP("2a01:4f8::1"), Global) + testScope(t, net.ParseIP("fd00::1"), SiteLocal) + testScope(t, net.ParseIP("fe80::1"), LinkLocal) + testScope(t, net.ParseIP("fec0::15"), SiteLocal) + testScope(t, net.ParseIP("feff::1"), SiteLocal) + testScope(t, net.ParseIP("ff02::1"), LocalMulticast) } func testScope(t *testing.T, ip net.IP, expectedScope IPScope) { diff --git a/service/network/packet/info_only.go b/service/network/packet/info_only.go index 09e349e56..bd7f0e59b 100644 --- a/service/network/packet/info_only.go +++ b/service/network/packet/info_only.go @@ -69,11 +69,6 @@ func (pkt *InfoPacket) RerouteToNameserver() error { return ErrInfoOnlyPacket } -// RerouteToTunnel does nothing on an info-only packet. -func (pkt *InfoPacket) RerouteToTunnel() error { - return ErrInfoOnlyPacket -} - func (pkt *InfoPacket) RerouteToSplitTun() error { return ErrInfoOnlyPacket } diff --git a/service/network/packet/packet.go b/service/network/packet/packet.go index 973d95c51..df1472b50 100644 --- a/service/network/packet/packet.go +++ b/service/network/packet/packet.go @@ -237,7 +237,6 @@ type Packet interface { PermanentBlock() error PermanentDrop() error RerouteToNameserver() error - RerouteToTunnel() error RerouteToSplitTun() error FastTrackedByIntegration() bool InfoOnly() bool diff --git a/service/network/packet/packetinfo.go b/service/network/packet/packetinfo.go index 821316259..e36b0390b 100644 --- a/service/network/packet/packetinfo.go +++ b/service/network/packet/packetinfo.go @@ -1,8 +1,9 @@ package packet import ( - "fmt" "net" + "net/netip" + "strconv" "time" ) @@ -61,16 +62,42 @@ func (pi *Info) CreateConnectionID() string { // CreateConnectionID creates a connection ID. func CreateConnectionID(protocol IPProtocol, src net.IP, srcPort uint16, dst net.IP, dstPort uint16, inbound bool) string { + // The output format is identical to the former fmt.Sprintf based + // implementation ("%d-%s-%d-%s-%d" / "%d-%s-%s"), but is built in a + // stack buffer to avoid per-packet allocations. + var stack [96]byte + buf := strconv.AppendUint(stack[:0], uint64(protocol), 10) + // TODO: make this ID not depend on the packet direction for better support for forwarded packets. + if inbound { + src, dst = dst, src + srcPort, dstPort = dstPort, srcPort + } + + buf = append(buf, '-') + buf = appendIP(buf, src) if protocol == TCP || protocol == UDP { - if inbound { - return fmt.Sprintf("%d-%s-%d-%s-%d", protocol, dst, dstPort, src, srcPort) - } - return fmt.Sprintf("%d-%s-%d-%s-%d", protocol, src, srcPort, dst, dstPort) + buf = append(buf, '-') + buf = strconv.AppendUint(buf, uint64(srcPort), 10) + } + buf = append(buf, '-') + buf = appendIP(buf, dst) + if protocol == TCP || protocol == UDP { + buf = append(buf, '-') + buf = strconv.AppendUint(buf, uint64(dstPort), 10) } - if inbound { - return fmt.Sprintf("%d-%s-%s", protocol, dst, src) + return string(buf) +} + +// appendIP appends the text form of ip, identical to ip.String(). +func appendIP(buf []byte, ip net.IP) []byte { + if len(ip) == net.IPv4len || len(ip) == net.IPv6len { + if addr, ok := netip.AddrFromSlice(ip); ok { + // net.IP.String prints 4-in-6 addresses as dotted quad. + return addr.Unmap().AppendTo(buf) + } } - return fmt.Sprintf("%d-%s-%s", protocol, src, dst) + // nil/empty and invalid lengths ("", "?hex"). + return append(buf, ip.String()...) } diff --git a/service/network/packet/packetinfo_id_test.go b/service/network/packet/packetinfo_id_test.go new file mode 100644 index 000000000..075c19adc --- /dev/null +++ b/service/network/packet/packetinfo_id_test.go @@ -0,0 +1,140 @@ +package packet + +import ( + "fmt" + "math/rand" + "net" + "testing" +) + +// referenceConnectionID is a copy of the original fmt.Sprintf implementation. +func referenceConnectionID(protocol IPProtocol, src net.IP, srcPort uint16, dst net.IP, dstPort uint16, inbound bool) string { + if protocol == TCP || protocol == UDP { + if inbound { + return fmt.Sprintf("%d-%s-%d-%s-%d", protocol, dst, dstPort, src, srcPort) + } + return fmt.Sprintf("%d-%s-%d-%s-%d", protocol, src, srcPort, dst, dstPort) + } + + if inbound { + return fmt.Sprintf("%d-%s-%s", protocol, dst, src) + } + return fmt.Sprintf("%d-%s-%s", protocol, src, dst) +} + +func testIPs() []net.IP { + return []net.IP{ + nil, + {}, + {1}, + {1, 2, 3}, + {1, 2, 3, 4, 5}, + make(net.IP, 15), + make(net.IP, 17), + make(net.IP, 20), + net.IPv4(0, 0, 0, 0), + net.IPv4(192, 168, 1, 255).To4(), + net.IPv4(192, 168, 1, 255), // 16 byte v4-mapped + net.IPv4(255, 255, 255, 255), + net.IPv6zero, + net.IPv6loopback, + net.IPv6unspecified, + net.ParseIP("::ffff:1.2.3.4"), + net.ParseIP("::1.2.3.4"), // v4-compatible, not mapped + net.ParseIP("64:ff9b::1.2.3.4"), + net.ParseIP("2001:db8::1"), + net.ParseIP("2001:db8:0:0:1:0:0:1"), + net.ParseIP("2001:db8:0:1:1:1:1:1"), + net.ParseIP("fe80::1"), + net.ParseIP("ff02::fb"), + net.ParseIP("2001:db8:aaaa:bbbb:cccc:dddd:eeee:ffff"), + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xfe, 1, 2, 3, 4}, // almost mapped + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 1, 2, 3, 4}, + } +} + +func TestCreateConnectionIDEquivalence(t *testing.T) { + t.Parallel() + + protocols := []IPProtocol{0, 1, ICMP, TCP, UDP, 41, 58, 132, 255} + ports := []uint16{0, 1, 53, 443, 8080, 65535} + + check := func(proto IPProtocol, src net.IP, sp uint16, dst net.IP, dp uint16, inbound bool) { + t.Helper() + want := referenceConnectionID(proto, src, sp, dst, dp, inbound) + if got := CreateConnectionID(proto, src, sp, dst, dp, inbound); got != want { + t.Fatalf("mismatch proto=%d src=%v(%d) dst=%v(%d) in=%v: got %q want %q", proto, []byte(src), sp, []byte(dst), dp, inbound, got, want) + } + } + + ips := testIPs() + for _, proto := range protocols { + for _, src := range ips { + for _, dst := range ips { + for _, inbound := range []bool{false, true} { + check(proto, src, 1234, dst, 80, inbound) + } + } + } + for _, sp := range ports { + for _, dp := range ports { + check(proto, ips[9], sp, ips[18], dp, false) + check(proto, ips[9], sp, ips[18], dp, true) + } + } + } + + // Randomized. + rnd := rand.New(rand.NewSource(1)) //nolint:gosec + randIP := func() net.IP { + var ip net.IP + switch rnd.Intn(6) { + case 0: + ip = make(net.IP, 4) + case 1: + ip = make(net.IP, 16) + case 2: // v4-mapped + ip = make(net.IP, 16) + ip[10], ip[11] = 0xff, 0xff + _, _ = rnd.Read(ip[12:]) // Never returns an error. + return ip + case 3: // sparse IPv6 to exercise :: compression + ip = make(net.IP, 16) + for i := range ip { + if rnd.Intn(3) == 0 { + ip[i] = byte(rnd.Intn(256)) //nolint:gosec // Intn(256) is always in byte range. + } + } + return ip + case 4: + ip = make(net.IP, rnd.Intn(40)) + default: + ip = make(net.IP, 16) + } + _, _ = rnd.Read(ip) // Never returns an error. + return ip + } + for range 200000 { + check(IPProtocol(rnd.Intn(256)), randIP(), uint16(rnd.Intn(65536)), randIP(), uint16(rnd.Intn(65536)), rnd.Intn(2) == 0) //nolint:gosec // Intn bounds are within the target type ranges. + } +} + +var benchSink string + +func BenchmarkCreateConnectionID(b *testing.B) { + v4s, v4d := net.IPv4(192, 168, 1, 23).To4(), net.IPv4(142, 250, 185, 78).To4() + v6s, v6d := net.ParseIP("fd00:1234:5678::23"), net.ParseIP("2a00:1450:4001:82b::200e") + + b.Run("IPv4", func(b *testing.B) { + b.ReportAllocs() + for range b.N { + benchSink = CreateConnectionID(TCP, v4s, 51234, v4d, 443, false) + } + }) + b.Run("IPv6", func(b *testing.B) { + b.ReportAllocs() + for range b.N { + benchSink = CreateConnectionID(TCP, v6s, 51234, v6d, 443, false) + } + }) +} diff --git a/service/network/packet/parse.go b/service/network/packet/parse.go index adfc69d90..cd9659725 100644 --- a/service/network/packet/parse.go +++ b/service/network/packet/parse.go @@ -111,6 +111,10 @@ func ParseLayer3(packetData []byte, pktBase *Base) (err error) { if len(packetData) == 0 { return errors.New("empty packet") } + // Hide any spare capacity of the buffer from the decoders: as we decode + // without copying, some gopacket decoders would otherwise read past the end + // of the packet into the rest of the buffer instead of failing. + packetData = packetData[:len(packetData):len(packetData)] pktBase.layer3Data = packetData @@ -161,6 +165,10 @@ func ParseLayer4(packetData []byte, pktBase *Base) (err error) { if len(packetData) == 0 { return errors.New("empty packet") } + // Hide any spare capacity of the buffer from the decoders: as we decode + // without copying, some gopacket decoders would otherwise read past the end + // of the packet into the rest of the buffer instead of failing. + packetData = packetData[:len(packetData):len(packetData)] var layer gopacket.LayerType switch pktBase.info.Protocol { diff --git a/service/network/packet/parse_fuzz_test.go b/service/network/packet/parse_fuzz_test.go new file mode 100644 index 000000000..3acc93cad --- /dev/null +++ b/service/network/packet/parse_fuzz_test.go @@ -0,0 +1,260 @@ +package packet + +import ( + "bytes" + "net" + "testing" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" +) + +// serializeSeed builds a seed packet from the given gopacket layers. +func serializeSeed(tb testing.TB, ls ...gopacket.SerializableLayer) []byte { + tb.Helper() + + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true} + err := gopacket.SerializeLayers(buf, opts, ls...) + if err != nil { + tb.Fatalf("failed to serialize seed: %s", err) + } + return append([]byte(nil), buf.Bytes()...) +} + +// layer3Seeds returns valid IPv4/IPv6 packets covering every protocol the +// parser knows about, plus some unusual but valid shapes (fragments, +// extension headers, protocol 61). +func layer3Seeds(tb testing.TB) [][]byte { + tb.Helper() + + src4, dst4 := net.IPv4(192, 168, 1, 2).To4(), net.IPv4(1, 1, 1, 1).To4() + src6, dst6 := net.ParseIP("fd00::2"), net.ParseIP("2001:db8::1") + ip4 := func(proto layers.IPProtocol) *layers.IPv4 { + return &layers.IPv4{Version: 4, IHL: 5, TTL: 64, Protocol: proto, SrcIP: src4, DstIP: dst4} + } + ip6 := func(next layers.IPProtocol) *layers.IPv6 { + return &layers.IPv6{Version: 6, HopLimit: 64, NextHeader: next, SrcIP: src6, DstIP: dst6} + } + payload := gopacket.Payload("hello") + + seeds := make([][]byte, 0, 11) + + // IPv4. + v4 := ip4(layers.IPProtocolTCP) + tcp := &layers.TCP{SrcPort: 40000, DstPort: 443, SYN: true, Window: 1024} + _ = tcp.SetNetworkLayerForChecksum(v4) + seeds = append(seeds, serializeSeed(tb, v4, tcp, payload)) + + v4 = ip4(layers.IPProtocolUDP) + udp := &layers.UDP{SrcPort: 40001, DstPort: 53} + _ = udp.SetNetworkLayerForChecksum(v4) + seeds = append(seeds, serializeSeed(tb, v4, udp, payload)) + + seeds = append(seeds, serializeSeed(tb, ip4(layers.IPProtocolICMPv4), + &layers.ICMPv4{TypeCode: layers.CreateICMPv4TypeCode(layers.ICMPv4TypeEchoRequest, 0), Id: 1, Seq: 1}, payload)) + seeds = append(seeds, serializeSeed(tb, ip4(layers.IPProtocolIGMP), + gopacket.Payload{0x11, 0x64, 0xee, 0x9b, 0, 0, 0, 0})) // IGMPv2 membership query + seeds = append(seeds, serializeSeed(tb, ip4(layers.IPProtocol(61)), payload)) + + // IPv4 non-first fragment of a TCP packet. + frag := ip4(layers.IPProtocolTCP) + frag.FragOffset = 10 + seeds = append(seeds, serializeSeed(tb, frag, payload)) + + // IPv6. + v6 := ip6(layers.IPProtocolTCP) + tcp = &layers.TCP{SrcPort: 40002, DstPort: 80, ACK: true, Window: 1024} + _ = tcp.SetNetworkLayerForChecksum(v6) + seeds = append(seeds, serializeSeed(tb, v6, tcp, payload)) + + v6 = ip6(layers.IPProtocolUDP) + udp = &layers.UDP{SrcPort: 40003, DstPort: 53} + _ = udp.SetNetworkLayerForChecksum(v6) + seeds = append(seeds, serializeSeed(tb, v6, udp, payload)) + + v6 = ip6(layers.IPProtocolICMPv6) + icmp6 := &layers.ICMPv6{TypeCode: layers.CreateICMPv6TypeCode(layers.ICMPv6TypeEchoRequest, 0)} + _ = icmp6.SetNetworkLayerForChecksum(v6) + seeds = append(seeds, serializeSeed(tb, v6, icmp6, &layers.ICMPv6Echo{Identifier: 1, SeqNumber: 1}, payload)) + + // IPv6 with a hop-by-hop extension header in front of UDP. + v6 = ip6(layers.IPProtocolIPv6HopByHop) + hbh := &layers.IPv6HopByHop{} + hbh.NextHeader = layers.IPProtocolUDP + hbh.Options = []*layers.IPv6HopByHopOption{{OptionType: 1, OptionLength: 4, OptionData: []byte{0, 0, 0, 0}}} + udp = &layers.UDP{SrcPort: 40004, DstPort: 5353} + _ = udp.SetNetworkLayerForChecksum(v6) + seeds = append(seeds, serializeSeed(tb, v6, hbh, udp, payload)) + + // IPv6 fragment header (first fragment) in front of TCP. + seeds = append(seeds, serializeSeed(tb, ip6(layers.IPProtocolIPv6Fragment), + gopacket.Payload{byte(layers.IPProtocolTCP), 0, 0, 1, 0, 0, 0, 1}, payload)) + + return seeds +} + +// checkParsedInfo checks invariants that must hold after successful parsing +// and exercises the accessors the platform-neutral callers use. +func checkParsedInfo(t *testing.T, base *Base) { + t.Helper() + + info := base.Info() + pkt := base.Layers() + if pkt == nil { + t.Fatal("parsing succeeded, but no layers were saved") + } + + if transport := pkt.TransportLayer(); transport != nil { + switch tl := transport.(type) { + case *layers.TCP: + if info.Protocol != TCP || info.SrcPort != uint16(tl.SrcPort) || info.DstPort != uint16(tl.DstPort) { + t.Fatalf("TCP layer does not match info: %+v", info) + } + case *layers.UDP: + if info.Protocol != UDP || info.SrcPort != uint16(tl.SrcPort) || info.DstPort != uint16(tl.DstPort) { + t.Fatalf("UDP layer does not match info: %+v", info) + } + } + if !bytes.Equal(base.Payload(), transport.LayerPayload()) { + t.Fatal("payload does not match transport payload") + } + } + + // Accessors used by the firewall and netenv. + _ = pkt.LayerClass(layers.LayerClassIPControl) + _ = pkt.Layer(layers.LayerTypeICMPv4) + _ = pkt.Layer(layers.LayerTypeICMPv6) + _ = base.GetConnectionID() + _ = base.FmtPacket() + _ = base.FmtRemoteAddress() + _ = base.HasPorts() +} + +// clip returns a copy of data without spare capacity. +func clip(data []byte) []byte { + c := make([]byte, len(data)) + copy(c, data) + return c +} + +// compareParseResults fails if two parses of the same packet differ. +func compareParseResults(t *testing.T, a *Base, aErr error, b *Base, bErr error) { + t.Helper() + + if (aErr == nil) != (bErr == nil) { + t.Fatalf("parse result depends on buffer capacity: %v vs %v (%+v / %+v)", aErr, bErr, a.Info(), b.Info()) + } + ai, bi := a.Info(), b.Info() + if ai.Version != bi.Version || ai.Protocol != bi.Protocol || + ai.SrcPort != bi.SrcPort || ai.DstPort != bi.DstPort || + !ai.Src.Equal(bi.Src) || !ai.Dst.Equal(bi.Dst) { + t.Fatalf("parsed info depends on buffer capacity: %+v vs %+v", ai, bi) + } + if !bytes.Equal(a.Payload(), b.Payload()) { + t.Fatal("payload depends on buffer capacity") + } +} + +func FuzzParseLayer3(f *testing.F) { + for _, seed := range layer3Seeds(f) { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, data []byte) { + // Use a buffer without spare capacity, so that parsing is deterministic. + data = clip(data) + orig := clip(data) + + base := &Base{} + err := ParseLayer3(data, base) + + // Parsing must not depend on the spare capacity of the given buffer. + padded := make([]byte, len(data), len(data)+256) + copy(padded, data) + paddedBase := &Base{} + paddedErr := ParseLayer3(padded, paddedBase) + compareParseResults(t, base, err, paddedBase, paddedErr) + + if !bytes.Equal(orig, data) { + t.Fatal("parsing modified the packet data") + } + if err != nil { + return + } + + info := base.Info() + switch data[0] >> 4 { + case 4: + if info.Version != IPv4 || len(info.Src) != net.IPv4len || len(info.Dst) != net.IPv4len { + t.Fatalf("bad IPv4 info: %+v", info) + } + case 6: + if info.Version != IPv6 || len(info.Src) != net.IPv6len || len(info.Dst) != net.IPv6len { + t.Fatalf("bad IPv6 info: %+v", info) + } + default: + t.Fatalf("accepted unknown IP version %d", data[0]>>4) + } + checkParsedInfo(t, base) + + // The lazy parse must yield the same result as an eager one. + eager := gopacket.NewPacket(orig, base.Layers().Layers()[0].LayerType(), gopacket.Default) + if nl := eager.NetworkLayer(); nl == nil || nl.NetworkFlow() != base.Layers().NetworkLayer().NetworkFlow() { + t.Fatal("lazy and eager parse disagree on the network layer") + } + if eager.ErrorLayer() != nil && info.Protocol != AnyHostInternalProtocol61 { + t.Fatalf("eager parse failed, lazy parse did not: %s", eager.ErrorLayer().Error()) + } + }) +} + +func FuzzParseLayer4(f *testing.F) { + // Seed with the transport parts of the layer 3 seeds. + for _, seed := range layer3Seeds(f) { + pkt := gopacket.NewPacket(seed, layers.LayerTypeIPv4, gopacket.Default) + if seed[0]>>4 == 6 { + pkt = gopacket.NewPacket(seed, layers.LayerTypeIPv6, gopacket.Default) + } + nl := pkt.NetworkLayer() + if nl == nil || len(nl.LayerPayload()) == 0 { + continue + } + var proto byte + switch ip := nl.(type) { + case *layers.IPv4: + proto = byte(ip.Protocol) + case *layers.IPv6: + proto = byte(ip.NextHeader) + } + f.Add(proto, nl.LayerPayload()) + } + + f.Fuzz(func(t *testing.T, proto byte, data []byte) { + data = clip(data) + base := &Base{} + base.Info().Protocol = IPProtocol(proto) + err := ParseLayer4(data, base) + + padded := make([]byte, len(data), len(data)+256) + copy(padded, data) + paddedBase := &Base{} + paddedBase.Info().Protocol = IPProtocol(proto) + paddedErr := ParseLayer4(padded, paddedBase) + compareParseResults(t, base, err, paddedBase, paddedErr) + + if err != nil { + return + } + + switch IPProtocol(proto) { //nolint:exhaustive // Only supported protocols may be parsed. + case TCP, UDP, ICMP, ICMPv6, IGMP: + default: + t.Fatalf("accepted unsupported protocol %d", proto) + } + if base.Info().Protocol != IPProtocol(proto) { + t.Fatalf("protocol changed from %d to %d", proto, base.Info().Protocol) + } + checkParsedInfo(t, base) + }) +} diff --git a/service/network/packet/parse_test.go b/service/network/packet/parse_test.go new file mode 100644 index 000000000..6d85e66b5 --- /dev/null +++ b/service/network/packet/parse_test.go @@ -0,0 +1,68 @@ +package packet + +import ( + "testing" +) + +// TestParseIgnoresSpareCapacity checks that parsing does not read past the end +// of the packet into the spare capacity of the given buffer. +func TestParseIgnoresSpareCapacity(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + layer3 bool + proto IPProtocol + payload []byte + }{ + { + // IPv6 + VRRP (112) claiming one more IP address than present. + name: "IPv6 VRRP", + layer3: true, + payload: []byte("a00000p00000000000000000000000000000000010000000"), + }, + { + // IPv4 + RDP (27) with a truncated header. + name: "IPv4 RDP", + layer3: true, + payload: []byte("E00000\x00\x000\x1b00000000000100"), + }, + { + // TCP, too short for its header. + name: "layer 4 TCP", + proto: TCP, + payload: []byte{0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0x50}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + parse := func(data []byte) error { + base := &Base{} + base.Info().Protocol = tc.proto + if tc.layer3 { + return ParseLayer3(data, base) + } + return ParseLayer4(data, base) + } + + exact := make([]byte, len(tc.payload)) + copy(exact, tc.payload) + exactErr := parse(exact) + if exactErr == nil { + t.Fatal("expected malformed packet to fail parsing") + } + + // Same packet, in a larger buffer, as done by some interception + // integrations. + padded := make([]byte, len(tc.payload), len(tc.payload)+256) + copy(padded, tc.payload) + paddedErr := parse(padded) + if paddedErr == nil { + t.Fatalf("malformed packet parsed successfully with spare buffer capacity (without: %s)", exactErr) + } + }) + } +} diff --git a/service/network/packet/testdata/fuzz/FuzzParseLayer3/4247139be95f73ef b/service/network/packet/testdata/fuzz/FuzzParseLayer3/4247139be95f73ef new file mode 100644 index 000000000..de601f1ff --- /dev/null +++ b/service/network/packet/testdata/fuzz/FuzzParseLayer3/4247139be95f73ef @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("a00000p00000000000000000000000000000000010000000") diff --git a/service/network/packet/testdata/fuzz/FuzzParseLayer3/f491862c9bd633a3 b/service/network/packet/testdata/fuzz/FuzzParseLayer3/f491862c9bd633a3 new file mode 100644 index 000000000..0c1d0a798 --- /dev/null +++ b/service/network/packet/testdata/fuzz/FuzzParseLayer3/f491862c9bd633a3 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("E00000\x00\x000\x1b00000000000100") diff --git a/service/network/pidhint_test.go b/service/network/pidhint_test.go index 6ba607935..52e1de0ed 100644 --- a/service/network/pidhint_test.go +++ b/service/network/pidhint_test.go @@ -25,7 +25,7 @@ func countPIDHints() int { return len(pidHints.cur) + len(pidHints.prev) } -func testPacketInfo(srcPort, dstPort uint16, pid int, inbound bool) packet.Info { +func testPacketInfo(srcPort uint16, pid int, inbound bool) packet.Info { return packet.Info{ Inbound: inbound, Version: packet.IPv4, @@ -33,7 +33,7 @@ func testPacketInfo(srcPort, dstPort uint16, pid int, inbound bool) packet.Info Src: net.IPv4(10, 0, 0, 1), SrcPort: srcPort, Dst: net.IPv4(93, 184, 216, 34), - DstPort: dstPort, + DstPort: 443, PID: pid, SeenAt: time.Now(), } @@ -55,7 +55,7 @@ func newTestRealPacket(info packet.Info) *testRealPacket { func TestPIDHintStoreAndTake(t *testing.T) { //nolint:paralleltest // Mutates package state. resetPIDHints() - pkt := packet.NewInfoPacket(testPacketInfo(10000, 443, 4242, false)) + pkt := packet.NewInfoPacket(testPacketInfo(10000, 4242, false)) SavePIDHint(pkt) pid, ok := takePIDHint(pkt.GetConnectionID()) @@ -75,7 +75,7 @@ func TestPIDHintStoreAndTake(t *testing.T) { //nolint:paralleltest // Mutates pa func TestPIDHintRotation(t *testing.T) { //nolint:paralleltest // Mutates package state. resetPIDHints() - pkt := packet.NewInfoPacket(testPacketInfo(10001, 443, 4243, false)) + pkt := packet.NewInfoPacket(testPacketInfo(10001, 4243, false)) SavePIDHint(pkt) // One rotation moves the hint to the previous generation, where it is still found. @@ -104,8 +104,8 @@ func TestPIDHintTakeRemovesBothGenerations(t *testing.T) { //nolint:paralleltest // The same connection reports a hint before and after a rotation, so both // generations hold an entry for it. - oldPkt := packet.NewInfoPacket(testPacketInfo(10002, 443, 4243, false)) - newPkt := packet.NewInfoPacket(testPacketInfo(10002, 443, 4244, false)) + oldPkt := packet.NewInfoPacket(testPacketInfo(10002, 4243, false)) + newPkt := packet.NewInfoPacket(testPacketInfo(10002, 4244, false)) SavePIDHint(oldPkt) pidHints.lock.Lock() rotatePIDHints() @@ -134,7 +134,7 @@ func TestPIDHintMaxEntries(t *testing.T) { //nolint:paralleltest // Mutates pack resetPIDHints() for i := range pidHintMaxEntries + 10 { - SavePIDHint(packet.NewInfoPacket(testPacketInfo(uint16(10000+i), 443, 1000+i, false))) //nolint:gosec // Test data. + SavePIDHint(packet.NewInfoPacket(testPacketInfo(uint16(10000+i), 1000+i, false))) //nolint:gosec // Test data. } if cnt := countPIDHints(); cnt > 2*pidHintMaxEntries { @@ -146,14 +146,14 @@ func TestPIDHintIgnoresUnusablePackets(t *testing.T) { //nolint:paralleltest // resetPIDHints() // Real packets must not create hints. - realPkt := newTestRealPacket(testPacketInfo(10100, 443, 4244, false)) + realPkt := newTestRealPacket(testPacketInfo(10100, 4244, false)) SavePIDHint(realPkt) if _, ok := takePIDHint(realPkt.GetConnectionID()); ok { t.Error("expected no pid hint for a real packet") } // Info-only packets without a pid have nothing to offer. - noPID := packet.NewInfoPacket(testPacketInfo(10101, 443, process.UndefinedProcessID, false)) + noPID := packet.NewInfoPacket(testPacketInfo(10101, process.UndefinedProcessID, false)) SavePIDHint(noPID) if _, ok := takePIDHint(noPID.GetConnectionID()); ok { t.Error("expected no pid hint for an info-only packet without a pid") @@ -164,7 +164,7 @@ func TestPIDHintSetsInfoOnlyPacketsActive(t *testing.T) { //nolint:paralleltest resetPIDHints() infoOnlyPacketsActive.UnSet() - SavePIDHint(packet.NewInfoPacket(testPacketInfo(10200, 443, 4245, false))) + SavePIDHint(packet.NewInfoPacket(testPacketInfo(10200, 4245, false))) if !infoOnlyPacketsActive.IsSet() { t.Error("expected info-only packets to be marked as active") @@ -173,7 +173,7 @@ func TestPIDHintSetsInfoOnlyPacketsActive(t *testing.T) { //nolint:paralleltest // The flag describes the transport, not the payload, so it is also set for // info-only packets that carry no usable pid. infoOnlyPacketsActive.UnSet() - SavePIDHint(packet.NewInfoPacket(testPacketInfo(10201, 443, process.UndefinedProcessID, false))) + SavePIDHint(packet.NewInfoPacket(testPacketInfo(10201, process.UndefinedProcessID, false))) if !infoOnlyPacketsActive.IsSet() { t.Error("expected info-only packets without a pid to be marked as active") @@ -190,26 +190,22 @@ func TestPIDHintConcurrency(t *testing.T) { //nolint:paralleltest // Mutates pac var wg sync.WaitGroup for worker := range 8 { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for i := range 500 { - pkt := packet.NewInfoPacket(testPacketInfo(uint16(20000+worker*500+i), 443, 5000+i, false)) //nolint:gosec // Test data. + pkt := packet.NewInfoPacket(testPacketInfo(uint16(20000+worker*500+i), 5000+i, false)) //nolint:gosec // Test data. SavePIDHint(pkt) _, _ = takePIDHint(pkt.GetConnectionID()) } - }() + }) } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for range 100 { pidHints.lock.Lock() rotatePIDHints() pidHints.lock.Unlock() } - }() + }) wg.Wait() } @@ -217,7 +213,7 @@ func TestPIDHintConcurrency(t *testing.T) { //nolint:paralleltest // Mutates pac func TestIncompleteConnectionAdoptsPIDHint(t *testing.T) { //nolint:paralleltest // Mutates package state. resetPIDHints() - info := testPacketInfo(10300, 443, 4246, false) + info := testPacketInfo(10300, 4246, false) SavePIDHint(packet.NewInfoPacket(info)) // The real packet does not know the pid. @@ -236,7 +232,7 @@ func TestIncompleteConnectionAdoptsPIDHint(t *testing.T) { //nolint:paralleltest func TestIncompleteConnectionKeepsPacketPID(t *testing.T) { //nolint:paralleltest // Mutates package state. resetPIDHints() - info := testPacketInfo(10400, 443, 4247, false) + info := testPacketInfo(10400, 4247, false) SavePIDHint(packet.NewInfoPacket(info)) // The real packet knows the pid itself and must not be overridden. @@ -256,7 +252,7 @@ func TestIncompleteConnectionKeepsPacketDirection(t *testing.T) { //nolint:paral resetPIDHints() // The eBPF listener only ever reports outbound connections. - outbound := testPacketInfo(10500, 443, 4249, false) + outbound := testPacketInfo(10500, 4249, false) SavePIDHint(packet.NewInfoPacket(outbound)) // The same connection, but intercepted on the inbound hook. The connection ID @@ -290,7 +286,7 @@ func TestInfoAndRealPacketShareConnectionID(t *testing.T) { for _, inbound := range []bool{false, true} { for _, protocol := range []packet.IPProtocol{packet.TCP, packet.UDP} { - info := testPacketInfo(10500, 443, 4248, inbound) + info := testPacketInfo(10500, 4248, inbound) info.Protocol = protocol infoPkt := packet.NewInfoPacket(info) diff --git a/service/network/proc/findpid.go b/service/network/proc/findpid.go index 8330a5494..2b5379058 100644 --- a/service/network/proc/findpid.go +++ b/service/network/proc/findpid.go @@ -6,6 +6,7 @@ import ( "errors" "io/fs" "os" + "slices" "strconv" "github.com/safing/portmaster/base/log" @@ -35,7 +36,9 @@ func GetPID(socketInfo socket.Info) (pid int) { // findPID returns the pid of the given uid and socket inode. func findPID(uid, inode int) (pid int) { - socketName := "socket:[" + strconv.Itoa(inode) + "]" + // Inodes are unsigned 32-bit values, but stored in an int. On 32-bit + // platforms, values above MaxInt32 wrap to negative, so format via uint32. + socketName := "socket:[" + strconv.FormatUint(uint64(uint32(inode)), 10) + "]" //nolint:gosec // Intentional truncation to the unsigned 32-bit inode, see comment above. // Always update pid table (it has a call limiter anyway) updatePids() @@ -65,10 +68,10 @@ func findPID(uid, inode int) (pid int) { result, _, _ := socketScans.Do(socketName, func() (any, error) { // Look through the PIDs in reverse order, because higher/newer PIDs will be more likely to // be searched for. - for j := len(pids) - 1; j >= 0; j-- { - if pidHasSocket(pids[j], socketName) { - cacheSocketOwner(uid, inode, pids[j]) - return pids[j], nil + for _, candidate := range slices.Backward(pids) { + if pidHasSocket(candidate, socketName) { + cacheSocketOwner(uid, inode, candidate) + return candidate, nil } } return socket.UndefinedProcessID, nil diff --git a/service/network/proc/findpid_test.go b/service/network/proc/findpid_test.go index 472ab7951..fbbd892cf 100644 --- a/service/network/proc/findpid_test.go +++ b/service/network/proc/findpid_test.go @@ -30,7 +30,8 @@ func TestFindPIDSharedSocket(t *testing.T) { //nolint:paralleltest // Uses the p defer func() { _ = file.Close() }() var stat syscall.Stat_t - if err := syscall.Fstat(int(file.Fd()), &stat); err != nil { + err = syscall.Fstat(int(file.Fd()), &stat) + if err != nil { t.Fatalf("failed to stat socket: %s", err) } uid := os.Getuid() @@ -43,11 +44,9 @@ func TestFindPIDSharedSocket(t *testing.T) { //nolint:paralleltest // Uses the p results := make([]int, lookups) var wg sync.WaitGroup for i := range lookups { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { results[i] = findPID(uid, inode) - }() + }) } wg.Wait() diff --git a/service/network/proc/tables.go b/service/network/proc/tables.go index 0fbfc79cd..1a6afa6e8 100644 --- a/service/network/proc/tables.go +++ b/service/network/proc/tables.go @@ -127,14 +127,14 @@ func getTableFromSource(stack uint8, procFile string) (connections []*socket.Con continue } - uid, err := strconv.ParseInt(fields[fieldIndexUID], 10, 32) + uid, err := strconv.ParseUint(fields[fieldIndexUID], 10, 32) // log.Tracef("uid: %s", fields[fieldIndexUID]) if err != nil { log.Warningf("proc: could not parse uid %s: %s", fields[11], err) continue } - inode, err := strconv.ParseInt(fields[fieldIndexInode], 10, 32) + inode, err := strconv.ParseUint(fields[fieldIndexInode], 10, 32) // log.Tracef("inode: %s", fields[fieldIndexInode]) if err != nil { log.Warningf("proc: could not parse inode %s: %s", fields[13], err) diff --git a/service/network/proc/tables_test.go b/service/network/proc/tables_test.go index 1a9f175e3..d282008e1 100644 --- a/service/network/proc/tables_test.go +++ b/service/network/proc/tables_test.go @@ -4,9 +4,42 @@ package proc import ( "fmt" + "os" + "path/filepath" "testing" ) +func TestGetTableFromSourceLargeInodeAndUID(t *testing.T) { + t.Parallel() + + // Linux inode numbers and UIDs are unsigned 32-bit values and may exceed + // the int32 range. + const header = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + content := header + + " 0: 0100007F:1F90 0100007F:C350 01 00000000:00000000 00:00000000 00000000 4294967294 0 3000000000 1 0000000000000000 100 0 0 10 0\n" + + " 1: 00000000:0050 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 4294967295 1 0000000000000000 100 0 0 10 0\n" + + path := filepath.Join(t.TempDir(), "tcp") + err := os.WriteFile(path, []byte(content), 0o600) + if err != nil { + t.Fatal(err) + } + + connections, listeners, err := getTableFromSource(TCP4, path) + if err != nil { + t.Fatal(err) + } + if len(connections) != 1 || len(listeners) != 1 { + t.Fatalf("expected 1 connection and 1 listener, got %d and %d", len(connections), len(listeners)) + } + if uid, inode := connections[0].GetUIDandInode(); uint32(uid) != 4294967294 || uint32(inode) != 3000000000 { //nolint:gosec // Intentionally checking the unsigned 32-bit values. + t.Errorf("connection: got uid=%d inode=%d", uint32(uid), uint32(inode)) //nolint:gosec // Intentionally printing the unsigned 32-bit values. + } + if _, inode := listeners[0].GetUIDandInode(); uint32(inode) != 4294967295 { //nolint:gosec // Intentionally checking the unsigned 32-bit value. + t.Errorf("listener: got inode=%d", uint32(inode)) //nolint:gosec // Intentionally printing the unsigned 32-bit value. + } +} + func TestSockets(t *testing.T) { t.Parallel() diff --git a/service/network/state/exists.go b/service/network/state/exists.go index cbe812393..1b55798ee 100644 --- a/service/network/state/exists.go +++ b/service/network/state/exists.go @@ -10,18 +10,27 @@ import ( const ( // UDPConnectionTTL defines the duration after which unseen UDP connections are regarded as ended. UDPConnectionTTL = 10 * time.Minute + + // existsMaxTCPTableAge defines the maximum age of the TCP tables used by + // Exists(). The connection cleaner checks all connections with the same + // now, so the first check of a cleaner run updates the tables and the + // other checks of the run reuse them. + existsMaxTCPTableAge = 1 * time.Second ) // Exists checks if the given connection is present in the system state tables. +// +// The tables are searched linearly. This is cheap compared to fetching the +// tables: 500 checks against tables with 2000 sockets each take about 0.5ms +// (BenchmarkExistsCleanerRun), so the connection cleaner does not need lookup +// maps for its checks. func Exists(pktInfo *packet.Info, now time.Time) (exists bool) { - // TODO: create lookup maps before running a flurry of Exists() checks. - switch { case pktInfo.Version == packet.IPv4 && pktInfo.Protocol == packet.TCP: - return tcp4Table.exists(pktInfo) + return tcp4Table.exists(pktInfo, now) case pktInfo.Version == packet.IPv6 && pktInfo.Protocol == packet.TCP: - return tcp6Table.exists(pktInfo) + return tcp6Table.exists(pktInfo, now) case pktInfo.Version == packet.IPv4 && pktInfo.Protocol == packet.UDP: return udp4Table.exists(pktInfo, now) @@ -34,9 +43,50 @@ func Exists(pktInfo *packet.Info, now time.Time) (exists bool) { } } -func (table *tcpTable) exists(pktInfo *packet.Info) (exists bool) { - // Update tables if older than the connection that is checked. - if table.lastUpdateAt.Load() < pktInfo.SeenAt.UnixNano() { +// UDPSocketExists checks if the local UDP socket of the given connection is +// still bound, regardless of when the connection was last looked up. +func UDPSocketExists(pktInfo *packet.Info) (exists bool) { + switch { + case pktInfo.Version == packet.IPv4 && pktInfo.Protocol == packet.UDP: + return udp4Table.findBindOrDualStack(pktInfo) != nil + + case pktInfo.Version == packet.IPv6 && pktInfo.Protocol == packet.UDP: + return udp6Table.findBindOrDualStack(pktInfo) != nil + + default: + return false + } +} + +func (table *tcpTable) exists(pktInfo *packet.Info, now time.Time) (exists bool) { + // Update the tables if they are older than the connection that is checked + // or older than the maximum age. Only lookups of new connections update + // the tables otherwise, so closed connections would never be noticed on a + // quiet system. + updateIfOlderThan := max( + pktInfo.SeenAt.UnixNano(), + now.Add(-existsMaxTCPTableAge).UnixNano(), + ) + + if table.existsInTable(pktInfo, updateIfOlderThan) { + return true + } + + // Lookups also check the dual-stack table, as IPv4 connections of + // dual-stack sockets are only listed there (with IPv4-mapped addresses). + if table.dualStack != nil { + return table.dualStack.existsInTable(pktInfo, updateIfOlderThan) + } + + return false +} + +func (table *tcpTable) existsInTable(pktInfo *packet.Info, updateIfOlderThan int64) (exists bool) { + // Update tables if older than the given time (unix nanoseconds). + // Use the time of the last fetch attempt, so that a failing fetch is not + // retried for every connection of a cleaner run. The last good tables are + // used instead until the next cleaner run. + if table.lastFetchAttemptAt.Load() < updateIfOlderThan { table.updateTables() } @@ -62,8 +112,40 @@ func (table *tcpTable) exists(pktInfo *packet.Info) (exists bool) { } func (table *udpTable) exists(pktInfo *packet.Info, now time.Time) (exists bool) { + socketInfo := table.findBindOrDualStack(pktInfo) + if socketInfo == nil { + return false + } + + udpConnState, ok := table.getConnState(socketInfo, socket.Address{ + IP: pktInfo.RemoteIP(), + Port: pktInfo.RemotePort(), + }) + if !ok { + return false + } + + return udpConnState.lastSeen.After(now.Add(-UDPConnectionTTL)) +} + +// findBindOrDualStack finds the socket of the given connection like lookups +// do: first in this table, then in the dual-stack table. Lookups store the +// connection state of sockets of the dual-stack table in this table. +func (table *udpTable) findBindOrDualStack(pktInfo *packet.Info) *socket.BindInfo { + socketInfo := table.findBind(pktInfo) + if socketInfo == nil && table.dualStack != nil { + socketInfo = table.dualStack.findBind(pktInfo) + } + return socketInfo +} + +// findBind returns the bind of the given connection, matching it the same way +// as lookups do. +func (table *udpTable) findBind(pktInfo *packet.Info) *socket.BindInfo { // Update tables if older than the connection that is checked. - if table.lastUpdateAt.Load() < pktInfo.SeenAt.UnixNano() { + // Use the time of the last fetch attempt, so that a failing fetch is not + // retried for every connection of a cleaner run. + if table.lastFetchAttemptAt.Load() < pktInfo.SeenAt.UnixNano() { table.updateTables() } @@ -72,31 +154,14 @@ func (table *udpTable) exists(pktInfo *packet.Info, now time.Time) (exists bool) localIP := pktInfo.LocalIP() localPort := pktInfo.LocalPort() - remoteIP := pktInfo.RemoteIP() - remotePort := pktInfo.RemotePort() - - connThreshhold := now.Add(-UDPConnectionTTL) // search binds for _, socketInfo := range table.binds { if localPort == socketInfo.Local.Port && - (socketInfo.Local.IP[0] == 0 || localIP.Equal(socketInfo.Local.IP)) { - - udpConnState, ok := table.getConnState(socketInfo, socket.Address{ - IP: remoteIP, - Port: remotePort, - }) - switch { - case !ok: - return false - case udpConnState.lastSeen.After(connThreshhold): - return true - default: - return false - } - + (socketInfo.ListensAny || localIP.Equal(socketInfo.Local.IP)) { + return socketInfo } } - return false + return nil } diff --git a/service/network/state/exists_fetch_error_test.go b/service/network/state/exists_fetch_error_test.go new file mode 100644 index 000000000..23d101e73 --- /dev/null +++ b/service/network/state/exists_fetch_error_test.go @@ -0,0 +1,169 @@ +package state + +import ( + "errors" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/safing/portmaster/base/utils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/socket" +) + +var errTestFetchFailed = errors.New("test: fetching the socket table failed") + +// testCleanerChecks is the number of Exists() checks of one cleaner run in +// the tests, as done by the cleaner for that many open connections. +const testCleanerChecks = 200 + +// newFailingTestTCPTable returns a TCP table that serves the given connections +// until failing is set, and counts the table fetches. +func newFailingTestTCPTable(connections []*socket.ConnectionInfo) (table *tcpTable, fetches *atomic.Int64, failing *atomic.Bool) { + fetches = new(atomic.Int64) + failing = new(atomic.Bool) + table = &tcpTable{ + version: 4, + fetchLimiter: utils.NewCallLimiter2(minDurationBetweenTableUpdates), + fetchTable: func() ([]*socket.ConnectionInfo, []*socket.BindInfo, error) { + fetches.Add(1) + if failing.Load() { + return nil, nil, errTestFetchFailed + } + return connections, nil, nil + }, + } + table.updateTables() + return table, fetches, failing +} + +// newFailingTestUDPTable returns a UDP table that serves the given binds +// until failing is set, and counts the table fetches. +func newFailingTestUDPTable(binds []*socket.BindInfo) (table *udpTable, fetches *atomic.Int64, failing *atomic.Bool) { + fetches = new(atomic.Int64) + failing = new(atomic.Bool) + table = &udpTable{ + version: 4, + fetchLimiter: utils.NewCallLimiter2(minDurationBetweenTableUpdates), + fetchTable: func() ([]*socket.BindInfo, error) { + fetches.Add(1) + if failing.Load() { + return nil, errTestFetchFailed + } + return binds, nil + }, + states: make(map[string]map[string]*udpState), + } + table.updateTables() + return table, fetches, failing +} + +func TestTCPExistsDoesNotRetryFailedFetchInCleanerRun(t *testing.T) { + t.Parallel() + + tcp4, fetches, failing := newFailingTestTCPTable([]*socket.ConnectionInfo{{ + Local: socket.Address{IP: testLocal4, Port: 40000}, + Remote: socket.Address{IP: testRemote4, Port: 443}, + }}) + pkt := cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40000, testRemote4, 443) + + // Next cleaner run: the tables are stale and fetching them fails. + failing.Store(true) + tick := waitForNextCleanerRun(tcp4) + start := fetches.Load() + began := time.Now() + for range testCleanerChecks { + // The connection is still reported from the last good table. + if !tcp4.exists(pkt, tick) { + t.Fatal("connection of the last good table reported as ended") + } + } + took := time.Since(began) + n := fetches.Load() - start + t.Logf("%d checks with a failing fetch: %d fetches in %s", testCleanerChecks, n, took) + if n != 1 { + t.Errorf("TCP table fetched %d times in one cleaner run with a failing fetch, want 1", n) + } + + // The next cleaner run tries again and picks up the recovered table. + failing.Store(false) + tick = waitForNextCleanerRun(tcp4) + start = fetches.Load() + if !tcp4.exists(pkt, tick) { + t.Fatal("connection reported as ended after the fetch recovered") + } + if n := fetches.Load() - start; n != 1 { + t.Errorf("TCP table fetched %d times in the cleaner run after the failure, want 1", n) + } +} + +func TestUDPExistsDoesNotRetryFailedFetchInCleanerRun(t *testing.T) { + t.Parallel() + + udp4, fetches, failing := newFailingTestUDPTable([]*socket.BindInfo{{ + Local: socket.Address{IP: net.IPv4zero, Port: 5353}, + PID: 4242, + }}) + // Make the table older than the connections, as when the connections + // started after the last good fetch. + udp4.lastUpdateAt.Add(-(2 * time.Minute).Nanoseconds()) + udp4.lastFetchAttemptAt.Add(-(2 * time.Minute).Nanoseconds()) + + failing.Store(true) + now := time.Now() + start := fetches.Load() + began := time.Now() + for i := range testCleanerChecks { + udp4.exists(cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, uint16(1000+i)), now) //nolint:gosec // Small test values. + } + took := time.Since(began) + n := fetches.Load() - start + t.Logf("%d checks with a failing fetch: %d fetches in %s", testCleanerChecks, n, took) + if n != 1 { + t.Errorf("UDP table fetched %d times in one cleaner run with a failing fetch, want 1", n) + } +} + +func TestLookupRetriesAfterFailedFetch(t *testing.T) { + t.Parallel() + + // A connection is opened after the last good fetch. + conn := &socket.ConnectionInfo{ + Local: socket.Address{IP: testLocal4, Port: 40000}, + Remote: socket.Address{IP: testRemote4, Port: 443}, + PID: 4242, // Set, so that CheckPID does not search /proc. + } + var osTable atomic.Pointer[[]*socket.ConnectionInfo] + osTable.Store(&[]*socket.ConnectionInfo{}) + failing := new(atomic.Bool) + tcp4 := &tcpTable{ + version: 4, + fetchLimiter: utils.NewCallLimiter2(minDurationBetweenTableUpdates), + fetchTable: func() ([]*socket.ConnectionInfo, []*socket.BindInfo, error) { + if failing.Load() { + return nil, nil, errTestFetchFailed + } + return *osTable.Load(), nil, nil + }, + } + tcp4.updateTables() + + pkt := cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40000, testRemote4, 443) + pkt.SeenAt = time.Now() + osTable.Store(&[]*socket.ConnectionInfo{conn}) + + // The cleaner runs and the fetch fails. + failing.Store(true) + tcp4.exists(pkt, time.Now()) + failing.Store(false) + + // A fast lookup of the new connection must still fetch the table again. + pid, _, err := tcp4.lookup(pkt, true) + if err != nil { + t.Fatalf("lookup after a failed fetch failed: %s", err) + } + if pid != 4242 { + t.Fatalf("lookup after a failed fetch returned pid %d, want 4242", pid) + } +} diff --git a/service/network/state/exists_refresh_test.go b/service/network/state/exists_refresh_test.go new file mode 100644 index 000000000..531199c1c --- /dev/null +++ b/service/network/state/exists_refresh_test.go @@ -0,0 +1,141 @@ +package state + +import ( + "sync/atomic" + "testing" + "time" + + "github.com/safing/portmaster/base/utils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/socket" +) + +// testCleanerTick is the interval of the connection cleaner +// (service/network/clean.go), which calls Exists(). +const testCleanerTick = 5 * time.Second + +// newMutableTestTCPTable returns a TCP table that serves the connections +// stored in osTable instead of reading them from the system, and counts the +// table fetches. +func newMutableTestTCPTable(version int, osTable *atomic.Pointer[[]*socket.ConnectionInfo]) (*tcpTable, *atomic.Int64) { + fetches := new(atomic.Int64) + table := &tcpTable{ + version: version, + fetchLimiter: utils.NewCallLimiter2(minDurationBetweenTableUpdates), + fetchTable: func() ([]*socket.ConnectionInfo, []*socket.BindInfo, error) { + fetches.Add(1) + return *osTable.Load(), nil, nil + }, + } + table.updateTables() + return table, fetches +} + +// waitForNextCleanerRun simulates the time passing until the next run of the +// connection cleaner by making the tables older, and returns the now of the +// next run. +func waitForNextCleanerRun(tables ...*tcpTable) (now time.Time) { + for _, table := range tables { + table.lastUpdateAt.Add(-testCleanerTick.Nanoseconds()) + table.lastFetchAttemptAt.Add(-testCleanerTick.Nanoseconds()) + } + return time.Now() +} + +func TestTCPExistsNoticesClosedConnection(t *testing.T) { + t.Parallel() + + // The connections started a minute ago, the tables were updated after + // that (by a lookup) and no lookups happen anymore (quiet system). + plain4Conn := &socket.ConnectionInfo{ + Local: socket.Address{IP: testLocal4, Port: 40000}, + Remote: socket.Address{IP: testRemote4, Port: 443}, + } + dualStackConn := &socket.ConnectionInfo{ + Local: socket.Address{IP: v4Mapped(testLocal4), Port: 40001}, + Remote: socket.Address{IP: v4Mapped(testRemote4), Port: 443}, + } + var os4, os6 atomic.Pointer[[]*socket.ConnectionInfo] + os4.Store(&[]*socket.ConnectionInfo{plain4Conn}) + os6.Store(&[]*socket.ConnectionInfo{dualStackConn}) + tcp4, fetches4 := newMutableTestTCPTable(4, &os4) + tcp6, fetches6 := newMutableTestTCPTable(6, &os6) + tcp4.dualStack = tcp6 + + plainPkt := cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40000, testRemote4, 443) + dualStackPkt := cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40001, testRemote4, 443) + closedPkt := cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40002, testRemote4, 443) + + // Next cleaner run: both connections are open. + tick := waitForNextCleanerRun(tcp4, tcp6) + if !tcp4.exists(plainPkt, tick) { + t.Fatal("open IPv4 connection reported as ended") + } + if !tcp4.exists(dualStackPkt, tick) { + t.Fatal("open IPv4 connection on dual-stack socket reported as ended") + } + + // Both connections are closed in the OS. + os4.Store(&[]*socket.ConnectionInfo{}) + os6.Store(&[]*socket.ConnectionInfo{}) + + // Next cleaner run: both connections must be reported as ended, and the + // tables must be updated once in the run, not once per check. + tick = waitForNextCleanerRun(tcp4, tcp6) + start4, start6 := fetches4.Load(), fetches6.Load() + if tcp4.exists(plainPkt, tick) { + t.Error("closed IPv4 connection still reported as existing") + } + if tcp4.exists(dualStackPkt, tick) { + t.Error("closed IPv4 connection on dual-stack socket still reported as existing") + } + for range 100 { + tcp4.exists(closedPkt, tick) + } + if n := fetches4.Load() - start4; n != 1 { + t.Errorf("TCP4 table fetched %d times in one cleaner run, want 1", n) + } + if n := fetches6.Load() - start6; n != 1 { + t.Errorf("TCP6 table fetched %d times in one cleaner run, want 1", n) + } +} + +// BenchmarkTableFetch measures one fetch of the system socket tables, as done +// by an update of a table. +func BenchmarkTableFetch(b *testing.B) { + tcpFetchers := map[string]func() ([]*socket.ConnectionInfo, []*socket.BindInfo, error){ + "TCP4": getTCP4Table, + "TCP6": getTCP6Table, + } + udpFetchers := map[string]func() ([]*socket.BindInfo, error){ + "UDP4": getUDP4Table, + "UDP6": getUDP6Table, + } + + for name, fetch := range tcpFetchers { + b.Run(name, func(b *testing.B) { + connections, listeners, err := fetch() + if err != nil { + b.Skipf("system table not available: %s", err) + } + b.ReportAllocs() + for b.Loop() { + _, _, _ = fetch() + } + b.ReportMetric(float64(len(connections)+len(listeners)), "sockets") + }) + } + for name, fetch := range udpFetchers { + b.Run(name, func(b *testing.B) { + binds, err := fetch() + if err != nil { + b.Skipf("system table not available: %s", err) + } + b.ReportAllocs() + for b.Loop() { + _, _ = fetch() + } + b.ReportMetric(float64(len(binds)), "sockets") + }) + } +} diff --git a/service/network/state/exists_test.go b/service/network/state/exists_test.go new file mode 100644 index 000000000..ab9eaf34a --- /dev/null +++ b/service/network/state/exists_test.go @@ -0,0 +1,340 @@ +package state + +import ( + "net" + "testing" + "time" + + "github.com/safing/portmaster/base/utils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/socket" +) + +// newTestTCPTable returns a TCP table that serves the given connections +// instead of reading them from the system. +func newTestTCPTable(version int, connections []*socket.ConnectionInfo) *tcpTable { + table := &tcpTable{ + version: version, + fetchLimiter: utils.NewCallLimiter2(minDurationBetweenTableUpdates), + fetchTable: func() ([]*socket.ConnectionInfo, []*socket.BindInfo, error) { + return connections, nil, nil + }, + } + table.updateTables() + return table +} + +// cleanerPacket returns a packet info as built by the connection cleaner +// (service/network/clean.go) to check if a connection still exists. +func cleanerPacket(version packet.IPVersion, protocol packet.IPProtocol, local net.IP, localPort uint16, remote net.IP, remotePort uint16) *packet.Info { + return &packet.Info{ + Inbound: false, // src == local + Version: version, + Protocol: protocol, + Src: local, + SrcPort: localPort, + Dst: remote, + DstPort: remotePort, + PID: socket.UndefinedProcessID, + // The cleaner uses the connection start time, so tables built by the + // test helpers are recent enough and are not updated again. + SeenAt: time.Now().Add(-time.Minute), + } +} + +var ( + testLocal4 = net.IPv4(192, 168, 1, 10).To4() + testRemote4 = net.IPv4(9, 9, 9, 9).To4() + testLocal6 = net.ParseIP("2001:db8::10") + testRemote6 = net.ParseIP("2001:db8::99") +) + +// v4Mapped returns the IPv4-mapped IPv6 address of the given IPv4 address, as +// it is read from /proc/net/{tcp,udp}6 for IPv4 traffic of dual-stack sockets. +func v4Mapped(ip net.IP) net.IP { + mapped := make(net.IP, net.IPv6len) + copy(mapped, net.IPv4(0, 0, 0, 0)) + copy(mapped[12:], ip.To4()) + return mapped +} + +func TestTCPExists(t *testing.T) { + t.Parallel() + + // IPv4 connection on a dual-stack (AF_INET6) socket: only listed in the + // TCP6 table, with IPv4-mapped addresses. + dualStackConn := &socket.ConnectionInfo{ + Local: socket.Address{IP: v4Mapped(testLocal4), Port: 40000}, + Remote: socket.Address{IP: v4Mapped(testRemote4), Port: 443}, + } + // Plain IPv4 connection, with addresses in 16 byte form as on Linux. + plain4Conn := &socket.ConnectionInfo{ + Local: socket.Address{IP: net.IPv4(192, 168, 1, 10), Port: 40001}, + Remote: socket.Address{IP: net.IPv4(9, 9, 9, 9), Port: 443}, + } + plain6Conn := &socket.ConnectionInfo{ + Local: socket.Address{IP: testLocal6, Port: 40002}, + Remote: socket.Address{IP: testRemote6, Port: 443}, + } + + tcp6 := newTestTCPTable(6, []*socket.ConnectionInfo{dualStackConn, plain6Conn}) + tcp4 := newTestTCPTable(4, []*socket.ConnectionInfo{plain4Conn}) + tcp4.dualStack = tcp6 + tcp4NoDualStack := newTestTCPTable(4, []*socket.ConnectionInfo{plain4Conn}) + + tests := []struct { + name string + table *tcpTable + pkt *packet.Info + want bool + }{ + { + name: "IPv4 on dual-stack socket", + table: tcp4, + pkt: cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40000, testRemote4, 443), + want: true, + }, + { + name: "IPv4 on dual-stack socket, dual-stack disabled", + table: tcp4NoDualStack, + pkt: cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40000, testRemote4, 443), + want: false, + }, + { + name: "IPv4", + table: tcp4, + pkt: cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40001, testRemote4, 443), + want: true, + }, + { + name: "IPv4, dual-stack disabled", + table: tcp4NoDualStack, + pkt: cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40001, testRemote4, 443), + want: true, + }, + { + name: "IPv4 closed", + table: tcp4, + pkt: cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40003, testRemote4, 443), + want: false, + }, + { + name: "IPv4 other remote port", + table: tcp4, + pkt: cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40000, testRemote4, 80), + want: false, + }, + { + name: "IPv6", + table: tcp6, + pkt: cleanerPacket(packet.IPv6, packet.TCP, testLocal6, 40002, testRemote6, 443), + want: true, + }, + { + name: "IPv6 closed", + table: tcp6, + pkt: cleanerPacket(packet.IPv6, packet.TCP, testLocal6, 40003, testRemote6, 443), + want: false, + }, + } + for _, tc := range tests { + if got := tc.table.exists(tc.pkt, time.Now()); got != tc.want { + t.Errorf("%s: exists() = %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestUDPExistsDualStack(t *testing.T) { + t.Parallel() + + udp4, udp6, _ := newDualStackTestTables() + now := time.Now() + + // Outbound IPv4 flow from the dual-stack [::]:5353 socket. + pkt := udp4TestPacket(false) + _, _, err := udp4.lookup(pkt, true) + if err != nil { + t.Fatalf("lookup failed: %s", err) + } + + check := cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 53) + if !udp4.exists(check, now) { + t.Fatal("IPv4 flow on open dual-stack socket reported as ended") + } + + // Flow that was never seen. + if udp4.exists(cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 54), now) { + t.Fatal("unseen flow on dual-stack socket reported as existing") + } + + // Flow that was not seen within the TTL. + if udp4.exists(check, now.Add(UDPConnectionTTL+time.Minute)) { + t.Fatal("expired flow on dual-stack socket reported as existing") + } + + // Close the dual-stack socket. + udp6.lock.Lock() + udp6.binds = nil + udp6.lock.Unlock() + if udp4.exists(check, now) { + t.Fatal("flow on closed dual-stack socket reported as existing") + } +} + +// TestUDPSocketExistsAfterFlowExpired checks the socket check that the +// cleaner uses for UDP flows whose packets are still seen: Exists() only knows +// the time the flow was last looked up, but the socket is still bound. +func TestUDPSocketExistsAfterFlowExpired(t *testing.T) { + t.Parallel() + + udp4, udp6, _ := newDualStackTestTables() + now := time.Now() + + // Outbound IPv4 flow from the dual-stack [::]:5353 socket, looked up for + // its first packet only. + _, _, err := udp4.lookup(udp4TestPacket(false), true) + if err != nil { + t.Fatalf("lookup failed: %s", err) + } + check := cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 53) + later := now.Add(UDPConnectionTTL + time.Minute) + + if udp4.exists(check, later) { + t.Fatal("flow not looked up within the TTL reported as existing") + } + if udp4.findBindOrDualStack(check) == nil { + t.Fatal("bound dual-stack socket of the flow not found") + } + if udp4.findBindOrDualStack(cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5354, testRemote4, 53)) != nil { + t.Fatal("socket found for a port that is not bound") + } + + // Close the dual-stack socket. + udp6.lock.Lock() + udp6.binds = nil + udp6.lock.Unlock() + if udp4.findBindOrDualStack(check) != nil { + t.Fatal("closed dual-stack socket of the flow found") + } +} + +func TestUDPExists(t *testing.T) { + t.Parallel() + + // IPv4 binds in 16 byte form, as on Linux: two binds on the same port. + udp4 := newTestUDPTable(4, []*socket.BindInfo{ + {Local: socket.Address{IP: net.IPv4(127, 0, 0, 1), Port: 5353}, PID: 1}, + {Local: socket.Address{IP: net.IPv4(192, 168, 1, 10), Port: 5353}, PID: 2}, + }) + udp6 := newTestUDPTable(6, []*socket.BindInfo{ + {Local: socket.Address{IP: testLocal6, Port: 5353}, PID: 3}, + }) + now := time.Now() + + // IPv4 + _, _, err := udp4.lookup(udp4TestPacket(false), true) + if err != nil { + t.Fatalf("IPv4 lookup failed: %s", err) + } + if !udp4.exists(cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 53), now) { + t.Error("open IPv4 flow reported as ended") + } + if udp4.exists(cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 54), now) { + t.Error("unseen IPv4 flow reported as existing") + } + if udp4.exists(cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5354, testRemote4, 53), now) { + t.Error("IPv4 flow without socket reported as existing") + } + + // IPv6 + pkt6 := &packet.Info{ + Version: packet.IPv6, + Protocol: packet.UDP, + Src: testLocal6, + SrcPort: 5353, + Dst: testRemote6, + DstPort: 53, + SeenAt: time.Now(), + } + _, _, err = udp6.lookup(pkt6, true) + if err != nil { + t.Fatalf("IPv6 lookup failed: %s", err) + } + if !udp6.exists(cleanerPacket(packet.IPv6, packet.UDP, testLocal6, 5353, testRemote6, 53), now) { + t.Error("open IPv6 flow reported as ended") + } + if udp6.exists(cleanerPacket(packet.IPv6, packet.UDP, testLocal6, 5353, testRemote6, 54), now) { + t.Error("unseen IPv6 flow reported as existing") + } + if udp6.exists(cleanerPacket(packet.IPv6, packet.UDP, testLocal6, 5353, testRemote6, 53), now.Add(UDPConnectionTTL+time.Minute)) { + t.Error("expired IPv6 flow reported as existing") + } +} + +func TestUDPExistsConcurrentWithLookup(t *testing.T) { + t.Parallel() + + udp4 := newTestUDPTable(4, []*socket.BindInfo{ + {Local: socket.Address{IP: net.IPv4(192, 168, 1, 10), Port: 5353}, PID: 1}, + }) + _, _, err := udp4.lookup(udp4TestPacket(false), true) + if err != nil { + t.Fatalf("lookup failed: %s", err) + } + check := cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 53) + + // Lookups update the last seen time of the state, while the cleaner + // reads it. Run with -race. + done := make(chan struct{}) + go func() { + defer close(done) + for range 100 { + _, _, _ = udp4.lookup(udp4TestPacket(true), true) + } + }() + for range 100 { + if !udp4.exists(check, time.Now()) { + t.Error("open flow reported as ended") + break + } + } + <-done +} + +func BenchmarkTCPExistsDualStack(b *testing.B) { + connections := make([]*socket.ConnectionInfo, 0, 100) + for i := range uint16(100) { + connections = append(connections, &socket.ConnectionInfo{ + Local: socket.Address{IP: v4Mapped(testLocal4), Port: 40000 + i}, + Remote: socket.Address{IP: v4Mapped(testRemote4), Port: 443}, + }) + } + tcp4 := newTestTCPTable(4, nil) + tcp4.dualStack = newTestTCPTable(6, connections) + pkt := cleanerPacket(packet.IPv4, packet.TCP, testLocal4, 40099, testRemote4, 443) + now := time.Now() + + b.ReportAllocs() + for b.Loop() { + if !tcp4.exists(pkt, now) { + b.Fatal("not found") + } + } +} + +func BenchmarkUDPExistsDualStack(b *testing.B) { + udp4 := newBenchUDPTables() + _, _, err := udp4.lookup(udp4TestPacket(false), true) + if err != nil { + b.Fatal(err) + } + pkt := cleanerPacket(packet.IPv4, packet.UDP, testLocal4, 5353, testRemote4, 53) + now := time.Now() + + b.ReportAllocs() + for b.Loop() { + if !udp4.exists(pkt, now) { + b.Fatal("not found") + } + } +} diff --git a/service/network/state/lookup.go b/service/network/state/lookup.go index f534e2c14..16f4b8ed5 100644 --- a/service/network/state/lookup.go +++ b/service/network/state/lookup.go @@ -28,6 +28,19 @@ var ( ErrPIDNotFound = errors.New("could not find pid for socket inode") ) +// The first try of a lookup always uses the current tables, whatever their age: +// - If they were fetched before the packet was seen, they usually still hold +// the socket (listeners, UDP sockets and connections that were looked up +// before), which saves fetching the tables for most packets. If they do +// not, the next try fetches them. +// - If they were fetched after the packet was seen (by the lookup of another +// packet while this one was waiting), they are as good as newly fetched +// ones. Fetching them again anyway made every packet of a burst of new +// connections wait for the pause between table updates. +// +// Note that the first case trusts tables of any age: a socket that was closed +// since, and whose local port (UDP, listeners) or address pair (TCP) is in use +// by another process now, is found first. Exists() does not use old tables. const ( lookupTries = 5 fastLookupTries = 2 // 1. current table, 2. get table with max 10ms, could be 0ms, 3. 10ms wait @@ -78,8 +91,8 @@ func (table *tcpTable) lookup(pktInfo *packet.Info, fast bool) ( // Search for the socket until found. for i := 1; i <= lookupTries; i++ { - // Use existing tables for first check if packet was seen after last table update. - if i == 1 && pktInfo.SeenAt.UnixNano() >= table.lastUpdateAt.Load() { + // Use the existing tables for the first check, see lookupTries. + if i == 1 { connections, listeners = table.getCurrentTables() } else { connections, listeners = table.updateTables() @@ -100,8 +113,8 @@ func (table *tcpTable) lookup(pktInfo *packet.Info, fast bool) ( continue } - // Use existing tables for first check if packet was seen after last table update. - if i == 1 && pktInfo.SeenAt.UnixNano() >= table.dualStack.lastUpdateAt.Load() { + // Use the existing tables for the first check, see lookupTries. + if i == 1 { dualStackConnections, dualStackListeners = table.dualStack.getCurrentTables() } else { dualStackConnections, dualStackListeners = table.dualStack.updateTables() @@ -178,8 +191,8 @@ func (table *udpTable) lookup(pktInfo *packet.Info, fast bool) ( // Search for the socket until found. for i := 1; i <= lookupTries; i++ { - // Get or update tables. - if i == 1 && pktInfo.SeenAt.UnixNano() >= table.lastUpdateAt.Load() { + // Use the existing tables for the first check, see lookupTries. + if i == 1 { binds = table.getCurrentTables() } else { binds = table.updateTables() @@ -211,8 +224,8 @@ func (table *udpTable) lookup(pktInfo *packet.Info, fast bool) ( continue } - // Get or update tables. - if i == 1 && pktInfo.SeenAt.UnixNano() >= table.lastUpdateAt.Load() { + // Use the existing tables for the first check, see lookupTries. + if i == 1 { dualStackBinds = table.dualStack.getCurrentTables() } else { dualStackBinds = table.dualStack.updateTables() diff --git a/service/network/state/lookup_bench_test.go b/service/network/state/lookup_bench_test.go new file mode 100644 index 000000000..a7bb43340 --- /dev/null +++ b/service/network/state/lookup_bench_test.go @@ -0,0 +1,115 @@ +package state + +import ( + "net" + "testing" + "time" + + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/socket" +) + +func newBenchUDPTables() (udp4 *udpTable) { + binds4 := make([]*socket.BindInfo, 0, 50) + binds6 := make([]*socket.BindInfo, 0, 51) + for i := range uint16(50) { + binds4 = append(binds4, &socket.BindInfo{ + Local: socket.Address{IP: net.IPv4(127, 0, 0, 1), Port: 40000 + i}, + PID: 1000, + }) + binds6 = append(binds6, &socket.BindInfo{ + Local: socket.Address{IP: net.IPv6loopback, Port: 41000 + i}, + PID: 1000, + }) + } + binds6 = append(binds6, &socket.BindInfo{ + Local: socket.Address{IP: net.IPv6zero, Port: 5353}, + PID: 4242, + }) + udp4 = newTestUDPTable(4, binds4) + udp4.dualStack = newTestUDPTable(6, binds6) + return udp4 +} + +func BenchmarkUDPLookupDualStack(b *testing.B) { + udp4 := newBenchUDPTables() + pkt := udp4TestPacket(false) + + b.ReportAllocs() + for b.Loop() { + _, _, err := udp4.lookup(pkt, true) + if err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkUDPGetDirection(b *testing.B) { + udp4 := newBenchUDPTables() + pkt := udp4TestPacket(false) + bind := &socket.BindInfo{Local: socket.Address{IP: net.IPv6zero, Port: 5353}} + + b.ReportAllocs() + for b.Loop() { + udp4.getDirection(bind, pkt) + } +} + +// BenchmarkExistsCleanerRun measures the Exists() checks of one cleaner run +// with 500 connections on a system with 2000 sockets per table. +func BenchmarkExistsCleanerRun(b *testing.B) { + const ( + sockets = 2000 + checks = 500 + ) + + connections := make([]*socket.ConnectionInfo, 0, sockets) + binds := make([]*socket.BindInfo, 0, sockets) + for i := range uint16(sockets) { + connections = append(connections, &socket.ConnectionInfo{ + Local: socket.Address{IP: net.IPv4(192, 168, 1, 10), Port: 30000 + i}, + Remote: socket.Address{IP: net.IPv4(9, 9, 9, 9), Port: 443}, + }) + binds = append(binds, &socket.BindInfo{ + Local: socket.Address{IP: net.IPv4(192, 168, 1, 10), Port: 30000 + i}, + }) + } + tcp4 := newTestTCPTable(4, connections) + udp4 := newTestUDPTable(4, binds) + // Use the time of the table update, so that the tables are not updated. + now := time.Now() + + // Check every fourth socket, so that the matches are spread over the + // tables, as the connections of the cleaner are. + tcpPkts := make([]*packet.Info, 0, checks) + udpPkts := make([]*packet.Info, 0, checks) + for i := range checks { + bind := binds[i*sockets/checks] + port := bind.Local.Port + tcpPkts = append(tcpPkts, cleanerPacket(packet.IPv4, packet.TCP, testLocal4, port, testRemote4, 443)) + udpPkt := cleanerPacket(packet.IPv4, packet.UDP, testLocal4, port, testRemote4, 443) + udpPkts = append(udpPkts, udpPkt) + udp4.getDirection(bind, udpPkt) + } + + b.Run("TCP", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, pkt := range tcpPkts { + if !tcp4.exists(pkt, now) { + b.Fatal("connection not found") + } + } + } + }) + b.Run("UDP", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, pkt := range udpPkts { + if !udp4.exists(pkt, now) { + b.Fatal("connection not found") + } + } + } + }) +} diff --git a/service/network/state/lookup_first_try_test.go b/service/network/state/lookup_first_try_test.go new file mode 100644 index 000000000..99a121f1e --- /dev/null +++ b/service/network/state/lookup_first_try_test.go @@ -0,0 +1,80 @@ +package state + +import ( + "net" + "testing" + "time" + + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/socket" +) + +// TestLookupFirstTryUsesTablesNewerThanPacket checks that a lookup does not +// fetch the tables from the system if the current tables hold the socket and +// were fetched after the packet was seen, eg. by the lookup of another packet +// of the same burst. Fetching waits for the pause between table updates. +func TestLookupFirstTryUsesTablesNewerThanPacket(t *testing.T) { + t.Parallel() + + local := net.IPv4(192, 168, 1, 10).To4() + remote := net.IPv4(9, 9, 9, 9).To4() + // The packet was seen before the tables are fetched below. + seenAt := time.Now().Add(-time.Millisecond) + + t.Run("udp", func(t *testing.T) { + t.Parallel() + + binds := []*socket.BindInfo{{ + Local: socket.Address{IP: local, Port: 5353}, + PID: 4242, // Set, so that CheckPID does not search /proc. + }} + table := newTestUDPTable(4, binds) + var fetches int + table.fetchTable = func() ([]*socket.BindInfo, error) { + fetches++ + return binds, nil + } + + pkt := udp4TestPacket(false) + pkt.SeenAt = seenAt + pid, _, err := table.lookup(pkt, true) + if err != nil || pid != 4242 { + t.Fatalf("unexpected lookup result: pid=%d err=%v", pid, err) + } + if fetches != 0 { + t.Errorf("table was fetched %d times, although it holds the socket and is newer than the packet", fetches) + } + }) + + t.Run("tcp", func(t *testing.T) { + t.Parallel() + + connections := []*socket.ConnectionInfo{{ + Local: socket.Address{IP: local, Port: 51234}, + Remote: socket.Address{IP: remote, Port: 443}, + PID: 4242, + }} + table := newTestTCPTable(4, connections) + var fetches int + table.fetchTable = func() ([]*socket.ConnectionInfo, []*socket.BindInfo, error) { + fetches++ + return connections, nil, nil + } + + pid, _, err := table.lookup(&packet.Info{ + Version: packet.IPv4, + Protocol: packet.TCP, + Src: local, + SrcPort: 51234, + Dst: remote, + DstPort: 443, + SeenAt: seenAt, + }, true) + if err != nil || pid != 4242 { + t.Fatalf("unexpected lookup result: pid=%d err=%v", pid, err) + } + if fetches != 0 { + t.Errorf("table was fetched %d times, although it holds the socket and is newer than the packet", fetches) + } + }) +} diff --git a/service/network/state/tcp.go b/service/network/state/tcp.go index e3883847f..ef522e00e 100644 --- a/service/network/state/tcp.go +++ b/service/network/state/tcp.go @@ -22,8 +22,14 @@ type tcpTable struct { listeners []*socket.BindInfo lock sync.RWMutex - // lastUpdateAt stores the time when the tables where last updated as unix nanoseconds. + // lastUpdateAt stores the time when the tables were last updated as unix nanoseconds. lastUpdateAt atomic.Int64 + // lastFetchAttemptAt stores the time of the last attempt to update the + // tables as unix nanoseconds, regardless of whether it succeeded. + // Exists() uses it, so that a failing fetch is not retried for every + // connection check. Lookups always fetch after their first try, so that + // they still retry. + lastFetchAttemptAt atomic.Int64 fetchLimiter *utils.CallLimiter2 fetchTable func() (connections []*socket.ConnectionInfo, listeners []*socket.BindInfo, err error) @@ -69,6 +75,8 @@ func (table *tcpTable) updateTables() ( table.fetchLimiter.Do(func() { // Fetch new tables from system. connections, listeners, err := table.fetchTable() + fetchedAt := time.Now().UnixNano() + defer table.lastFetchAttemptAt.Store(fetchedAt) if err != nil { log.Warningf("state: failed to get TCP%d socket table: %s", table.version, err) return @@ -84,7 +92,7 @@ func (table *tcpTable) updateTables() ( defer table.lock.Unlock() table.connections = connections table.listeners = listeners - table.lastUpdateAt.Store(time.Now().UnixNano()) + table.lastUpdateAt.Store(fetchedAt) }) return table.getCurrentTables() diff --git a/service/network/state/udp.go b/service/network/state/udp.go index 0dcecc84f..f320c28f6 100644 --- a/service/network/state/udp.go +++ b/service/network/state/udp.go @@ -21,8 +21,14 @@ type udpTable struct { binds []*socket.BindInfo lock sync.RWMutex - // lastUpdateAt stores the time when the tables where last updated as unix nanoseconds. + // lastUpdateAt stores the time when the tables were last updated as unix nanoseconds. lastUpdateAt atomic.Int64 + // lastFetchAttemptAt stores the time of the last attempt to update the + // tables as unix nanoseconds, regardless of whether it succeeded. + // Exists() uses it, so that a failing fetch is not retried for every + // connection check. Lookups always fetch after their first try, so that + // they still retry. + lastFetchAttemptAt atomic.Int64 fetchLimiter *utils.CallLimiter2 fetchTable func() (binds []*socket.BindInfo, err error) @@ -83,6 +89,8 @@ func (table *udpTable) updateTables() (binds []*socket.BindInfo) { table.fetchLimiter.Do(func() { // Fetch new tables from system. binds, err := table.fetchTable() + fetchedAt := time.Now().UnixNano() + defer table.lastFetchAttemptAt.Store(fetchedAt) if err != nil { log.Warningf("state: failed to get UDP%d socket table: %s", table.version, err) return @@ -97,7 +105,7 @@ func (table *udpTable) updateTables() (binds []*socket.BindInfo) { table.lock.Lock() defer table.lock.Unlock() table.binds = binds - table.lastUpdateAt.Store(time.Now().UnixNano()) + table.lastUpdateAt.Store(fetchedAt) }) return table.getCurrentTables() @@ -107,6 +115,11 @@ func (table *udpTable) updateTables() (binds []*socket.BindInfo) { func CleanUDPStates(_ context.Context) { now := time.Now().UTC() + // Update the dual-stack table before cleaning the UDP4 table, as the UDP4 + // table also holds the states of dual-stack sockets. + if udp4Table.dualStack != nil { + udp4Table.dualStack.updateTables() + } udp4Table.updateTables() udp4Table.cleanStates(now) @@ -116,20 +129,29 @@ func CleanUDPStates(_ context.Context) { } } +// getConnState returns a copy of the connection state, so that it can be +// used without holding the states lock. func (table *udpTable) getConnState( socketInfo *socket.BindInfo, remoteAddress socket.Address, -) (udpConnState *udpState, ok bool) { +) (udpConnState udpState, ok bool) { + // Build the keys in stack buffers, so that the lookup does not allocate. + var localKeyBuf, remoteKeyBuf [udpStateKeyBufSize]byte + localKey := appendUDPStateKey(localKeyBuf[:0], socketInfo.Local) + remoteKey := appendUDPStateKey(remoteKeyBuf[:0], remoteAddress) + table.statesLock.Lock() defer table.statesLock.Unlock() - bindMap, ok := table.states[makeUDPStateKey(socketInfo.Local)] - if ok { - udpConnState, ok = bindMap[makeUDPStateKey(remoteAddress)] - return + bindMap, ok := table.states[string(localKey)] + if !ok { + return udpState{}, false } - - return nil, false + state, ok := bindMap[string(remoteKey)] + if !ok { + return udpState{}, false + } + return *state, true } func (table *udpTable) getDirection( @@ -139,21 +161,24 @@ func (table *udpTable) getDirection( table.statesLock.Lock() defer table.statesLock.Unlock() - localKey := makeUDPStateKey(socketInfo.Local) + // Build the keys in stack buffers, so that looking up existing state does + // not allocate. Strings are only allocated when new state is stored. + var localKeyBuf, remoteKeyBuf [udpStateKeyBufSize]byte + localKey := appendUDPStateKey(localKeyBuf[:0], socketInfo.Local) - bindMap, ok := table.states[localKey] + bindMap, ok := table.states[string(localKey)] if !ok { bindMap = make(map[string]*udpState) - table.states[localKey] = bindMap + table.states[string(localKey)] = bindMap } - remoteKey := makeUDPStateKey(socket.Address{ + remoteKey := appendUDPStateKey(remoteKeyBuf[:0], socket.Address{ IP: pktInfo.RemoteIP(), Port: pktInfo.RemotePort(), }) - udpConnState, ok := bindMap[remoteKey] + udpConnState, ok := bindMap[string(remoteKey)] if !ok { - bindMap[remoteKey] = &udpState{ + bindMap[string(remoteKey)] = &udpState{ inbound: pktInfo.Inbound, lastSeen: time.Now().UTC(), } @@ -167,7 +192,7 @@ func (table *udpTable) getDirection( func (table *udpTable) cleanStates(now time.Time) { // compute thresholds threshold := now.Add(-UDPConnStateTTL) - shortThreshhold := now.Add(-UDPConnStateShortenedTTL) + shortThreshold := now.Add(-UDPConnStateShortenedTTL) // make lookup map of all active keys bindKeys := make(map[string]struct{}) @@ -176,6 +201,13 @@ func (table *udpTable) cleanStates(now time.Time) { bindKeys[makeUDPStateKey(socketInfo.Local)] = struct{}{} } table.lock.RUnlock() + // Lookups store the states of dual-stack sockets in this table, so the + // sockets of the dual-stack table are active too. + if table.dualStack != nil { + for _, socketInfo := range table.dualStack.getCurrentTables() { + bindKeys[makeUDPStateKey(socketInfo.Local)] = struct{}{} + } + } table.statesLock.Lock() defer table.statesLock.Unlock() @@ -192,7 +224,7 @@ func (table *udpTable) cleanStates(now time.Time) { // if there are too many clean more aggressively if len(bindMap) > AggressiveCleaningThreshold { for remoteKey, udpConnState := range bindMap { - if udpConnState.lastSeen.Before(shortThreshhold) { + if udpConnState.lastSeen.Before(shortThreshold) { delete(bindMap, remoteKey) } } @@ -204,7 +236,17 @@ func (table *udpTable) cleanStates(now time.Time) { } } +// udpStateKeyBufSize fits a 16 byte IP and a 5 digit port. +const udpStateKeyBufSize = 21 + func makeUDPStateKey(address socket.Address) string { + var buf [udpStateKeyBufSize]byte + return string(appendUDPStateKey(buf[:0], address)) +} + +// appendUDPStateKey appends the state key of the given address to buf. +func appendUDPStateKey(buf []byte, address socket.Address) []byte { // This could potentially go wrong, but as all IPs are created by the same source, everything should be fine. - return string(address.IP) + strconv.Itoa(int(address.Port)) + buf = append(buf, address.IP...) + return strconv.AppendUint(buf, uint64(address.Port), 10) } diff --git a/service/network/state/udp_test.go b/service/network/state/udp_test.go new file mode 100644 index 000000000..10c9f92e7 --- /dev/null +++ b/service/network/state/udp_test.go @@ -0,0 +1,191 @@ +package state + +import ( + "encoding/binary" + "net" + "strconv" + "testing" + "time" + + "github.com/safing/portmaster/base/utils" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/service/network/socket" +) + +// newTestUDPTable returns a UDP table that serves the given binds instead of +// reading them from the system. +func newTestUDPTable(version int, binds []*socket.BindInfo) *udpTable { + table := &udpTable{ + version: version, + fetchLimiter: utils.NewCallLimiter2(minDurationBetweenTableUpdates), + fetchTable: func() ([]*socket.BindInfo, error) { + return binds, nil + }, + states: make(map[string]map[string]*udpState), + } + table.updateTables() + return table +} + +// newDualStackTestTables models a host with IPv6 enabled: the UDP4 table has +// no sockets of its own and the UDP6 table, which is attached as the +// dual-stack table of the UDP4 table, holds a wildcard [::]:5353 socket that +// also receives IPv4 traffic. +func newDualStackTestTables() (udp4, udp6 *udpTable, dualStackBind *socket.BindInfo) { + dualStackBind = &socket.BindInfo{ + Local: socket.Address{IP: net.IPv6zero, Port: 5353}, + PID: 4242, // Set, so that CheckPID does not search /proc. + } + udp6 = newTestUDPTable(6, []*socket.BindInfo{dualStackBind}) + udp4 = newTestUDPTable(4, nil) + udp4.dualStack = udp6 + return udp4, udp6, dualStackBind +} + +func udp4TestPacket(inbound bool) *packet.Info { + local := net.IPv4(192, 168, 1, 10).To4() + remote := net.IPv4(9, 9, 9, 9).To4() + pkt := &packet.Info{ + Inbound: inbound, + Version: packet.IPv4, + Protocol: packet.UDP, + SeenAt: time.Now(), + } + if inbound { + pkt.Src, pkt.SrcPort, pkt.Dst, pkt.DstPort = remote, 53, local, 5353 + } else { + pkt.Src, pkt.SrcPort, pkt.Dst, pkt.DstPort = local, 5353, remote, 53 + } + return pkt +} + +func TestUDPDualStackDirectionSurvivesCleaning(t *testing.T) { + t.Parallel() + + udp4, _, _ := newDualStackTestTables() + + // First packet of the flow is outbound. + pid, inbound, err := udp4.lookup(udp4TestPacket(false), true) + if err != nil { + t.Fatalf("lookup of outbound packet failed: %s", err) + } + if pid != 4242 || inbound { + t.Fatalf("unexpected lookup result for outbound packet: pid=%d inbound=%v", pid, inbound) + } + + // The cleaner runs while the dual-stack socket is still open. + udp4.cleanStates(time.Now().UTC()) + + // The reply must still be attributed to the outbound flow. + _, inbound, err = udp4.lookup(udp4TestPacket(true), true) + if err != nil { + t.Fatalf("lookup of reply packet failed: %s", err) + } + if inbound { + t.Fatal("direction state of open dual-stack socket was cleaned: reply of outbound flow reported as inbound") + } +} + +func TestUDPDualStackStateRemovedWhenSocketClosed(t *testing.T) { + t.Parallel() + + udp4, udp6, _ := newDualStackTestTables() + + _, _, err := udp4.lookup(udp4TestPacket(false), true) + if err != nil { + t.Fatalf("lookup failed: %s", err) + } + if len(udp4.states) != 1 { + t.Fatalf("expected state for 1 socket, got %d", len(udp4.states)) + } + + // Close the dual-stack socket. + udp6.lock.Lock() + udp6.binds = nil + udp6.lock.Unlock() + + udp4.cleanStates(time.Now().UTC()) + if len(udp4.states) != 0 { + t.Fatalf("state of closed dual-stack socket was not removed: %d sockets left", len(udp4.states)) + } +} + +func TestUDPStateTTL(t *testing.T) { + t.Parallel() + + udp4, _, bind := newDualStackTestTables() + now := time.Now().UTC() + + // Add more than AggressiveCleaningThreshold remotes, half of them older + // than the shortened TTL, plus one older than the full TTL. + remotes := make(map[string]*udpState) + for i := range uint32(AggressiveCleaningThreshold + 10) { + lastSeen := now + if i%2 == 0 { + lastSeen = now.Add(-UDPConnStateShortenedTTL - time.Minute) + } + ip := make(net.IP, 4) + binary.BigEndian.PutUint32(ip, 0x0a000000+i) + remotes[makeUDPStateKey(socket.Address{IP: ip, Port: 53})] = &udpState{lastSeen: lastSeen} + } + remotes[makeUDPStateKey(socket.Address{IP: net.IPv4(10, 1, 0, 0).To4(), Port: 53})] = &udpState{lastSeen: now.Add(-UDPConnStateTTL - time.Minute)} + udp4.states[makeUDPStateKey(bind.Local)] = remotes + + udp4.cleanStates(now) + if got, want := len(remotes), (AggressiveCleaningThreshold+10)/2; got != want { + t.Fatalf("expected %d remaining remotes, got %d", want, got) + } +} + +func TestMakeUDPStateKey(t *testing.T) { + t.Parallel() + + for _, address := range []socket.Address{ + {IP: net.IPv4(192, 168, 1, 1), Port: 0}, + {IP: net.IPv4(192, 168, 1, 1).To4(), Port: 53}, + {IP: net.IPv6zero, Port: 5353}, + {IP: net.ParseIP("2001:db8::1"), Port: 65535}, + {IP: nil, Port: 1}, + } { + // Expected format: raw IP bytes followed by the decimal port. + want := string(address.IP) + strconv.Itoa(int(address.Port)) + got := makeUDPStateKey(address) + if got != want { + t.Errorf("makeUDPStateKey(%v) = %q, want %q", address, got, want) + } + } +} + +// TestUDPDualStackLookupUsesOwnTableAge checks that the first try of a lookup +// decides by the age of the dual-stack table itself whether it has to be +// updated, and not by the age of the UDP4 table. +func TestUDPDualStackLookupUsesOwnTableAge(t *testing.T) { + t.Parallel() + + udp4, udp6, _ := newDualStackTestTables() + + // Count the fetches of the dual-stack table and do not limit them. + var fetches int + binds := udp6.getCurrentTables() + udp6.fetchLimiter = utils.NewCallLimiter2(0) + udp6.fetchTable = func() ([]*socket.BindInfo, error) { + fetches++ + return binds, nil + } + + // The packet was seen after the dual-stack table was updated, but before + // the UDP4 table was. + pkt := udp4TestPacket(false) + udp4.lastUpdateAt.Store(pkt.SeenAt.Add(time.Second).UnixNano()) + + pid, _, err := udp4.lookup(pkt, true) + if err != nil { + t.Fatalf("lookup failed: %s", err) + } + if pid != 4242 { + t.Fatalf("unexpected pid %d", pid) + } + if fetches != 0 { + t.Fatalf("dual-stack table was fetched %d times, although it is newer than the packet", fetches) + } +} diff --git a/service/process/api.go b/service/process/api.go index f4f669233..e8535488c 100644 --- a/service/process/api.go +++ b/service/process/api.go @@ -2,7 +2,9 @@ package process import ( "errors" + "maps" "net/http" + "slices" "strconv" "github.com/safing/portmaster/base/api" @@ -70,7 +72,14 @@ func handleGetProcessesByProfile(ar *api.Request) (any, error) { } result := GetProcessesWithProfile(ar.Context(), profile.ProfileSource(source), id, true) - return result, nil + + // Return snapshots, as the result is encoded after returning, without + // holding the process locks. + snapshots := make([]*Process, 0, len(result)) + for _, p := range result { + snapshots = append(snapshots, p.snapshotForAPI()) + } + return snapshots, nil } func handleGetProcessGroupLeader(ar *api.Request) (any, error) { @@ -84,12 +93,64 @@ func handleGetProcessGroupLeader(ar *api.Request) (any, error) { return nil, api.ErrorWithStatus(err, http.StatusInternalServerError) } err = process.FindProcessGroupLeader(ar.Context()) + leader := process.Leader() switch { - case process.Leader() != nil: - return process.Leader(), nil + case leader != nil: + // Return a snapshot, as the result is encoded after returning, without + // holding the process lock. + return leader.snapshotForAPI(), nil case err != nil: return nil, api.ErrorWithStatus(err, http.StatusInternalServerError) default: return nil, api.ErrorWithStatus(errors.New("leader not found"), http.StatusNotFound) } } + +// snapshotForAPI returns a copy of the exported (serialized) attributes of +// the process, made while holding the process lock. Some of these attributes +// (eg. LastSeen, PrimaryProfileID) are changed under the process lock while +// the process is in use, so the live process must not be encoded by the API +// without holding its lock. +// The copy is only meant for encoding: it has no database key, metadata or +// profile and is not stored anywhere. +// Only the lock of this process is taken, no other locks are acquired while +// holding it. +func (p *Process) snapshotForAPI() *Process { + p.Lock() + defer p.Unlock() + + return &Process{ + Name: p.Name, + UserID: p.UserID, + UserName: p.UserName, + UserHome: p.UserHome, + + Pid: p.Pid, + CreatedAt: p.CreatedAt, + + ParentPid: p.ParentPid, + ParentCreatedAt: p.ParentCreatedAt, + + LeaderPid: p.LeaderPid, + + Path: p.Path, + ExecName: p.ExecName, + Cwd: p.Cwd, + CmdLine: p.CmdLine, + FirstArg: p.FirstArg, + Env: maps.Clone(p.Env), + + processKey: p.processKey, + + Tags: slices.Clone(p.Tags), + MatchingPath: p.MatchingPath, + + PrimaryProfileID: p.PrimaryProfileID, + + FirstSeen: p.FirstSeen, + LastSeen: p.LastSeen, + Error: p.Error, + + ExecHashes: maps.Clone(p.ExecHashes), + } +} diff --git a/service/process/api_race_test.go b/service/process/api_race_test.go new file mode 100644 index 000000000..3f8562e5d --- /dev/null +++ b/service/process/api_race_test.go @@ -0,0 +1,199 @@ +package process + +import ( + "bytes" + "net/http" + "net/http/httptest" + "reflect" + "sync" + "testing" + + "github.com/safing/portmaster/base/api" + "github.com/safing/portmaster/service/profile" + "github.com/safing/structures/dsd" +) + +const ( + apiTestProfileSource = profile.SourceLocal + apiTestProfileID = "api-race-test-profile" +) + +// newAPITestProcess returns a fully populated process that is stored in the +// process storage (and thus reachable from the API handlers), together with +// a function that removes it again. +func newAPITestProcess(t *testing.T) (*Process, func()) { + t.Helper() + + lp := profile.NewLayeredProfile(&profile.Profile{ + Source: apiTestProfileSource, + ID: apiTestProfileID, + }) + + p := &Process{ + Name: "test", + UserID: 1000, + UserName: "user", + UserHome: "/home/user", + Pid: 4242, + CreatedAt: 1700000000000, + ParentPid: 1, + ParentCreatedAt: 1600000000000, + LeaderPid: 4242, + Path: "/usr/bin/test", + ExecName: "test", + Cwd: "/tmp", + CmdLine: "/usr/bin/test --flag", + FirstArg: "/usr/bin/test", + Env: map[string]string{"HOME": "/home/user", "LANG": "C"}, + processKey: "4242-1700000000000", + Tags: []profile.Tag{{Key: "k", Value: "v"}}, + MatchingPath: "/usr/bin/test-alt", + FirstSeen: 1700000001, + LastSeen: 1700000002, + Error: "some error", + ExecHashes: map[string]string{"sha256": "abcd"}, + } + p.setProfile(profile.MakeScopedID(apiTestProfileSource, apiTestProfileID), lp) + + processesLock.Lock() + processes[p.processKey] = p + processesLock.Unlock() + + return p, func() { + processesLock.Lock() + delete(processes, p.processKey) + processesLock.Unlock() + } +} + +func newProcessesByProfileRequest() *api.Request { + return &api.Request{ + Request: httptest.NewRequest(http.MethodGet, "/api/v1/process/list/by-profile/local/"+apiTestProfileID, nil), + URLVars: map[string]string{ + "source": string(apiTestProfileSource), + "id": apiTestProfileID, + }, + } +} + +// TestHandleGetProcessesByProfileRace checks that the processes returned by +// the API handler can be encoded (as the API endpoint does after the handler +// returns, without any lock) while the process is mutated under its lock, as +// CleanProcessStorage (SetLastSeen) and RefetchProfile (setProfile) do. +// Run with -race. +func TestHandleGetProcessesByProfileRace(t *testing.T) { //nolint:paralleltest // Modifies the global process storage. + p, cleanup := newAPITestProcess(t) + defer cleanup() + lp := p.Profile() + + const rounds = 200 + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + for i := int64(0); ; i++ { + select { + case <-stop: + return + default: + } + // Same write patterns as CleanProcessStorage and RefetchProfile. + p.SetLastSeen(i) + p.Lock() + p.setProfile(profile.MakeScopedID(apiTestProfileSource, apiTestProfileID), lp) + p.Unlock() + } + }) + + for range rounds { + // Same as the endpoint: call the StructFunc, then encode the result. + v, err := handleGetProcessesByProfile(newProcessesByProfileRequest()) + if err != nil { + t.Fatal(err) + } + _, _, _, err = dsd.MimeDump(v, "application/json") + if err != nil { + t.Fatal(err) + } + } + close(stop) + wg.Wait() +} + +// TestProcessAPIOutputUnchanged checks that the API handler returns exactly +// the same encoded data as encoding the live process directly did. +func TestProcessAPIOutputUnchanged(t *testing.T) { //nolint:paralleltest // Modifies the global process storage. + p, cleanup := newAPITestProcess(t) + defer cleanup() + + // Make sure the test process has all serialized fields set, so that a field + // missing from the snapshot changes the output. + pv := reflect.ValueOf(p).Elem() + for i := range pv.NumField() { + f := pv.Type().Field(i) + if f.IsExported() && !f.Anonymous && pv.Field(i).IsZero() { + t.Fatalf("test process must set field %s", f.Name) + } + } + + formats := []string{"application/json", "application/yaml", "application/cbor", "application/msgpack"} + for _, accept := range formats { + // Encoded output of the live process, as previously returned by the handler. + p.Lock() + want, _, format, err := dsd.MimeDump([]*Process{p}, accept) + p.Unlock() + if err != nil { + t.Fatalf("%s: %s", accept, err) + } + + v, err := handleGetProcessesByProfile(newProcessesByProfileRequest()) + if err != nil { + t.Fatal(err) + } + got, _, _, err := dsd.MimeDump(v, accept) + if err != nil { + t.Fatalf("%s: %s", accept, err) + } + assertSameEncoding(t, accept, format, want, got) + + // Single process, as returned by the group leader handler. + p.Lock() + want, _, _, err = dsd.MimeDump(p, accept) + p.Unlock() + if err != nil { + t.Fatalf("%s: %s", accept, err) + } + got, _, _, err = dsd.MimeDump(p.snapshotForAPI(), accept) + if err != nil { + t.Fatalf("%s: %s", accept, err) + } + assertSameEncoding(t, accept, format, want, got) + } +} + +// assertSameEncoding checks that want and got are the same encoded data. +// CBOR and msgpack encode maps in random order, so their output is compared +// after decoding it. +func assertSameEncoding(t *testing.T, accept string, format uint8, want, got []byte) { + t.Helper() + + if bytes.Equal(want, got) { + return + } + if format == dsd.JSON || format == dsd.YAML { + t.Errorf("%s: output changed:\nwant: %s\ngot: %s", accept, want, got) + return + } + + var wantV, gotV any + err := dsd.LoadAsFormat(want, format, &wantV) + if err != nil { + t.Fatalf("%s: %s", accept, err) + } + err = dsd.LoadAsFormat(got, format, &gotV) + if err != nil { + t.Fatalf("%s: %s", accept, err) + } + if !reflect.DeepEqual(wantV, gotV) { + t.Errorf("%s: output changed:\nwant: %v\ngot: %v", accept, wantV, gotV) + } +} diff --git a/service/process/createtime_linux.go b/service/process/createtime_linux.go new file mode 100644 index 000000000..0bb5479d5 --- /dev/null +++ b/service/process/createtime_linux.go @@ -0,0 +1,127 @@ +package process + +import ( + "bytes" + "context" + "os" + "strconv" + + "github.com/shirou/gopsutil/host" + processInfo "github.com/shirou/gopsutil/process" + "golang.org/x/sys/unix" +) + +// fastCreateTime returns the creation time of the process with the given PID +// exactly as gopsutil's Process.CreateTime computes it, but much cheaper. +// +// gopsutil computes the creation time from the start time in /proc//stat +// and the boot time, which it reads from the btime line of /proc/stat on every +// call. The kernel generates all of /proc/stat (including the counters of +// every CPU and interrupt) for each read, which makes up most of the cost of +// looking up the process of a connection. Here, the boot time is computed +// from the clocks the kernel derives btime from instead. +// +// If ok is false, the fast path cannot be used and the caller must use +// gopsutil. +func fastCreateTime(ctx context.Context, pid int32) (createdAt int64, ok bool) { + // gopsutil reads from HOST_PROC, if set, and computes the boot time + // differently in containers. + if os.Getenv("HOST_PROC") != "" { + return 0, false + } + system, role, err := host.VirtualizationWithContext(ctx) // Cached by gopsutil. + if err != nil || role == "guest" && (system == "lxc" || system == "docker") { + return 0, false + } + + startTicks, ok := readStartTicks(pid) + if !ok { + return 0, false + } + bootTime, ok := bootTimeFromClocks() + if !ok { + return 0, false + } + + // Same computation as gopsutil. + ctime := (startTicks / uint64(processInfo.ClockTicks)) + bootTime //nolint:gosec // Same conversion as gopsutil. + return int64(ctime * 1000), true //nolint:gosec // Same conversion as gopsutil. +} + +// readStartTicks returns the start time of the process in clock ticks after +// boot (field 22 of /proc//stat). +func readStartTicks(pid int32) (uint64, bool) { + contents, err := os.ReadFile("/proc/" + strconv.Itoa(int(pid)) + "/stat") + if err != nil { + return 0, false + } + + // The process name (field 2) is in parentheses and may contain spaces and + // parentheses: Continue after the last closing parenthesis, as gopsutil does. + nameEnd := bytes.LastIndexByte(contents, ')') + if nameEnd < 0 || nameEnd+2 > len(contents) { + return 0, false + } + rest := contents[nameEnd+2:] + + // The rest starts with field 3: Find field 22. + const startTimeIndex = 22 - 3 + var index int + for { + // Skip whitespace. + for len(rest) > 0 && isStatSpace(rest[0]) { + rest = rest[1:] + } + if len(rest) == 0 { + return 0, false + } + // Find end of field. + end := 0 + for end < len(rest) && !isStatSpace(rest[end]) { + end++ + } + if index == startTimeIndex { + startTicks, err := strconv.ParseUint(string(rest[:end]), 10, 64) + if err != nil { + return 0, false + } + return startTicks, true + } + rest = rest[end:] + index++ + } +} + +func isStatSpace(c byte) bool { + switch c { + case ' ', '\t', '\n', '\v', '\f', '\r': + return true + default: + return false + } +} + +// bootTimeFromClocks returns the boot time in seconds since the epoch, like +// the btime line of /proc/stat. +// +// The kernel computes btime as the difference of CLOCK_REALTIME and +// CLOCK_BOOTTIME (in the time namespace of the reader), truncated to seconds. +// The two clocks cannot be read at the same instant, so the realtime clock is +// read between two reads of the boottime clock, which brackets the exact +// difference. If the bracket spans a full second, the result is ambiguous and +// ok is false. +func bootTimeFromClocks() (bootTime uint64, ok bool) { + var boot1, realtime, boot2 unix.Timespec + if unix.ClockGettime(unix.CLOCK_BOOTTIME, &boot1) != nil || + unix.ClockGettime(unix.CLOCK_REALTIME, &realtime) != nil || + unix.ClockGettime(unix.CLOCK_BOOTTIME, &boot2) != nil { + return 0, false + } + + upper := realtime.Nano() - boot1.Nano() + lower := realtime.Nano() - boot2.Nano() + if lower <= 0 || lower/1e9 != upper/1e9 { + return 0, false + } + return uint64(lower / 1e9), true //nolint:gosec // Checked to be positive. +} diff --git a/service/process/createtime_linux_test.go b/service/process/createtime_linux_test.go new file mode 100644 index 000000000..0b688fc68 --- /dev/null +++ b/service/process/createtime_linux_test.go @@ -0,0 +1,102 @@ +package process + +import ( + "bufio" + "context" + "os" + "strconv" + "strings" + "testing" + + processInfo "github.com/shirou/gopsutil/process" +) + +func TestBootTimeFromClocks(t *testing.T) { + t.Parallel() + + f, err := os.Open("/proc/stat") + if err != nil { + t.Skip(err) + } + defer func() { _ = f.Close() }() + var btime uint64 + scanner := bufio.NewScanner(f) + scanner.Buffer(nil, 1<<20) + for scanner.Scan() { + if value, ok := strings.CutPrefix(scanner.Text(), "btime "); ok { + btime, err = strconv.ParseUint(value, 10, 64) + if err != nil { + t.Fatal(err) + } + } + } + if btime == 0 { + t.Skip("no btime in /proc/stat") + } + + bootTime, ok := bootTimeFromClocks() + if !ok { + // Only fails if the bracket spans a second boundary, which is very + // unlikely: Try again. + bootTime, ok = bootTimeFromClocks() + } + if !ok { + t.Fatal("failed to get boot time from clocks") + } + if bootTime != btime { + t.Fatalf("boot time %d differs from btime %d", bootTime, btime) + } +} + +func TestFastCreateTime(t *testing.T) { + t.Parallel() + + ctx := context.Background() + entries, err := os.ReadDir("/proc") + if err != nil { + t.Skip(err) + } + var checked int + for _, entry := range entries { + pid, err := strconv.ParseInt(entry.Name(), 10, 32) + if err != nil { + continue + } + pInfo, err := processInfo.NewProcessWithContext(ctx, int32(pid)) + if err != nil { + continue // Exited. + } + want, err := pInfo.CreateTimeWithContext(ctx) + if err != nil { + continue + } + got, ok := fastCreateTime(ctx, int32(pid)) + if !ok { + _, err = os.Stat("/proc/" + entry.Name()) + if err != nil { + continue // Exited. + } + t.Fatalf("fast create time failed for pid %d", pid) + } + if got != want { + t.Fatalf("create time of pid %d: got %d, want %d", pid, got, want) + } + checked++ + } + if checked == 0 { + t.Skip("no processes checked") + } + t.Logf("checked %d processes", checked) +} + +func TestReadStartTicks(t *testing.T) { + t.Parallel() + + if _, ok := readStartTicks(-1); ok { + t.Fatal("expected failure for invalid pid") + } + ownPID := int32(os.Getpid()) //nolint:gosec // PIDs fit into int32. + if _, ok := readStartTicks(ownPID); !ok { + t.Fatal("failed to read start ticks of own process") + } +} diff --git a/service/process/createtime_other.go b/service/process/createtime_other.go new file mode 100644 index 000000000..f7828ed70 --- /dev/null +++ b/service/process/createtime_other.go @@ -0,0 +1,11 @@ +//go:build !linux + +package process + +import "context" + +// fastCreateTime is only implemented on Linux: Getting the creation time is +// cheap on other platforms. +func fastCreateTime(_ context.Context, _ int32) (createdAt int64, ok bool) { + return 0, false +} diff --git a/service/process/database.go b/service/process/database.go index 689a3faed..35bed5176 100644 --- a/service/process/database.go +++ b/service/process/database.go @@ -58,7 +58,7 @@ func GetProcessesWithProfile(ctx context.Context, profileSource profile.ProfileS // Get all processes that match the given profile. procs := make([]*Process, 0, 8) for _, p := range All() { - lp := p.profile.LocalProfile() + lp := p.Profile().LocalProfile() if lp != nil && lp.Source == profileSource && lp.ID == profileID { if preferProcessGroupLeader && p.Leader() != nil { procs = append(procs, p.Leader()) @@ -147,14 +147,14 @@ func CleanProcessStorage(activePIDs map[int]struct{}) { // Check if this is a special process. switch p.Pid { case UnidentifiedProcessID, UnsolicitedProcessID, SystemProcessID: - p.profile.MarkStillActive() + p.Profile().MarkStillActive() continue } // Check if process is active. _, active := activePIDs[p.Pid] if active { - p.profile.MarkStillActive() + p.Profile().MarkStillActive() continue } diff --git a/service/process/executable.go b/service/process/executable.go deleted file mode 100644 index 107d91da3..000000000 --- a/service/process/executable.go +++ /dev/null @@ -1,45 +0,0 @@ -package process - -import ( - "crypto" - "encoding/hex" - "hash" - "io" - "os" -) - -// GetExecHash returns the hash of the executable with the given algorithm. -func (p *Process) GetExecHash(algorithm string) (string, error) { - sum, ok := p.ExecHashes[algorithm] - if ok { - return sum, nil - } - - var hasher hash.Hash - switch algorithm { - case "md5": - hasher = crypto.MD5.New() - case "sha1": - hasher = crypto.SHA1.New() - case "sha256": - hasher = crypto.SHA256.New() - } - - file, err := os.Open(p.Path) - if err != nil { - return "", err - } - - defer func() { - _ = file.Close() - }() - - _, err = io.Copy(hasher, file) - if err != nil { - return "", err - } - - sum = hex.EncodeToString(hasher.Sum(nil)) - p.ExecHashes[algorithm] = sum - return sum, nil -} diff --git a/service/process/find.go b/service/process/find.go index a94acedc0..68ec2def6 100644 --- a/service/process/find.go +++ b/service/process/find.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net" + "net/http" "time" "github.com/safing/portmaster/base/api" @@ -126,8 +127,7 @@ func GetNetworkHost(ctx context.Context, remoteIP net.IP) (process *Process, err } // Assign profile to process. - networkHost.PrimaryProfileID = networkHostProfile.ScopedID() - networkHost.profile = networkHostProfile.LayeredProfile() + networkHost.setProfile(networkHostProfile.ScopedID(), networkHostProfile.LayeredProfile()) return networkHost, nil } @@ -148,6 +148,18 @@ func GetProcessByRequestOrigin(ar *api.Request) (*Process, error) { SrcPort: remotePort, // source as in the process we are looking for PID: UndefinedProcessID, } + if remoteIP.To4() == nil { + pkt.Version = packet.IPv6 + } + // The socket lookup also matches the other end of the connection: the + // local address of the API server that received the request. + if localAddr, ok := ar.Context().Value(http.LocalAddrContextKey).(net.Addr); ok { + localIP, localPort, err := netutils.ParseIPPort(localAddr.String()) + if err == nil { + pkt.Dst = localIP + pkt.DstPort = localPort + } + } pid, _, err := GetPidOfConnection(ar.Context(), pkt) if err != nil { diff --git a/service/process/find_bench_test.go b/service/process/find_bench_test.go new file mode 100644 index 000000000..40fbea423 --- /dev/null +++ b/service/process/find_bench_test.go @@ -0,0 +1,38 @@ +package process + +import ( + "context" + "os" + "testing" + + "github.com/safing/portmaster/service/profile" +) + +// BenchmarkGetProcessWithProfile measures the process attribution of a new +// connection of a process that is already known and has a profile, which is +// the case for almost all connections. +func BenchmarkGetProcessWithProfile(b *testing.B) { + enableProcessDetection = func() bool { return true } + ctx := context.Background() + pid := os.Getpid() + + // Load the process once, as the first connection of a process does. + proc, err := GetOrFindProcess(ctx, pid) + if err != nil { + b.Fatal(err) + } + proc.Lock() + proc.setProfile("local/bench", &profile.LayeredProfile{}) + proc.Unlock() + + b.ReportAllocs() + for b.Loop() { + p, err := GetProcessWithProfile(ctx, pid) + if err != nil { + b.Fatal(err) + } + if p != proc { + b.Fatal("unexpected process") + } + } +} diff --git a/service/process/module.go b/service/process/module.go index 797c21e35..33948c337 100644 --- a/service/process/module.go +++ b/service/process/module.go @@ -2,8 +2,11 @@ package process import ( "errors" + "path/filepath" "runtime" + "sync" "sync/atomic" + "time" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/mgr" @@ -14,7 +17,10 @@ type ProcessModule struct { mgr *mgr.Manager instance instance - portmasterUIPath string + // uiPathLock guards uiPath and uiPathChecked. + uiPathLock sync.Mutex + uiPath string + uiPathChecked time.Time } func (pm *ProcessModule) Manager() *mgr.Manager { @@ -22,22 +28,51 @@ func (pm *ProcessModule) Manager() *mgr.Manager { } func (pm *ProcessModule) Start() error { + if pm.portmasterUIPath() == "" { + // Installations without the UI, like servers, are fine. + log.Infof("process: the Portmaster UI is not installed (yet)") + } + return nil +} + +func (pm *ProcessModule) Stop() error { + return nil +} + +// uiPathRecheckInterval is how often the path of the UI is looked up again +// while the UI is not installed. +const uiPathRecheckInterval = 10 * time.Second + +// portmasterUIPath returns the real path of the Portmaster UI binary, or an +// empty string if it is not installed. The path is looked up again +// later if the UI is missing, as the updater may install it after start. +func (pm *ProcessModule) portmasterUIPath() string { + pm.uiPathLock.Lock() + defer pm.uiPathLock.Unlock() + + if pm.uiPath != "" || time.Since(pm.uiPathChecked) < uiPathRecheckInterval { + return pm.uiPath + } + pm.uiPathChecked = time.Now() + identifier := "portmaster" if runtime.GOOS == "windows" { identifier += ".exe" } - file, err := pm.instance.BinaryUpdates().GetFile(identifier) if err != nil { - log.Errorf("process: failed to get path of ui: %s", err) - } else { - pm.portmasterUIPath = file.Path() + log.Debugf("process: failed to get path of ui: %s", err) + return "" } - return nil -} -func (pm *ProcessModule) Stop() error { - return nil + // Processes are compared by their real path. + path := file.Path() + realPath, err := filepath.EvalSymlinks(path) + if err == nil { + path = realPath + } + pm.uiPath = path + return path } func prep() error { diff --git a/service/process/primary_profile_id_race_test.go b/service/process/primary_profile_id_race_test.go new file mode 100644 index 000000000..5904f6e6f --- /dev/null +++ b/service/process/primary_profile_id_race_test.go @@ -0,0 +1,70 @@ +package process + +import ( + "sync" + "testing" + + "github.com/safing/portmaster/service/profile" +) + +// TestPrimaryProfileIDConcurrentReassign checks that IsSystemResolver and +// GetPrimaryProfileID are safe to call while the profile is being (re)assigned +// through setProfile, the write path shared by GetProfile, RefetchProfile and +// GetNetworkHost. RefetchProfile reassigns the profile of a process that is +// shared by all of its connections (network.reAttributeConnection), while the +// firewall calls IsSystemResolver on other connections of the same process +// without holding the process lock. +func TestPrimaryProfileIDConcurrentReassign(t *testing.T) { + t.Parallel() + + p := &Process{} + a := &profile.LayeredProfile{} + b := &profile.LayeredProfile{} + const otherID = "local/other" + + const rounds = 1000 + var wg sync.WaitGroup + wg.Go(func() { + for i := range rounds { + id, lp := systemResolverScopedID, a + if i%2 == 1 { + id, lp = otherID, b + } + // Same write pattern as GetProfile/RefetchProfile. + p.Lock() + p.setProfile(id, lp) + p.Unlock() + } + }) + + for range rounds { + _ = p.IsSystemResolver() + if id := p.GetPrimaryProfileID(); id != "" && id != systemResolverScopedID && id != otherID { + t.Errorf("unexpected primary profile ID %q", id) + break + } + } + wg.Wait() + + // The exported (serialized) field and the accessor must agree. + p.Lock() + defer p.Unlock() + if p.PrimaryProfileID != p.GetPrimaryProfileID() { + t.Fatalf("field %q and accessor %q disagree", p.PrimaryProfileID, p.GetPrimaryProfileID()) + } +} + +// TestPrimaryProfileIDZeroValue checks the accessors on processes without a +// profile and on nil processes. +func TestPrimaryProfileIDZeroValue(t *testing.T) { + t.Parallel() + + var nilProc *Process + if nilProc.GetPrimaryProfileID() != "" || nilProc.IsSystemResolver() { + t.Fatal("nil process must have no primary profile ID") + } + p := &Process{} + if p.GetPrimaryProfileID() != "" || p.IsSystemResolver() { + t.Fatal("process without profile must have no primary profile ID") + } +} diff --git a/service/process/process.go b/service/process/process.go index 4e0eeeae1..074768643 100644 --- a/service/process/process.go +++ b/service/process/process.go @@ -8,6 +8,7 @@ import ( "runtime" "strings" "sync" + "sync/atomic" "time" processInfo "github.com/shirou/gopsutil/process" @@ -65,9 +66,18 @@ type Process struct { MatchingPath string // PrimaryProfileID holds the scoped ID of the primary profile. + // It is reassigned by RefetchProfile while the process is in use: only + // access it while holding the process lock (as serialization does), and + // use GetPrimaryProfileID for lock-free reads. PrimaryProfileID string + // primaryProfileID mirrors PrimaryProfileID for lock-free reads via + // GetPrimaryProfileID. Both are only written by setProfile. + primaryProfileID atomic.Pointer[string] // profile holds the layered profile based on the primary profile. - profile *profile.LayeredProfile + // It is reassigned by RefetchProfile while the process is in use, so it is + // atomic to allow lock-free reads via Profile(). Writers still hold the + // process lock to update it together with PrimaryProfileID. + profile atomic.Pointer[profile.LayeredProfile] // Mutable attributes. @@ -94,7 +104,7 @@ func (p *Process) Profile() *profile.LayeredProfile { return nil } - return p.profile + return p.profile.Load() } // Leader returns the process group leader that is attached to the process. @@ -154,7 +164,21 @@ func (p *Process) IsSystemResolver() bool { } // Check ID. - return p.PrimaryProfileID == systemResolverScopedID + return p.GetPrimaryProfileID() == systemResolverScopedID +} + +// GetPrimaryProfileID returns the scoped ID of the primary profile, or an +// empty string if no profile is assigned yet. Unlike the PrimaryProfileID +// field, it is safe to call without holding the process lock. +func (p *Process) GetPrimaryProfileID() string { + if p == nil { + return "" + } + + if id := p.primaryProfileID.Load(); id != nil { + return *id + } + return "" } // GetLastSeen returns the unix timestamp when the process was last seen. @@ -196,6 +220,17 @@ func GetOrFindProcess(ctx context.Context, pid int) (*Process, error) { return GetSystemProcess(ctx), nil } + // Return a known process without the more expensive lookup of all process + // data by gopsutil. The creation time is the same, so the process key is, + // too. If the fast path fails, for example because the process exited, the + // lookup below handles it as before. + pid32 := int32(pid) //nolint:gosec // PIDs fit into int32, as for gopsutil below. + if createdAt, ok := fastCreateTime(ctx, pid32); ok { + if p, ok := GetProcessFromStorage(getProcessKey(pid32, createdAt)); ok { + return p, nil + } + } + // Get pid and creation time for identification. pInfo, err := processInfo.NewProcessWithContext(ctx, int32(pid)) if err != nil { diff --git a/service/process/profile.go b/service/process/profile.go index 5b3de0945..1236a2b91 100644 --- a/service/process/profile.go +++ b/service/process/profile.go @@ -20,7 +20,7 @@ func (p *Process) GetProfile(ctx context.Context) (changed bool, err error) { defer p.Unlock() // Check if profile is already loaded. - if p.profile != nil { + if p.profile.Load() != nil { log.Tracer(ctx).Trace("process: profile already loaded") return } @@ -35,8 +35,7 @@ func (p *Process) GetProfile(ctx context.Context) (changed bool, err error) { } // Assign profile to process. - p.PrimaryProfileID = localProfile.ScopedID() - p.profile = localProfile.LayeredProfile() + p.setProfile(localProfile.ScopedID(), localProfile.LayeredProfile()) return true, nil } @@ -53,12 +52,20 @@ func (p *Process) RefetchProfile(ctx context.Context) error { } // Assign profile to process. - p.PrimaryProfileID = localProfile.ScopedID() - p.profile = localProfile.LayeredProfile() + p.setProfile(localProfile.ScopedID(), localProfile.LayeredProfile()) return nil } +// setProfile assigns the primary profile ID and the layered profile to the +// process. The caller must hold the process lock (or own the process +// exclusively, before it is published). +func (p *Process) setProfile(scopedID string, lp *profile.LayeredProfile) { + p.PrimaryProfileID = scopedID + p.primaryProfileID.Store(&scopedID) + p.profile.Store(lp) +} + // getSpecialProfileID returns the special profile ID for the process, if any. func (p *Process) getSpecialProfileID() (specialProfileID string) { // Check if we need a special profile. @@ -108,7 +115,8 @@ func (p *Process) getSpecialProfileID() (specialProfileID string) { // IsPortmasterUi checks if the process is the Portmaster UI or its child (up to 3 parent levels). func (p *Process) IsPortmasterUi(ctx context.Context) bool { - if module.portmasterUIPath == "" { + uiPath := module.portmasterUIPath() + if uiPath == "" { return false } @@ -126,7 +134,7 @@ func (p *Process) IsPortmasterUi(ctx context.Context) bool { } realPath, err := filepath.EvalSymlinks(proc.Path) - if err == nil && realPath == module.portmasterUIPath { + if err == nil && realPath == uiPath { if runtime.GOOS != "windows" { return true } diff --git a/service/process/profile_race_test.go b/service/process/profile_race_test.go new file mode 100644 index 000000000..0e8ec0b3d --- /dev/null +++ b/service/process/profile_race_test.go @@ -0,0 +1,43 @@ +package process + +import ( + "sync" + "testing" + + "github.com/safing/portmaster/service/profile" +) + +// TestProfileConcurrentReassign checks that Profile() is safe to call while +// the profile is being (re)assigned, as RefetchProfile does when connections +// are re-attributed (network.reAttributeConnection) while other connections of +// the same process read the profile, and as GetProfile does for a process that +// is already stored and reachable via All(). +func TestProfileConcurrentReassign(t *testing.T) { + t.Parallel() + + p := &Process{} + a := &profile.LayeredProfile{} + b := &profile.LayeredProfile{} + + const rounds = 1000 + var wg sync.WaitGroup + wg.Go(func() { + for i := range rounds { + lp := a + if i%2 == 1 { + lp = b + } + // Same write pattern as GetProfile/RefetchProfile. + p.Lock() + p.setProfile("local/test", lp) + p.Unlock() + } + }) + + for range rounds { + if lp := p.Profile(); lp != nil && lp != a && lp != b { + t.Fatal("unexpected profile") + } + } + wg.Wait() +} diff --git a/service/profile/binmeta/name.go b/service/profile/binmeta/name.go index cd20c4ea4..546269559 100644 --- a/service/profile/binmeta/name.go +++ b/service/profile/binmeta/name.go @@ -11,7 +11,9 @@ var ( nameOnly = regexp.MustCompile("^[A-Za-z0-9]+$") delimitersAtStart = regexp.MustCompile("^[^A-Za-z0-9]+") delimitersOnly = regexp.MustCompile("^[^A-Za-z0-9]+$") - removeQuotes = strings.NewReplacer(`"`, ``, `'`, ``) + // removeUnsafeChars removes quotes and angle brackets: names are shown in + // the UI, and brackets would let a binary inject HTML through its name. + removeUnsafeChars = strings.NewReplacer(`"`, ``, `'`, ``, `<`, ``, `>`, ``) ) // GenerateBinaryNameFromPath generates a more human readable binary name from @@ -89,9 +91,9 @@ func GenerateBinaryNameFromPath(path string) string { func cleanFileDescription(fileDescr string) string { fields := strings.Fields(fileDescr) - // Clean out and `"` and `'`. + // Clean out quotes and angle brackets. for i := range fields { - fields[i] = removeQuotes.Replace(fields[i]) + fields[i] = removeUnsafeChars.Replace(fields[i]) } // If there is a 1 or 2 character delimiter field, only use fields before it. diff --git a/service/profile/binmeta/name_test.go b/service/profile/binmeta/name_test.go index 90a3b5d94..e003b09fc 100644 --- a/service/profile/binmeta/name_test.go +++ b/service/profile/binmeta/name_test.go @@ -32,6 +32,8 @@ func TestCleanFileDescription(t *testing.T) { assert.Equal(t, "Product Name", cleanFileDescription("Product Name - Does this and that.")) assert.Equal(t, "Product Name", cleanFileDescription("Product Name / Does this and that.")) assert.Equal(t, "Product Name", cleanFileDescription("Product Name :: Does this and that.")) + // Angle brackets would let a binary inject HTML through its name. + assert.Equal(t, "img src=x onerror=alert(1)", cleanFileDescription(``)) assert.Equal(t, "/ Product Name", cleanFileDescription("/ Product Name")) assert.Equal(t, "Product", cleanFileDescription("Product / Name")) assert.Equal(t, "Software 2", cleanFileDescription("Software 2")) diff --git a/service/profile/config-update.go b/service/profile/config-update.go index 8cee47ad2..a98a3b1b6 100644 --- a/service/profile/config-update.go +++ b/service/profile/config-update.go @@ -2,13 +2,17 @@ package profile import ( "context" + "errors" "fmt" "sync" + "sync/atomic" "time" + "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/intel/filterlists" "github.com/safing/portmaster/service/mgr" "github.com/safing/portmaster/service/profile/endpoints" + "github.com/safing/portmaster/service/updates" ) var ( @@ -18,9 +22,6 @@ var ( cfgEndpoints endpoints.Endpoints cfgServiceEndpoints endpoints.Endpoints cfgSplitTunUsagePolicy endpoints.Endpoints - cfgSPNUsagePolicy endpoints.Endpoints - cfgSPNTransitHubPolicy endpoints.Endpoints - cfgSPNExitHubPolicy endpoints.Endpoints cfgFilterLists []string ) @@ -34,12 +35,19 @@ func registerGlobalConfigProfileUpdater() error { const globalConfigProfileErrorID = "profile:global-profile-error" +// globalConfigProfileRetryPending is set while a retry of +// updateGlobalConfigProfile is scheduled. +var globalConfigProfileRetryPending atomic.Bool + func updateGlobalConfigProfile(_ context.Context) error { cfgLock.Lock() defer cfgLock.Unlock() var err error var lastErr error + // retry is set if a setting can only be applied once intel data is + // available, which is not a failure of the settings. + var retry bool action := cfgOptionDefaultAction() switch action { @@ -71,8 +79,16 @@ func updateGlobalConfigProfile(_ context.Context) error { list = cfgOptionFilterLists() cfgFilterLists, err = filterlists.ResolveListIDs(list) - if err != nil { + switch { + case errors.Is(err, updates.ErrNotFound): + // The filter list index is not downloaded yet, e.g. on the first + // start. Apply the lists once it is there. + log.Debugf("profile: filter list index not available yet, retrying global config profile later") + retry = true + case err != nil: lastErr = err + default: + reloadProfilesWithPendingFilterLists() } list = cfgOptionSplitTunUsagePolicy() @@ -82,27 +98,6 @@ func updateGlobalConfigProfile(_ context.Context) error { lastErr = err } - list = cfgOptionSPNUsagePolicy() - cfgSPNUsagePolicy, err = endpoints.ParseEndpoints(list) - if err != nil { - // TODO: module error? - lastErr = err - } - - list = cfgOptionTransitHubPolicy() - cfgSPNTransitHubPolicy, err = endpoints.ParseEndpoints(list) - if err != nil { - // TODO: module error? - lastErr = err - } - - list = cfgOptionExitHubPolicy() - cfgSPNExitHubPolicy, err = endpoints.ParseEndpoints(list) - if err != nil { - // TODO: module error? - lastErr = err - } - // Build config. newConfig := make(map[string]interface{}) // fill profile config options @@ -135,18 +130,20 @@ func updateGlobalConfigProfile(_ context.Context) error { lastErr = err } - // If there was any error, try again later until it succeeds. - if lastErr == nil { - module.states.Remove(globalConfigProfileErrorID) - } else { - // Create task after first failure. - - // Schedule task. + // If there was any error or intel data is missing, try again later until + // it succeeds. Only one retry is pending at a time, also when the config + // changes in the meantime. + if (lastErr != nil || retry) && globalConfigProfileRetryPending.CompareAndSwap(false, true) { _ = module.mgr.Delay("retry updating global config profile", 15*time.Second, func(w *mgr.WorkerCtx) error { + globalConfigProfileRetryPending.Store(false) return updateGlobalConfigProfile(w.Ctx()) }) + } + if lastErr == nil { + module.states.Remove(globalConfigProfileErrorID) + } else { // Add module warning to inform user. module.states.Add(mgr.State{ ID: globalConfigProfileErrorID, @@ -158,3 +155,15 @@ func updateGlobalConfigProfile(_ context.Context) error { return lastErr } + +// reloadProfilesWithPendingFilterLists marks all active profiles as outdated +// whose filter lists could not be resolved before, because the filter list +// index was not available yet. They are reloaded on their next use. +func reloadProfilesWithPendingFilterLists() { + for _, profile := range getAllActiveProfiles() { + if profile.filterListsPending.Load() { + log.Debugf("profile: reloading %s to apply its filter lists", profile.ScopedID()) + profile.outdated.Set() + } + } +} diff --git a/service/profile/config-update_test.go b/service/profile/config-update_test.go new file mode 100644 index 000000000..38bbbe0fc --- /dev/null +++ b/service/profile/config-update_test.go @@ -0,0 +1,32 @@ +package profile + +import "testing" + +func TestReloadProfilesWithPendingFilterLists(t *testing.T) { + t.Parallel() + + pending := &Profile{Source: SourceLocal, ID: "pending-filterlists"} + pending.prepProfile() + pending.filterListsPending.Store(true) + + resolved := &Profile{Source: SourceLocal, ID: "resolved-filterlists"} + resolved.prepProfile() + + addActiveProfile(pending) + addActiveProfile(resolved) + t.Cleanup(func() { + activeProfilesLock.Lock() + defer activeProfilesLock.Unlock() + delete(activeProfiles, pending.ScopedID()) + delete(activeProfiles, resolved.ScopedID()) + }) + + reloadProfilesWithPendingFilterLists() + + if !pending.IsOutdated() { + t.Error("profile with pending filter lists should be marked as outdated") + } + if resolved.IsOutdated() { + t.Error("profile with resolved filter lists should not be marked as outdated") + } +} diff --git a/service/profile/config.go b/service/profile/config.go index 3c80b41a8..f14d3b2f0 100644 --- a/service/profile/config.go +++ b/service/profile/config.go @@ -7,7 +7,6 @@ import ( "github.com/safing/portmaster/base/config" "github.com/safing/portmaster/service/profile/endpoints" "github.com/safing/portmaster/service/status" - "github.com/safing/portmaster/spn/access/account" ) // Configuration Keys. @@ -116,33 +115,6 @@ var ( cfgOptionKeepHistory config.IntOption cfgOptionKeepHistoryOrder = 97 - // Setting "Enable SPN" at order 128. - - CfgOptionUseSPNKey = "spn/use" - cfgOptionUseSPN config.BoolOption - cfgOptionUseSPNOrder = 129 - - CfgOptionSPNUsagePolicyKey = "spn/usagePolicy" - cfgOptionSPNUsagePolicy config.StringArrayOption - cfgOptionSPNUsagePolicyOrder = 130 - - CfgOptionRoutingAlgorithmKey = "spn/routingAlgorithm" - cfgOptionRoutingAlgorithm config.StringOption - cfgOptionRoutingAlgorithmOrder = 144 - DefaultRoutingProfileID = "double-hop" // Copied due to import loop. - - // Setting "Home Node Rules" at order 145. - - CfgOptionTransitHubPolicyKey = "spn/transitHubPolicy" - cfgOptionTransitHubPolicy config.StringArrayOption - cfgOptionTransitHubPolicyOrder = 146 - - CfgOptionExitHubPolicyKey = "spn/exitHubPolicy" - cfgOptionExitHubPolicy config.StringArrayOption - cfgOptionExitHubPolicyOrder = 147 - - // Setting "DNS Exit Node Rules" at order 148. - // Split Tunnel. CfgOptionSplitTunUseKey = "splittun/use" cfgOptionSplitTunUse config.BoolOption @@ -157,29 +129,6 @@ var ( cfgOptionSplitTunUsagePolicyOrder = 216 ) -var ( - // SPNRulesQuickSettings are now generated automatically shorty after start. - SPNRulesQuickSettings = []config.QuickSetting{ - {Name: "Loading...", Action: config.QuickMergeTop, Value: []string{""}}, - } - - // SPNRulesVerdictNames defines the verdicts names to be used for SPN Rules. - SPNRulesVerdictNames = map[string]string{ - "-": "Exclude", // Default. - "+": "Allow", - } - - // SPNRulesHelp defines the help text for SPN related Hub selection rules. - SPNRulesHelp = strings.ReplaceAll(`Rules are checked from top to bottom, stopping after the first match. They can match the following attributes of SPN Nodes: - -- Country (based on IPs): "US" (two-letter country codes according to ISO 3166-1 alpha-2) -- AS number: "AS123456" -- Address: "192.168.0.1" -- Network: "192.168.0.1/24" -- Anything: "*" -`, `"`, "`") -) - func registerConfiguration() error { //nolint:maintidx // Default Filter Action // permit - blocklist mode: everything is allowed unless blocked @@ -256,10 +205,9 @@ In order to reduce noise optimize performance, internal and device-only (localho ExpertiseLevel: config.ExpertiseLevelUser, DefaultValue: false, Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.DisplayOrderAnnotation: cfgOptionEnableHistoryOrder, - config.CategoryAnnotation: "General", - config.RequiresFeatureIDAnnotation: account.FeatureHistory, + config.SettablePerAppAnnotation: true, + config.DisplayOrderAnnotation: cfgOptionEnableHistoryOrder, + config.CategoryAnnotation: "General", }, }) if err != nil { @@ -281,11 +229,10 @@ Set to 0 days to keep network history forever. Depending on your device, this mi ExpertiseLevel: config.ExpertiseLevelUser, DefaultValue: 30, Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.UnitAnnotation: "Days", - config.DisplayOrderAnnotation: cfgOptionKeepHistoryOrder, - config.CategoryAnnotation: "General", - config.RequiresFeatureIDAnnotation: account.FeatureHistory, + config.SettablePerAppAnnotation: true, + config.UnitAnnotation: "Days", + config.DisplayOrderAnnotation: cfgOptionKeepHistoryOrder, + config.CategoryAnnotation: "General", }, }) if err != nil { @@ -689,150 +636,6 @@ Please note that DNS bypass attempts might be additionally blocked in the System cfgOptionPreventBypassing = config.Concurrent.GetAsBool(CfgOptionPreventBypassingKey, true) cfgBoolOptions[CfgOptionPreventBypassingKey] = cfgOptionPreventBypassing - // Use SPN - err = config.Register(&config.Option{ - Name: "Use SPN", - Key: CfgOptionUseSPNKey, - Description: "Protect network traffic with the Safing Privacy Network. If the SPN is not available or the connection is interrupted, network traffic will be blocked.", - OptType: config.OptTypeBool, - DefaultValue: true, - Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.DisplayOrderAnnotation: cfgOptionUseSPNOrder, - config.CategoryAnnotation: "General", - }, - }) - if err != nil { - return err - } - cfgOptionUseSPN = config.Concurrent.GetAsBool(CfgOptionUseSPNKey, true) - cfgBoolOptions[CfgOptionUseSPNKey] = cfgOptionUseSPN - - // SPN Rules - err = config.Register(&config.Option{ - Name: "SPN Rules", - Key: CfgOptionSPNUsagePolicyKey, - Description: `Customize rules which connections should or should not be routed through the SPN. Only active if "Use SPN" is enabled.`, - Help: rulesHelp, - Sensitive: true, - OptType: config.OptTypeStringArray, - DefaultValue: []string{}, - Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.StackableAnnotation: true, - config.CategoryAnnotation: "General", - config.DisplayOrderAnnotation: cfgOptionSPNUsagePolicyOrder, - config.DisplayHintAnnotation: endpoints.DisplayHintEndpointList, - endpoints.EndpointListVerdictNamesAnnotation: SPNRulesVerdictNames, - }, - ValidationRegex: endpoints.ListEntryValidationRegex, - ValidationFunc: endpoints.ValidateEndpointListConfigOption, - }) - if err != nil { - return err - } - cfgOptionSPNUsagePolicy = config.Concurrent.GetAsStringArray(CfgOptionSPNUsagePolicyKey, []string{}) - cfgStringArrayOptions[CfgOptionSPNUsagePolicyKey] = cfgOptionSPNUsagePolicy - - // Transit Node Rules - err = config.Register(&config.Option{ - Name: "Transit Node Rules", - Key: CfgOptionTransitHubPolicyKey, - Description: `Customize which countries should or should not be used as Transit Nodes. Transit Nodes are used to transit the SPN from your Home to your Exit Node.`, - Help: SPNRulesHelp, - Sensitive: true, - OptType: config.OptTypeStringArray, - ExpertiseLevel: config.ExpertiseLevelExpert, - DefaultValue: []string{}, - Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.StackableAnnotation: true, - config.CategoryAnnotation: "Routing", - config.DisplayOrderAnnotation: cfgOptionTransitHubPolicyOrder, - config.DisplayHintAnnotation: endpoints.DisplayHintEndpointList, - config.QuickSettingsAnnotation: SPNRulesQuickSettings, - endpoints.EndpointListVerdictNamesAnnotation: SPNRulesVerdictNames, - }, - ValidationRegex: endpoints.ListEntryValidationRegex, - ValidationFunc: endpoints.ValidateEndpointListConfigOption, - }) - if err != nil { - return err - } - cfgOptionTransitHubPolicy = config.Concurrent.GetAsStringArray(CfgOptionTransitHubPolicyKey, []string{}) - cfgStringArrayOptions[CfgOptionTransitHubPolicyKey] = cfgOptionTransitHubPolicy - - // Exit Node Rules - err = config.Register(&config.Option{ - Name: "Exit Node Rules", - Key: CfgOptionExitHubPolicyKey, - Description: `Customize which countries should or should not be used for your Exit Nodes. Exit Nodes are used to exit the SPN and establish a connection to your destination. - -By default, the Portmaster tries to choose the node closest to the destination as the Exit Node. This reduces your exposure to the open Internet. Exit Nodes are chosen for every destination separately.`, - Help: SPNRulesHelp, - Sensitive: true, - OptType: config.OptTypeStringArray, - DefaultValue: []string{}, - Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.StackableAnnotation: true, - config.CategoryAnnotation: "Routing", - config.DisplayOrderAnnotation: cfgOptionExitHubPolicyOrder, - config.DisplayHintAnnotation: endpoints.DisplayHintEndpointList, - config.QuickSettingsAnnotation: SPNRulesQuickSettings, - endpoints.EndpointListVerdictNamesAnnotation: SPNRulesVerdictNames, - }, - ValidationRegex: endpoints.ListEntryValidationRegex, - ValidationFunc: endpoints.ValidateEndpointListConfigOption, - }) - if err != nil { - return err - } - cfgOptionExitHubPolicy = config.Concurrent.GetAsStringArray(CfgOptionExitHubPolicyKey, []string{}) - cfgStringArrayOptions[CfgOptionExitHubPolicyKey] = cfgOptionExitHubPolicy - - // Select SPN Routing Algorithm - err = config.Register(&config.Option{ - Name: "Select SPN Routing Algorithm", - Key: CfgOptionRoutingAlgorithmKey, - Description: "Select the routing algorithm for your connections through the SPN. Configure your preferred balance between speed and privacy. Portmaster may automatically upgrade the routing algorithm if necessary to protect your privacy.", - OptType: config.OptTypeString, - DefaultValue: DefaultRoutingProfileID, - Annotations: config.Annotations{ - config.SettablePerAppAnnotation: true, - config.DisplayHintAnnotation: config.DisplayHintOneOf, - config.DisplayOrderAnnotation: cfgOptionRoutingAlgorithmOrder, - config.CategoryAnnotation: "Routing", - }, - PossibleValues: []config.PossibleValue{ - { - Name: "Plain VPN Mode", - Value: "home", - Description: "Always connect to the destination directly from the Home Hub. Only provides very basic privacy, as the Home Hub both knows where you are coming from and where you are connecting to.", - }, - { - Name: "Speed Focused", - Value: "single-hop", - Description: "Optimize routes with a minimum of one hop. Provides good speeds. This will often use the Home Hub to connect to destinations near you, but will use more hops to far away destinations for better privacy over long distances.", - }, - { - Name: "Balanced", - Value: "double-hop", - Description: "Optimize routes with a minimum of two hops. Provides good privacy as well as good speeds. No single node knows where you are coming from *and* where you are connecting to.", - }, - { - Name: "Privacy Focused", - Value: "triple-hop", - Description: "Optimize routes with a minimum of three hops. Provides very good privacy. No single node knows where you are coming from *and* where you are connecting to - with an additional hop just to be sure.", - }, - }, - }) - if err != nil { - return err - } - cfgOptionRoutingAlgorithm = config.Concurrent.GetAsString(CfgOptionRoutingAlgorithmKey, DefaultRoutingProfileID) - cfgStringOptions[CfgOptionRoutingAlgorithmKey] = cfgOptionRoutingAlgorithm - // // Split Tunnel // @@ -843,9 +646,7 @@ By default, the Portmaster tries to choose the node closest to the destination a Key: CfgOptionSplitTunUseKey, Description: `Route specific traffic through a different network interface, bypassing default system routing (useful for avoiding VPNs for certain apps). -When you enable this and the Network Interface option is empty, Portmaster will try to route your traffic through the default physical network interface. - -Important: SPN takes precedence over Split Tunnel. To use Split Tunnel with SPN, configure SPN on a per-app basis or define exceptions that allow Split Tunnel to take effect.`, +When you enable this and the Network Interface option is empty, Portmaster will try to route your traffic through the default physical network interface.`, OptType: config.OptTypeBool, DefaultValue: false, Annotations: config.Annotations{ @@ -871,9 +672,7 @@ Important: SPN takes precedence over Split Tunnel. To use Split Tunnel with SPN, Leave empty to let Portmaster detect the physical network interface and ignore virtual VPN interfaces. This helps bypass VPN tunnels. For better reliability, you can specify the interface manually if empty value does not work as expected. -Important: The connection will be dropped if the network interface cannot be detected or becomes unavailable. - -Important: SPN takes precedence over Split Tunnel. To use Split Tunnel with SPN, configure SPN on a per-app basis or define exceptions that allow Split Tunnel to take effect.`, +Important: The connection will be dropped if the network interface cannot be detected or becomes unavailable.`, Sensitive: true, OptType: config.OptTypeString, DefaultValue: "", @@ -902,11 +701,9 @@ Important: SPN takes precedence over Split Tunnel. To use Split Tunnel with SPN, } err = config.Register(&config.Option{ - Name: "Split Tunnel Rules", - Key: CfgOptionSplitTunUsagePolicyKey, - Description: `Customize rules which connections should or should not be routed through the Split Tunnel. Only active if "Use Split Tunnel" is enabled. - -Important: SPN takes precedence over Split Tunnel. To use Split Tunnel with SPN, configure SPN on a per-app basis or define exceptions that allow Split Tunnel to take effect.`, + Name: "Split Tunnel Rules", + Key: CfgOptionSplitTunUsagePolicyKey, + Description: `Customize rules which connections should or should not be routed through the Split Tunnel. Only active if "Use Split Tunnel" is enabled.`, Help: rulesHelp, Sensitive: true, OptType: config.OptTypeStringArray, diff --git a/service/profile/endpoints/endpoint-domain.go b/service/profile/endpoints/endpoint-domain.go index cdb6f2482..358b1840b 100644 --- a/service/profile/endpoints/endpoint-domain.go +++ b/service/profile/endpoints/endpoint-domain.go @@ -36,34 +36,26 @@ type EndpointDomain struct { } func (ep *EndpointDomain) check(entity *intel.Entity, domain string) (EPResult, Reason) { - result, reason := ep.match(ep, entity, ep.OriginalValue, "domain matches") - + var matched bool switch ep.MatchType { case domainMatchTypeExact: - if domain == ep.Domain { - return result, reason - } + matched = domain == ep.Domain case domainMatchTypeZone: - if domain == ep.Domain { - return result, reason - } - if strings.HasSuffix(domain, ep.DomainZone) { - return result, reason - } + matched = domain == ep.Domain || strings.HasSuffix(domain, ep.DomainZone) case domainMatchTypeSuffix: - if strings.HasSuffix(domain, ep.Domain) { - return result, reason - } + matched = strings.HasSuffix(domain, ep.Domain) case domainMatchTypePrefix: - if strings.HasPrefix(domain, ep.Domain) { - return result, reason - } + matched = strings.HasPrefix(domain, ep.Domain) case domainMatchTypeContains: - if strings.Contains(domain, ep.Domain) { - return result, reason - } + matched = strings.Contains(domain, ep.Domain) } - return NoMatch, nil + + // Only build the reason if the domain matches, as this is done for every + // domain rule against the domain and all CNAMEs of every connection. + if !matched { + return NoMatch, nil + } + return ep.match(ep, entity, ep.OriginalValue, "domain matches") } // Matches checks whether the given entity matches this endpoint definition. diff --git a/service/profile/endpoints/endpoint-scopes.go b/service/profile/endpoints/endpoint-scopes.go index b506e2a13..e956b5740 100644 --- a/service/profile/endpoints/endpoint-scopes.go +++ b/service/profile/endpoints/endpoint-scopes.go @@ -94,11 +94,11 @@ func parseTypeScope(fields []string) (Endpoint, error) { for _, val := range strings.Split(strings.ToLower(fields[1]), ",") { switch val { case scopeLocalhostMatcher: - ep.scopes ^= scopeLocalhost + ep.scopes |= scopeLocalhost case scopeLANMatcher: - ep.scopes ^= scopeLAN + ep.scopes |= scopeLAN case scopeInternetMatcher: - ep.scopes ^= scopeInternet + ep.scopes |= scopeInternet default: return nil, nil } diff --git a/service/profile/endpoints/endpoint.go b/service/profile/endpoints/endpoint.go index 2c28aac44..157d44c33 100644 --- a/service/profile/endpoints/endpoint.go +++ b/service/profile/endpoints/endpoint.go @@ -17,7 +17,7 @@ type Endpoint interface { } // EndpointBase provides general functions for implementing an Endpoint to reduce boilerplate. -type EndpointBase struct { //nolint:maligned // TODO +type EndpointBase struct { Protocol uint8 StartPort uint16 EndPort uint16 @@ -64,7 +64,7 @@ func (ep *EndpointBase) makeReason(s fmt.Stringer, value, desc string, keyval .. r.Extra = make(map[string]interface{}) - for idx := 0; idx < len(keyval)/2; idx += 2 { + for idx := 0; idx+1 < len(keyval); idx += 2 { key := keyval[idx] val := keyval[idx+1] @@ -162,7 +162,12 @@ func (ep *EndpointBase) parsePPP(typedEp Endpoint, fields []string) (Endpoint, e case "", "*": return nil, invalidDefinitionError(fields, "omit port if should match any") default: - portSplitted := strings.Split(splitted[1], "-") + // Some port names contain a hyphen (eg. "FTP-DATA"), check + // for a full name match before splitting a port range. + portSplitted := []string{splitted[1]} + if _, isName := reference.GetPortNumber(splitted[1]); !isName { + portSplitted = strings.Split(splitted[1], "-") + } if len(portSplitted) > 2 { return nil, invalidDefinitionError(fields, "ports must be in format from-to") } @@ -196,6 +201,9 @@ func (ep *EndpointBase) parsePPP(typedEp Endpoint, fields []string) (Endpoint, e return nil, invalidDefinitionError(fields, "port number cannot be 0") } ep.EndPort = n16 + if ep.EndPort < ep.StartPort { + return nil, invalidDefinitionError(fields, "start port must not be greater than end port") + } } } // check if anything was parsed @@ -236,6 +244,10 @@ func parseEndpoint(value string) (endpoint Endpoint, err error) { break } } + // All parsers access the first two fields. + if len(fields) < 2 { + return nil, invalidDefinitionError(fields, "missing permission prefix or entity") + } // any if endpoint, err = parseTypeAny(fields); endpoint != nil || err != nil { diff --git a/service/profile/endpoints/endpoint_fuzz_test.go b/service/profile/endpoints/endpoint_fuzz_test.go new file mode 100644 index 000000000..997790fe4 --- /dev/null +++ b/service/profile/endpoints/endpoint_fuzz_test.go @@ -0,0 +1,60 @@ +package endpoints + +import ( + "context" + "net" + "testing" + + "github.com/safing/portmaster/service/intel" +) + +var fuzzSeeds = []string{ + "- *", "+ *", "- *bad*", "- bad*", "- *bad.com", "- .bad.com", "- bad.com", + "- www.bad.com.", "+ 127.0.0.1", "+ ::1", "+ 2606:4700:4700::1111", + "+ 127.0.0.0/8", "+ 2606:4700:4700::/48", "+ ::ffff:1.2.3.0/120", "+ ::ffff:1.2.3.4", + "+ DE", "+ AS", "+ C:EU", "+ AS1234", "+ Localhost", "+ LAN", "+ Internet", + "+ Localhost,LAN,Internet", "+ LAN,LAN", "+ * TCP/1-1024", "+ * */DNS", "+ * ICMP", + "+ * 127", "+ * UDP/1234", "+ * TCP/HTTP", "+ * TCP/80-443", "+ * TCP/443-80", + "+ * TCP/20", "+ * TCP/FTP-DATA", "+ * 6/65535", "+ * 6/65536", "+ * 256", + "+ L:MAL", "- L:MAL,TRAC", "- L:", "+ example.* */HTTPS", "+ .example.com", + "+ *example.com", "+ example.com # comment", "+ #", "+ # comment", "# foo bar", + "+", "-", "", " ", "+ .", "+ *.", "+ **", "+ ä.com", "+ 1.2.3.4 UDP-LITE/1-2", +} + +var fuzzEntities = []*intel.Entity{ + (&intel.Entity{}).Init(0), + (&intel.Entity{Domain: apexDomain}).Init(0), + (&intel.Entity{IP: net.ParseIP("127.0.0.1"), Protocol: 6, Port: 80}).Init(0), + (&intel.Entity{IP: net.ParseIP("192.168.1.1"), Domain: "bad.com.", Protocol: 17, Port: 53}).Init(0), + (&intel.Entity{IP: net.ParseIP("::ffff:1.2.3.4"), Protocol: 1}).Init(0), +} + +func FuzzParseEndpoint(f *testing.F) { + for _, s := range fuzzSeeds { + f.Add(s) + } + f.Fuzz(func(t *testing.T, value string) { + ep, err := parseEndpoint(value) + if err != nil { + return + } + if ep == nil { + t.Fatalf("nil endpoint without error for %q", value) + } + s := ep.String() + ep2, err := parseEndpoint(s) + if err != nil { + t.Fatalf("%q parsed, but String() %q does not: %s", value, s, err) + } + if s2 := ep2.String(); s2 != s { + t.Fatalf("%q: unstable String(): %q -> %q", value, s, s2) + } + for _, e := range fuzzEntities { + r1, _ := ep.Matches(context.Background(), e) + r2, _ := ep2.Matches(context.Background(), e) + if r1 != r2 { + t.Fatalf("%q vs re-parsed %q: match result differs for %+v: %s vs %s", value, s, e, r1, r2) + } + } + }) +} diff --git a/service/profile/endpoints/endpoint_portrange_test.go b/service/profile/endpoints/endpoint_portrange_test.go new file mode 100644 index 000000000..f969da16f --- /dev/null +++ b/service/profile/endpoints/endpoint_portrange_test.go @@ -0,0 +1,21 @@ +package endpoints + +import "testing" + +func TestParsePortRange(t *testing.T) { + t.Parallel() + + for _, rule := range []string{"+ * TCP/80-8000", "- * UDP/HTTP-HTTPS", "- * TCP/443-443"} { + _, err := parseEndpoint(rule) + if err != nil { + t.Errorf("%q: unexpected error: %s", rule, err) + } + } + // A reversed range never matched any port, so a block rule silently did nothing. + for _, rule := range []string{"- * TCP/8000-80", "+ * TCP/443-80", "- * UDP/HTTPS-HTTP"} { + _, err := parseEndpoint(rule) + if err == nil { + t.Errorf("%q: reversed port range was accepted", rule) + } + } +} diff --git a/service/profile/endpoints/endpoint_test.go b/service/profile/endpoints/endpoint_test.go index 1af937e0d..45c602080 100644 --- a/service/profile/endpoints/endpoint_test.go +++ b/service/profile/endpoints/endpoint_test.go @@ -59,6 +59,13 @@ func TestEndpointParsing(t *testing.T) { testParsing(t, "+ * UDP/1234") testParsing(t, "+ * TCP/HTTP") testParsing(t, "+ * TCP/80-443") + testParsing(t, "+ * TCP/FTP-DATA") // Port name with hyphen. + ep, err := parseEndpoint("+ * UDP/DHCP-SERVER") + if err != nil { + t.Error(err) + } else if ep.String() != "+ * UDP/DHCP_SERVER" { + t.Errorf(`unexpected rendering of hyphenated port name: "%s"`, ep.String()) + } // TODO: Test fails: // testParsing(t, "+ 1234") diff --git a/service/profile/endpoints/endpoints_bench_test.go b/service/profile/endpoints/endpoints_bench_test.go new file mode 100644 index 000000000..1580af14d --- /dev/null +++ b/service/profile/endpoints/endpoints_bench_test.go @@ -0,0 +1,161 @@ +package endpoints + +import ( + "context" + "net" + "strings" + "testing" + + "github.com/safing/portmaster/service/intel" +) + +const ( + ruleExact = "- example.com" + ruleZone = "+ .example.com" + ruleZonePPP = "- .example.com TCP/443" + rulePrefix = "- stats.*" + wwwDomain = "www.example.com." + apexDomain = "example.com." +) + +// benchRules is a realistic mix of endpoint rules as found in a user's +// profile: mostly domain rules of all match types, followed by a few IP, +// network, country, ASN, scope and filter list rules. Country and ASN rules +// are allow rules, so that missing geoip data in tests does not end matching. +var benchRules = []string{ + "- ads.example.net", + "- tracker.example.org", + "- .doubleclick.net", + "- .googlesyndication.com", + "- .facebook.com", + "- .fbcdn.net", + "- *.telemetry.microsoft.com", + "- *analytics*", + "- *metrics*", + rulePrefix, + "- *.hotjar.com", + "+ .github.com", + "+ .githubusercontent.com", + "+ api.mozilla.org", + "+ *.debian.org", + "+ .ubuntu.com TCP/443", + "+ updates.example.com UDP/443", + "- *.ru", + "- .cn", + "+ .wikipedia.org", + "+ .wikimedia.org", + "- 203.0.113.7", + "- 198.51.100.0/24", + "- 2001:db8::/32", + "+ 192.168.0.0/16", + "+ AS64496", + "+ AS64511", + "+ CH", + "+ AT", + "+ Localhost", + "- L:TRAC,MAL", + "+ LAN", + "- * TCP/23", + "- * UDP/137-139", +} + +func newBenchEntity(ctx context.Context) *intel.Entity { + entity := (&intel.Entity{ + Domain: "www.service.example.com.", + CNAME: []string{"www.service.example.com.edgekey.net.", "e1234.a.akamaiedge.net.", "lb.cdn.example.net."}, + IP: net.ParseIP("93.184.216.34"), + Protocol: 6, + Port: 443, + // Pre-loaded list data, as it would be after LoadLists. + ListOccurences: map[string][]string{ + "lb.cdn.example.net.": {"ADS"}, + }, + }).Init(0) + entity.EnableCNAMECheck(ctx, true) + return entity +} + +// BenchmarkEndpointsMatch measures matching a connection entity that matches +// no rule against a realistic rule list, which is the most common case: every +// rule has to be evaluated against the domain and all its CNAMEs. +func BenchmarkEndpointsMatch(b *testing.B) { + eps, err := ParseEndpoints(benchRules) + if err != nil { + b.Fatal(err) + } + ctx := context.Background() + entity := newBenchEntity(ctx) + // Fetch (or fail to fetch) the geoip data once, as it is cached in the + // entity and may wait for the geoip database to become available. + entity.FetchLocation(ctx) + + b.ReportAllocs() + for b.Loop() { + if result, _ := eps.Match(ctx, entity); result != NoMatch { + b.Fatalf("unexpected result %s", result) + } + } +} + +func TestEndpointDomainCheck(t *testing.T) { + t.Parallel() + + ctx := context.Background() + tests := []struct { + rule string + domain string + cnames []string + proto uint8 + port uint16 + want EPResult + }{ + {rule: ruleExact, domain: apexDomain, want: Denied}, + {rule: ruleExact, domain: wwwDomain, want: NoMatch}, + {rule: ruleExact, domain: "example.com", want: NoMatch}, // Missing trailing dot. + {rule: ruleExact, domain: "", want: NoMatch}, + {rule: ruleZone, domain: apexDomain, want: Permitted}, + {rule: ruleZone, domain: "a.b.example.com.", want: Permitted}, + {rule: ruleZone, domain: "badexample.com.", want: NoMatch}, + {rule: "- *example.com", domain: "badexample.com.", want: Denied}, + {rule: "- *.example.com", domain: apexDomain, want: NoMatch}, + {rule: rulePrefix, domain: "stats.example.com.", want: Denied}, + {rule: rulePrefix, domain: "www.stats.example.com.", want: NoMatch}, + {rule: "- *track*", domain: "xn--trck-loa.tracker.example.", want: Denied}, + {rule: "- *track*", domain: "träck.example.", want: NoMatch}, + {rule: ruleZonePPP, domain: wwwDomain, proto: 6, port: 443, want: Denied}, + {rule: ruleZonePPP, domain: wwwDomain, proto: 17, port: 443, want: NoMatch}, + {rule: ruleZonePPP, domain: wwwDomain, proto: 6, port: 80, want: NoMatch}, + // CNAMEs only count for deny rules. + {rule: "- .cdn.example", domain: wwwDomain, cnames: []string{"a.cdn.example."}, want: Denied}, + {rule: "+ .cdn.example", domain: wwwDomain, cnames: []string{"a.cdn.example."}, want: NoMatch}, + {rule: "- .cdn.example", domain: wwwDomain, cnames: []string{"", "cdn.example."}, want: Denied}, + } + for _, tc := range tests { + ep, err := parseEndpoint(tc.rule) + if err != nil { + t.Fatalf("failed to parse %q: %s", tc.rule, err) + } + entity := (&intel.Entity{ + Domain: tc.domain, + CNAME: tc.cnames, + Protocol: tc.proto, + Port: tc.port, + }).Init(0) + entity.EnableCNAMECheck(ctx, true) + + result, r := ep.Matches(ctx, entity) + if result != tc.want { + t.Errorf("%q on %q %v: got %s, want %s", tc.rule, tc.domain, tc.cnames, result, tc.want) + } + if (r != nil) != (result != NoMatch) { + t.Errorf("%q on %q %v: got reason %v for result %s", tc.rule, tc.domain, tc.cnames, r, result) + } + if r == nil { + continue + } + rc, ok := r.Context().(*reason) + if !ok || rc.Value != strings.Fields(tc.rule)[1] { + t.Errorf("%q on %q: unexpected reason %+v", tc.rule, tc.domain, r.Context()) + } + } +} diff --git a/service/profile/endpoints/endpoints_test.go b/service/profile/endpoints/endpoints_test.go index e911e530e..e2fb5fac5 100644 --- a/service/profile/endpoints/endpoints_test.go +++ b/service/profile/endpoints/endpoints_test.go @@ -168,6 +168,12 @@ func TestEndpointFormat(t *testing.T) { testFormat(t, "+ *has.prefix.*", true) testFormat(t, "+ .sub.and.prefix.*", false) testFormat(t, "+ *.sub..and.prefix.*", false) + + // Comments must not leave too few fields behind. + testFormat(t, "+ #", false) + testFormat(t, "- # comment", false) + testFormat(t, "# just a comment", false) + testFormat(t, "+ * # comment", true) } func TestEndpointMatching(t *testing.T) { //nolint:maintidx // TODO @@ -507,6 +513,17 @@ func TestEndpointMatching(t *testing.T) { //nolint:maintidx // TODO entity = (&intel.Entity{IP: net.IPv4(151, 101, 1, 164)}).Init(0) // nytimes.com testEndpointMatch(t, ep, entity, NoMatch) + // A scope listed twice must still be included. + ep, err = parseEndpoint("+ Localhost,LAN,LAN") + if err != nil { + t.Fatal(err) + } + if ep.String() != "+ Localhost,LAN" { + t.Errorf(`unexpected rendering of duplicate scopes: "%s"`, ep.String()) + } + entity = (&intel.Entity{IP: net.IPv4(192, 168, 0, 1)}).Init(0) + testEndpointMatch(t, ep, entity, Permitted) + // Port with protocol wildcard ep, err = parseEndpoint("+ * */443") diff --git a/service/profile/endpoints/reason_test.go b/service/profile/endpoints/reason_test.go new file mode 100644 index 000000000..3b09e03ea --- /dev/null +++ b/service/profile/endpoints/reason_test.go @@ -0,0 +1,36 @@ +package endpoints + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMakeReasonKeyValuePairs(t *testing.T) { + t.Parallel() + + ep := &EndpointBase{} + extra := func(keyval ...any) map[string]any { + r, ok := ep.makeReason(&EndpointAny{}, "v", "desc", keyval...).(*reason) + require.True(t, ok, "must be a *reason") + return r.Extra + } + + assert.Empty(t, extra()) + assert.Equal(t, map[string]any{"a": 1}, extra("a", 1)) + assert.Equal( + t, + map[string]any{"a": 1, "b": "two", "c": true}, + extra("a", 1, "b", "two", "c", true), + ) + + // Odd number of arguments: trailing key without value is ignored. + assert.NotPanics(t, func() { + assert.Equal(t, map[string]any{"a": 1}, extra("a", 1, "b")) + assert.Empty(t, extra("a")) + }) + + // Non-string keys are skipped. + assert.Equal(t, map[string]any{"b": 2}, extra(1, 1, "b", 2)) +} diff --git a/service/profile/migrations.go b/service/profile/migrations.go index b9c813537..5c676c1f6 100644 --- a/service/profile/migrations.go +++ b/service/profile/migrations.go @@ -40,7 +40,7 @@ func migrateLinkedPath(ctx context.Context, _, to *version.Version, db *database it, err := db.Query(query.New(ProfilesDBPath)) if err != nil { log.Tracer(ctx).Errorf("profile: failed to migrate from linked path: failed to start query: %s", err) - return nil + return fmt.Errorf("failed to start profile query for linked path migration: %w", err) } // Migrate all profiles. @@ -71,6 +71,7 @@ func migrateLinkedPath(ctx context.Context, _, to *version.Version, db *database // Check if there was an error while iterating. if err := it.Err(); err != nil { log.Tracer(ctx).Errorf("profile: failed to migrate from linked path: failed to iterate over profiles for migration: %s", err) + return fmt.Errorf("failed to iterate over profiles for linked path migration: %w", err) } return nil @@ -81,12 +82,13 @@ func migrateIcons(ctx context.Context, _, to *version.Version, db *database.Inte it, err := db.Query(query.New(ProfilesDBPath)) if err != nil { log.Tracer(ctx).Errorf("profile: failed to migrate from icon fields: failed to start query: %s", err) - return nil + return fmt.Errorf("failed to start profile query for icon fields migration: %w", err) } // Migrate all profiles. var ( lastErr error + iterErr error failed int total int ) @@ -124,6 +126,7 @@ func migrateIcons(ctx context.Context, _, to *version.Version, db *database.Inte // Check if there was an error while iterating. if err := it.Err(); err != nil { log.Tracer(ctx).Errorf("profile: failed to migrate from icon fields: failed to iterate over profiles for migration: %s", err) + iterErr = fmt.Errorf("failed to iterate over profiles for icon migration: %w", err) } // Log migration failure and try again next time. @@ -139,7 +142,7 @@ func migrateIcons(ctx context.Context, _, to *version.Version, db *database.Inte return fmt.Errorf("failed to migrate %d profiles (out of %d pending) - last error: %w", failed, total, lastErr) } - return lastErr + return iterErr } var randomUUIDRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) @@ -151,12 +154,13 @@ func migrateToDerivedIDs(ctx context.Context, _, to *version.Version, db *databa it, err := db.Query(query.New(ProfilesDBPath)) if err != nil { log.Tracer(ctx).Errorf("profile: failed to migrate to derived profile IDs: failed to start query: %s", err) - return nil + return fmt.Errorf("failed to start profile query for derived profile IDs migration: %w", err) } // Migrate all profiles. var ( lastErr error + iterErr error failed int total int ) @@ -165,6 +169,7 @@ func migrateToDerivedIDs(ctx context.Context, _, to *version.Version, db *databa profile, err := EnsureProfile(r) if err != nil { failed++ + total++ lastErr = err log.Tracer(ctx).Debugf("profiles: failed to parse profile %s for migration: %s", r.Key(), err) continue @@ -208,6 +213,7 @@ func migrateToDerivedIDs(ctx context.Context, _, to *version.Version, db *databa // Check if there was an error while iterating. if err := it.Err(); err != nil { log.Tracer(ctx).Errorf("profile: failed to migrate to derived profile IDs: failed to iterate over profiles for migration: %s", err) + iterErr = fmt.Errorf("failed to iterate over profiles for derived profile IDs migration: %w", err) } // Delete old migrated profiles. @@ -228,5 +234,5 @@ func migrateToDerivedIDs(ctx context.Context, _, to *version.Version, db *databa return fmt.Errorf("failed to migrate %d profiles (out of %d pending) - last error: %w", failed, total, lastErr) } - return nil + return iterErr } diff --git a/service/profile/migrations_test.go b/service/profile/migrations_test.go new file mode 100644 index 000000000..a15c4ee79 --- /dev/null +++ b/service/profile/migrations_test.go @@ -0,0 +1,80 @@ +package profile + +import ( + "context" + "errors" + "testing" + + "github.com/hashicorp/go-version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/database" + "github.com/safing/portmaster/base/database/iterator" + "github.com/safing/portmaster/base/database/query" + "github.com/safing/portmaster/base/database/storage" +) + +// abortingStorage is a storage whose queries start successfully, but whose +// iteration is aborted with an error before any record is delivered. +type abortingStorage struct { + storage.InjectBase +} + +var errIterationAborted = errors.New("iteration aborted") + +func (*abortingStorage) Query(_ *query.Query, _, _ bool) (*iterator.Iterator, error) { + it := iterator.New() + it.Finish(errIterationAborted) + return it, nil +} + +// TestMigrationsReportQueryStartFailure verifies that migrations return an +// error if the profile query cannot be started, so that the migration is not +// recorded as applied and is retried on the next start. +func TestMigrationsReportQueryStartFailure(t *testing.T) { + t.Parallel() + + // The profile database is not available in this test, so every query fails. + db := database.NewInterface(&database.Options{Local: true, Internal: true}) + to := version.Must(version.NewSemver("v1.6.3")) + + for name, migrate := range map[string]func(context.Context, *version.Version, *version.Version, *database.Interface) error{ + "linked path": migrateLinkedPath, + "icons": migrateIcons, + "derived IDs": migrateToDerivedIDs, + } { + err := migrate(context.Background(), nil, to, db) + assert.Error(t, err, "migration %q must fail if the query cannot be started", name) + } +} + +// TestMigrationsReportIterationFailure verifies that migrations return an +// error if the profile iteration is aborted midway, so that the migration is +// not recorded as applied and the remaining profiles are migrated on retry. +// +//nolint:paralleltest // Initializes and injects into the global database system. +func TestMigrationsReportIterationFailure(t *testing.T) { + require.NoError(t, database.Initialize(t.TempDir())) + _, err := database.Register(&database.Database{ + Name: "core", + Description: "test", + StorageType: database.StorageTypeInjected, + }) + require.NoError(t, err) + controller, err := database.InjectDatabase("core", &abortingStorage{}) + require.NoError(t, err) + t.Cleanup(controller.Withdraw) + + db := database.NewInterface(&database.Options{Local: true, Internal: true}) + to := version.Must(version.NewSemver("v1.6.3")) + + for name, migrate := range map[string]func(context.Context, *version.Version, *version.Version, *database.Interface) error{ + "linked path": migrateLinkedPath, + "icons": migrateIcons, + "derived IDs": migrateToDerivedIDs, + } { + err := migrate(context.Background(), nil, to, db) + require.ErrorIs(t, err, errIterationAborted, "migration %q must fail if the iteration is aborted", name) + } +} diff --git a/service/profile/profile-layered.go b/service/profile/profile-layered.go index f0f732850..78b20de83 100644 --- a/service/profile/profile-layered.go +++ b/service/profile/profile-layered.go @@ -2,6 +2,7 @@ package profile import ( "context" + "slices" "sync" "sync/atomic" @@ -27,8 +28,13 @@ type LayeredProfile struct { securityLevel *uint32 - // These functions give layered access to configuration options and require - // the layered profile to be read locked. + // optionState is the state the wrapped config options below are derived + // from. It is replaced, never changed, while the layered profile is write + // locked, so the options can be used without locking the layered profile. + optionState atomic.Pointer[layeredOptionState] + + // These functions give layered access to configuration options. They do + // not require the layered profile to be locked. // TODO(ppacher): we need JSON tags here so the layeredProfile can be exposed // via the API. If we ever switch away from JSON to something else supported @@ -46,14 +52,19 @@ type LayeredProfile struct { FilterCNAMEs config.BoolOption `json:"-"` PreventBypassing config.BoolOption `json:"-"` DomainHeuristics config.BoolOption `json:"-"` - UseSPN config.BoolOption `json:"-"` - SPNRoutingAlgorithm config.StringOption `json:"-"` EnableHistory config.BoolOption `json:"-"` KeepHistory config.IntOption `json:"-"` UseSplitTun config.BoolOption `json:"-"` SplitTunInterface config.StringOption `json:"-"` } +// layeredOptionState is an immutable snapshot of the revision and the layers +// of a layered profile. +type layeredOptionState struct { + revisionCounter uint64 + layers []*Profile +} + // NewLayeredProfile returns a new layered profile based on the given local profile. func NewLayeredProfile(localProfile *Profile) *LayeredProfile { var securityLevelVal uint32 @@ -123,14 +134,6 @@ func NewLayeredProfile(localProfile *Profile) *LayeredProfile { CfgOptionSplitTunInterfaceKey, cfgOptionSplitTunInterface, ) - lp.UseSPN = lp.wrapBoolOption( - CfgOptionUseSPNKey, - cfgOptionUseSPN, - ) - lp.SPNRoutingAlgorithm = lp.wrapStringOption( - CfgOptionRoutingAlgorithmKey, - cfgOptionRoutingAlgorithm, - ) lp.EnableHistory = lp.wrapBoolOption( CfgOptionEnableHistoryKey, cfgOptionEnableHistory, @@ -142,6 +145,7 @@ func NewLayeredProfile(localProfile *Profile) *LayeredProfile { lp.LayerIDs = append(lp.LayerIDs, localProfile.ScopedID()) lp.layers = append(lp.layers, localProfile) + lp.publishOptionState() // TODO: Load additional profiles. @@ -167,10 +171,12 @@ func (lp *LayeredProfile) LockForUsage() { // UnlockForUsage unlocks the layered profile, including all layers individually. func (lp *LayeredProfile) UnlockForUsage() { - lp.RUnlock() + // Unlock the layers while still holding the read lock on the layered + // profile, as Update may replace layers as soon as it is released. for _, layer := range lp.layers { layer.RUnlock() } + lp.RUnlock() } // LocalProfile returns the local profile associated with this layered profile. @@ -210,6 +216,7 @@ func (lp *LayeredProfile) increaseRevisionCounter(lock bool) (revisionCounter ui // Increase the revision counter. lp.RevisionCounter++ + lp.publishOptionState() // Push the increased counter to the UI. pushLayeredProfile(lp) @@ -377,56 +384,6 @@ func (lp *LayeredProfile) MatchSplitTunUsagePolicy(ctx context.Context, entity * return cfgSplitTunUsagePolicy.Match(ctx, entity) } -// MatchSPNUsagePolicy checks if the given endpoint matches an entry in any of the profiles. This functions requires the layered profile to be read locked. -func (lp *LayeredProfile) MatchSPNUsagePolicy(ctx context.Context, entity *intel.Entity) (endpoints.EPResult, endpoints.Reason) { - for _, layer := range lp.layers { - if layer.spnUsagePolicy.IsSet() { - result, reason := layer.spnUsagePolicy.Match(ctx, entity) - if endpoints.IsDecision(result) { - return result, reason - } - } - } - - cfgLock.RLock() - defer cfgLock.RUnlock() - return cfgSPNUsagePolicy.Match(ctx, entity) -} - -// StackedTransitHubPolicies returns all transit hub policies of the layered profile, including the global one. -func (lp *LayeredProfile) StackedTransitHubPolicies() []endpoints.Endpoints { - policies := make([]endpoints.Endpoints, 0, len(lp.layers)+3) // +1 for global policy, +2 for intel policies - - for _, layer := range lp.layers { - if layer.spnTransitHubPolicy.IsSet() { - policies = append(policies, layer.spnTransitHubPolicy) - } - } - - cfgLock.RLock() - defer cfgLock.RUnlock() - policies = append(policies, cfgSPNTransitHubPolicy) - - return policies -} - -// StackedExitHubPolicies returns all exit hub policies of the layered profile, including the global one. -func (lp *LayeredProfile) StackedExitHubPolicies() []endpoints.Endpoints { - policies := make([]endpoints.Endpoints, 0, len(lp.layers)+3) // +1 for global policy, +2 for intel policies - - for _, layer := range lp.layers { - if layer.spnExitHubPolicy.IsSet() { - policies = append(policies, layer.spnExitHubPolicy) - } - } - - cfgLock.RLock() - defer cfgLock.RUnlock() - policies = append(policies, cfgSPNExitHubPolicy) - - return policies -} - // MatchFilterLists matches the entity against the set of filter // lists. This functions requires the layered profile to be read locked. func (lp *LayeredProfile) MatchFilterLists(ctx context.Context, entity *intel.Entity) (endpoints.EPResult, endpoints.Reason) { @@ -465,12 +422,15 @@ func (lp *LayeredProfile) wrapBoolOption(configKey string, globalConfig config.B defer refreshLock.Unlock() // Check if we need to refresh the value. - if revCnt != lp.RevisionCounter { - revCnt = lp.RevisionCounter + // Use the published state, as the caller might not hold a lock on + // the layered profile. + state := lp.optionState.Load() + if revCnt != state.revisionCounter { + revCnt = state.revisionCounter // Go through all layers to find an active value. found := false - for _, layer := range lp.layers { + for _, layer := range state.layers { layerValue, ok := layer.configPerspective.GetAsBool(configKey) if ok { found = true @@ -497,12 +457,15 @@ func (lp *LayeredProfile) wrapIntOption(configKey string, globalConfig config.In defer refreshLock.Unlock() // Check if we need to refresh the value. - if revCnt != lp.RevisionCounter { - revCnt = lp.RevisionCounter + // Use the published state, as the caller might not hold a lock on + // the layered profile. + state := lp.optionState.Load() + if revCnt != state.revisionCounter { + revCnt = state.revisionCounter // Go through all layers to find an active value. found := false - for _, layer := range lp.layers { + for _, layer := range state.layers { layerValue, ok := layer.configPerspective.GetAsInt(configKey) if ok { found = true @@ -543,12 +506,15 @@ func (lp *LayeredProfile) wrapStringOption(configKey string, globalConfig config defer refreshLock.Unlock() // Check if we need to refresh the value. - if revCnt != lp.RevisionCounter { - revCnt = lp.RevisionCounter + // Use the published state, as the caller might not hold a lock on + // the layered profile. + state := lp.optionState.Load() + if revCnt != state.revisionCounter { + revCnt = state.revisionCounter // Go through all layers to find an active value. found := false - for _, layer := range lp.layers { + for _, layer := range state.layers { layerValue, ok := layer.configPerspective.GetAsString(configKey) if ok { found = true @@ -564,3 +530,13 @@ func (lp *LayeredProfile) wrapStringOption(configKey string, globalConfig config return value } } + +// publishOptionState makes the current revision and layers available to the +// wrapped config options. The layered profile must be write locked, or not +// yet be shared. +func (lp *LayeredProfile) publishOptionState() { + lp.optionState.Store(&layeredOptionState{ + revisionCounter: lp.RevisionCounter, + layers: slices.Clone(lp.layers), + }) +} diff --git a/service/profile/profile-layered_test.go b/service/profile/profile-layered_test.go new file mode 100644 index 000000000..a9affea43 --- /dev/null +++ b/service/profile/profile-layered_test.go @@ -0,0 +1,207 @@ +package profile + +import ( + "fmt" + "sync" + "testing" + "time" + + "github.com/safing/portmaster/base/config" +) + +// TestLayeredProfileUnlockForUsageDuringUpdate checks that UnlockForUsage +// releases exactly the layers that LockForUsage locked, even if Update +// replaces an outdated layer concurrently (as happens when multiple +// connections of the same process are handled by the firewall). +// +//nolint:paralleltest // Uses the global active profiles. +func TestLayeredProfileUnlockForUsageDuringUpdate(t *testing.T) { + for i := range 200 { + id := fmt.Sprintf("test-unlock-for-usage-%d", i) + oldProfile := New(&Profile{ID: id, Source: SourceLocal}) + addActiveProfile(oldProfile) + lp := NewLayeredProfile(oldProfile) + + // A connection uses the layered profile. + lp.LockForUsage() + + // Meanwhile, the profile is updated (this marks the old one as outdated) + // and another connection updates the layered profile. + newProfile := New(&Profile{ID: id, Source: SourceLocal}) + addActiveProfile(newProfile) + updated := make(chan struct{}) + go func() { + defer close(updated) + lp.Update(nil, nil) + }() + + // The first connection is done. + lp.UnlockForUsage() + <-updated + + // All locks of the old layer must be released. + if !oldProfile.TryLock() { + t.Fatalf("iteration %d: replaced layer is still read-locked", i) + } + oldProfile.Unlock() + + // The new layer was never locked for usage and must be unlocked too. + if !newProfile.TryLock() { + t.Fatalf("iteration %d: new layer is locked", i) + } + newProfile.Unlock() + + // Clean up. + activeProfilesLock.Lock() + delete(activeProfiles, newProfile.ScopedID()) + activeProfilesLock.Unlock() + } +} + +const testLayeredOptionKey = "test/layeredProfileOption" + +var registerTestLayeredOption sync.Once + +// newTestLayeredProfileVersion creates and activates a new version of the +// test profile with the given ID, which marks the previous one as outdated. +func newTestLayeredProfileVersion(t *testing.T, id string, optionValue bool) *Profile { + t.Helper() + + registerTestLayeredOption.Do(func() { + err := config.Register(&config.Option{ + Name: "Test Layered Profile Option", + Key: testLayeredOptionKey, + Description: "Option for testing the wrapped options of layered profiles.", + OptType: config.OptTypeBool, + DefaultValue: false, + }) + if err != nil { + t.Fatal(err) + } + }) + + p := New(&Profile{ + ID: id, + Source: SourceLocal, + Config: map[string]any{testLayeredOptionKey: optionValue}, + }) + addActiveProfile(p) + return p +} + +func removeTestLayeredProfile(id string) { + activeProfilesLock.Lock() + defer activeProfilesLock.Unlock() + delete(activeProfiles, MakeScopedID(SourceLocal, id)) +} + +// TestLayeredProfileOptionsWithoutLock checks that the wrapped config options +// may be used without holding a lock on the layered profile (as eg. the +// tunnel checks, the history cleaner and the connection saving do), while the +// layered profile is updated. +// Run with -race. +// +//nolint:paralleltest // Uses the global active profiles. +func TestLayeredProfileOptionsWithoutLock(t *testing.T) { + const id = "test-options-without-lock" + defer removeTestLayeredProfile(id) + + lp := NewLayeredProfile(newTestLayeredProfileVersion(t, id, false)) + globalDefault := func() bool { + t.Error("the option is set by the profile, the global config must not be used") + return false + } + boolOption := lp.wrapBoolOption(testLayeredOptionKey, globalDefault) + intOption := lp.wrapIntOption("test/unsetIntOption", func() int64 { return 42 }) + stringOption := lp.wrapStringOption("test/unsetStringOption", func() string { return "global" }) + + // Use the options without any lock. + var ( + wg sync.WaitGroup + done = make(chan struct{}) + ) + for range 4 { + wg.Go(func() { + for { + select { + case <-done: + return + default: + } + boolOption() + if v := intOption(); v != 42 { + t.Errorf("int option is %d, expected 42", v) + return + } + if v := stringOption(); v != "global" { + t.Errorf("string option is %q, expected global", v) + return + } + } + }) + } + + // Meanwhile, replace the layer and bump the revision. + for i := range 500 { + value := i%2 == 0 + newTestLayeredProfileVersion(t, id, value) + lp.Update(nil, nil) + lp.increaseRevisionCounter(true) + + // After an update, the option must reflect the new layer. + if got := boolOption(); got != value { + t.Fatalf("iteration %d: option is %v after update, expected %v", i, got, value) + } + } + close(done) + wg.Wait() +} + +// TestLayeredProfileOptionsDoNotLock checks that the wrapped config options +// do not lock the layered profile: Callers such as MatchFilterLists use them +// while holding a read lock. Acquiring another read lock would deadlock as +// soon as Update waits for the write lock in between. +// +//nolint:paralleltest // Uses the global active profiles. +func TestLayeredProfileOptionsDoNotLock(t *testing.T) { + const id = "test-options-do-not-lock" + defer removeTestLayeredProfile(id) + + lp := NewLayeredProfile(newTestLayeredProfileVersion(t, id, true)) + option := lp.wrapBoolOption(testLayeredOptionKey, func() bool { return false }) + + // A connection uses the layered profile. + lp.LockForUsage() + + // Meanwhile, an update waits for the write lock. + newTestLayeredProfileVersion(t, id, false) + updated := make(chan struct{}) + go func() { + defer close(updated) + lp.Update(nil, nil) + }() + // New read locks are refused as soon as a writer is waiting. + for lp.TryRLock() { + lp.RUnlock() + time.Sleep(time.Millisecond) + } + + // Using an option now must not block and return the value of the + // revision that is locked for usage. + result := make(chan bool, 1) + go func() { result <- option() }() + select { + case value := <-result: + if !value { + t.Error("option changed while the layered profile was locked for usage") + } + case <-time.After(10 * time.Second): + t.Fatal("option blocks while a read lock is held and an update is waiting") + } + + lp.UnlockForUsage() + <-updated + if option() { + t.Error("option was not updated") + } +} diff --git a/service/profile/profile.go b/service/profile/profile.go index 9efd12881..2fe477fe3 100644 --- a/service/profile/profile.go +++ b/service/profile/profile.go @@ -18,10 +18,11 @@ import ( "github.com/safing/portmaster/service/intel/filterlists" "github.com/safing/portmaster/service/profile/binmeta" "github.com/safing/portmaster/service/profile/endpoints" + "github.com/safing/portmaster/service/updates" ) // ProfileSource is the source of the profile. -type ProfileSource string //nolint:golint +type ProfileSource string // Profile Sources. const ( @@ -38,7 +39,7 @@ const ( ) // Profile is used to predefine a security profile for applications. -type Profile struct { //nolint:maligned // not worth the effort +type Profile struct { record.Base sync.RWMutex @@ -114,16 +115,16 @@ type Profile struct { //nolint:maligned // not worth the effort layeredProfile *LayeredProfile // Interpreted Data - configPerspective *config.Perspective - dataParsed bool - defaultAction uint8 - endpoints endpoints.Endpoints - serviceEndpoints endpoints.Endpoints - filterListsSet bool - filterListIDs []string - spnUsagePolicy endpoints.Endpoints - spnTransitHubPolicy endpoints.Endpoints - spnExitHubPolicy endpoints.Endpoints + configPerspective *config.Perspective + dataParsed bool + defaultAction uint8 + endpoints endpoints.Endpoints + serviceEndpoints endpoints.Endpoints + filterListsSet bool + filterListIDs []string + // filterListsPending is set if the filter lists of the profile could not + // be resolved, because the filter list index is not available yet. + filterListsPending atomic.Bool splitTunUsagePolicy endpoints.Endpoints // Lifecycle Management @@ -195,11 +196,18 @@ func (profile *Profile) parseConfig() error { list, ok = profile.configPerspective.GetAsStringArray(CfgOptionFilterListsKey) profile.filterListsSet = false + profile.filterListsPending.Store(false) if ok { profile.filterListIDs, err = filterlists.ResolveListIDs(list) - if err != nil { + switch { + case errors.Is(err, updates.ErrNotFound): + // The filter list index is not downloaded yet, e.g. on the first + // start. The profile is reloaded once it is there. + log.Debugf("profiles: filter list index not available yet for %s", profile.ScopedID()) + profile.filterListsPending.Store(true) + case err != nil: log.Warningf("profiles: failed to resolve filter list IDs: %s", err) - } else { + default: profile.filterListsSet = true } } @@ -213,33 +221,6 @@ func (profile *Profile) parseConfig() error { } } - list, ok = profile.configPerspective.GetAsStringArray(CfgOptionSPNUsagePolicyKey) - profile.spnUsagePolicy = nil - if ok { - profile.spnUsagePolicy, err = endpoints.ParseEndpoints(list) - if err != nil { - lastErr = err - } - } - - list, ok = profile.configPerspective.GetAsStringArray(CfgOptionTransitHubPolicyKey) - profile.spnTransitHubPolicy = nil - if ok { - profile.spnTransitHubPolicy, err = endpoints.ParseEndpoints(list) - if err != nil { - lastErr = err - } - } - - list, ok = profile.configPerspective.GetAsStringArray(CfgOptionExitHubPolicyKey) - profile.spnExitHubPolicy = nil - if ok { - profile.spnExitHubPolicy, err = endpoints.ParseEndpoints(list) - if err != nil { - lastErr = err - } - } - return lastErr } diff --git a/service/resolver/failing_test.go b/service/resolver/failing_test.go index 960b538c0..99fc38bb1 100644 --- a/service/resolver/failing_test.go +++ b/service/resolver/failing_test.go @@ -67,7 +67,7 @@ func TestOrderResolvers(t *testing.T) { func TestResolveAndCacheAsksFailingResolvers(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. // Runs first: it needs the online status, and the resolvers of the other // subtests do not answer the online check of the running module. - t.Run("failing resolver is not asked after a not found answer", func(t *testing.T) { + t.Run("failing resolver is not asked after a not found answer", func(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. // Special-use domains are tried on all local resolvers, and a "not // found" answer continues with the next one. healthyAddr, healthyQueries := startTestDNSServer(t, dns.RcodeNameError) @@ -96,7 +96,7 @@ func TestResolveAndCacheAsksFailingResolvers(t *testing.T) { //nolint:parallelte } }) - t.Run("failing resolver is not asked while a healthy one answers", func(t *testing.T) { + t.Run("failing resolver is not asked while a healthy one answers", func(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. healthyAddr, healthyQueries := startTestDNSServer(t, dns.RcodeSuccess) healthy := newTestResolver(healthyAddr) failingAddr, failingQueries := startTestDNSServer(t, dns.RcodeSuccess) @@ -123,7 +123,7 @@ func TestResolveAndCacheAsksFailingResolvers(t *testing.T) { //nolint:parallelte } }) - t.Run("failing resolver is asked after the healthy one does not answer", func(t *testing.T) { + t.Run("failing resolver is asked after the healthy one does not answer", func(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. healthyAddr, _ := startTestDNSServer(t, noReply) healthy := newTestResolver(healthyAddr) failingAddr, failingQueries := startTestDNSServer(t, dns.RcodeSuccess) @@ -146,7 +146,7 @@ func TestResolveAndCacheAsksFailingResolvers(t *testing.T) { //nolint:parallelte } }) - t.Run("only resolver is failing and answers", func(t *testing.T) { + t.Run("only resolver is failing and answers", func(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. addr, queries := startTestDNSServer(t, dns.RcodeSuccess) failing := newTestResolver(addr) markFailing(t, failing) @@ -167,7 +167,7 @@ func TestResolveAndCacheAsksFailingResolvers(t *testing.T) { //nolint:parallelte } }) - t.Run("only resolver is failing and does not answer", func(t *testing.T) { + t.Run("only resolver is failing and does not answer", func(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. addr, _ := startTestDNSServer(t, noReply) failing := newTestResolver(addr) markFailing(t, failing) @@ -200,14 +200,15 @@ func TestCheckFailingResolvers(t *testing.T) { //nolint:paralleltest // Replaces {"answers with SERVFAIL", dns.RcodeServerFailure, false}, {"does not answer", noReply, true}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { + for _, tt := range tests { //nolint:paralleltest // Subtests replace the global resolvers. + t.Run(tt.name, func(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. addr, _ := startTestDNSServer(t, tt.rcode) resolver := newTestResolver(addr) markFailing(t, resolver) useTestResolvers(t, resolver) - if err := module.mgr.Do("check failing resolvers", checkFailingResolvers); err != nil { + err := module.mgr.Do("check failing resolvers", checkFailingResolvers) + if err != nil { t.Fatalf("check failed: %s", err) } if got := resolver.Conn.IsFailing(); got != tt.wantFailing { @@ -298,17 +299,27 @@ func requireOnline(t *testing.T) { netenv.ConnectedToDNS.Set() t.Cleanup(func() { netenv.ConnectedToDNS.SetTo(wasConnected) }) - // A check that is already running returns its own, older result first. - // Check again until the result reflects the connected DNS. + // Trigger a new check and wait for its result. A check that is already + // running may report its own, older result first, and the trigger is queued + // for the next check then. Trigger again until the result reflects the + // connected DNS. + // + // Do not use netenv.CheckAndGetOnlineStatus here: it waits on a + // sync.WaitGroup that the online status worker adds to again right after a + // check when another trigger is queued. Waiting while it is reused is a + // data race and panics with "WaitGroup is reused before previous Wait has + // returned", seen with -race -count=50. deadline := time.Now().Add(30 * time.Second) for { - status := netenv.CheckAndGetOnlineStatus() + netenv.TriggerOnlineStatusInvestigation() + status := netenv.GetOnlineStatus() if status == netenv.StatusOnline { return } if time.Now().After(deadline) { t.Fatalf("expected online status %s, got %s", netenv.StatusOnline, status) } + time.Sleep(10 * time.Millisecond) } } @@ -337,7 +348,8 @@ func startTestDNSServer(t *testing.T, rcode int) (*net.UDPAddr, *atomic.Int32) { queries := new(atomic.Int32) if rcode == noReply { - if err := pc.Close(); err != nil { + err := pc.Close() + if err != nil { t.Fatalf("failed to close listener: %s", err) } return addr, queries @@ -365,7 +377,8 @@ func startTestDNSServer(t *testing.T, rcode int) (*net.UDPAddr, *atomic.Int32) { A: net.IPv4(127, 0, 0, 1), }) } - if err := w.WriteMsg(reply); err != nil { + err := w.WriteMsg(reply) + if err != nil { t.Errorf("failed to send reply: %s", err) } }), @@ -379,7 +392,8 @@ func startTestDNSServer(t *testing.T, rcode int) (*net.UDPAddr, *atomic.Int32) { t.Fatalf("failed to start test DNS server: %s", err) } t.Cleanup(func() { - if err := server.Shutdown(); err != nil { + err := server.Shutdown() + if err != nil { t.Errorf("failed to stop test DNS server: %s", err) } }) diff --git a/service/resolver/ipinfo.go b/service/resolver/ipinfo.go index 32cc0cc3b..2c8db1eea 100644 --- a/service/resolver/ipinfo.go +++ b/service/resolver/ipinfo.go @@ -2,12 +2,14 @@ package resolver import ( "fmt" + "net" "strings" "sync" "time" "github.com/safing/portmaster/base/database" "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/service/network/netutils" ) const ( @@ -132,6 +134,20 @@ func (info *IPInfo) AddDomain(resolved ResolvedDomain) { // Add new entry to the end. info.ResolvedDomains = append(info.ResolvedDomains, resolved) + + // Resolvers that follow a CNAME chain themselves (such as + // systemd-resolved) query the CNAME target directly after the requested + // domain. Keep the entry with the full chain as the most recent one, so + // that rules for the requested domain still apply to the connection. + if len(resolved.CNAMEs) == 0 { + for idx, d := range info.ResolvedDomains[:len(info.ResolvedDomains)-1] { + if len(d.CNAMEs) > 0 && d.CNAMEs[len(d.CNAMEs)-1] == resolved.Domain { + info.ResolvedDomains = append(info.ResolvedDomains[:idx], info.ResolvedDomains[idx+1:]...) + info.ResolvedDomains = append(info.ResolvedDomains, d) + break + } + } + } } // MostRecentDomain returns the most recent domain. @@ -147,8 +163,16 @@ func (info *IPInfo) MostRecentDomain() *ResolvedDomain { return &mostRecent } +// RecordDomainsFor reports whether domains resolved to ip should be recorded +// for naming connections to it. Localhost IPs are never recorded, nor are +// 0.0.0.0 and ::, which DNS filters answer for blocked names: connections to +// them would otherwise get the name of the last blocked domain. +func RecordDomainsFor(ip net.IP) bool { + return !ip.IsUnspecified() && netutils.GetIPScope(ip) != netutils.HostLocal +} + func makeIPInfoKey(profileID, ip string) string { - return fmt.Sprintf("cache:intel/ipInfo/%s/%s", profileID, ip) + return "cache:intel/ipInfo/" + profileID + "/" + ip } // GetIPInfo gets an IPInfo record from the database. diff --git a/service/resolver/ipinfo_test.go b/service/resolver/ipinfo_test.go index 61740c4d9..50b8542d1 100644 --- a/service/resolver/ipinfo_test.go +++ b/service/resolver/ipinfo_test.go @@ -1,6 +1,7 @@ package resolver import ( + "net" "testing" "github.com/stretchr/testify/assert" @@ -44,3 +45,47 @@ func TestIPInfo(t *testing.T) { info.AddDomain(subOverWrite) assert.Equal(t, ResolvedDomains{example, sub2Example, subOverWrite}, info.ResolvedDomains) } + +func TestIPInfoCNAMETargetQueriedDirectly(t *testing.T) { + t.Parallel() + + chain := ResolvedDomain{ + Domain: "tr.archive.ubuntu.com.", + CNAMEs: []string{"ftp.linux.org.tr."}, + } + target := ResolvedDomain{ + Domain: "ftp.linux.org.tr.", + } + other := ResolvedDomain{ + Domain: "other.example.", + } + + info := &IPInfo{IP: "193.140.98.183"} + info.AddDomain(other) + info.AddDomain(chain) + // The resolver follows the chain and queries the target on its own. + info.AddDomain(target) + + assert.Equal(t, ResolvedDomains{other, target, chain}, info.ResolvedDomains) + assert.Equal(t, chain.Domain, info.MostRecentDomain().Domain) + + // A different domain resolved later still becomes the most recent one. + info.AddDomain(other) + assert.Equal(t, other.Domain, info.MostRecentDomain().Domain) +} + +func TestRecordDomainsFor(t *testing.T) { + t.Parallel() + + for ip, want := range map[string]bool{ + "0.0.0.0": false, + "::": false, + "127.0.0.1": false, + "::1": false, + "93.184.216.34": true, + "192.168.1.10": true, + "2606:4700::6810": true, + } { + assert.Equal(t, want, RecordDomainsFor(net.ParseIP(ip)), ip) + } +} diff --git a/service/resolver/localhooks_race_test.go b/service/resolver/localhooks_race_test.go new file mode 100644 index 000000000..aa510b85e --- /dev/null +++ b/service/resolver/localhooks_race_test.go @@ -0,0 +1,63 @@ +package resolver + +import ( + "net" + "sync" + "testing" +) + +// TestLocalHooksSwapIsRaceFree swaps the package-level hooks while a +// goroutine, like a still running resolver query, keeps reading them. +func TestLocalHooksSwapIsRaceFree(t *testing.T) { //nolint:paralleltest // Replaces the package-level hooks. + prevHooks := localPortHooks.Load() + prevFactory := localAddrFactory.Load() + t.Cleanup(func() { + localPortHooks.Store(prevHooks) + localAddrFactory.Store(prevFactory) + }) + + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + for { + select { + case <-stop: + return + default: + } + authorizeLocalPort(networkUDP, 1) + releaseLocalPort(networkUDP, 1, false) + getLocalAddr(networkUDP) + } + }) + + for range 100000 { + localPortHooks.Store(&LocalPortHooks{Authorize: func(string, uint16) {}}) + factory := func(string) net.Addr { return nil } + localAddrFactory.Store(&factory) + } + close(stop) + wg.Wait() +} + +// TestSetLocalAddrFactoryOnce checks that the factory can be set once, and +// that setting no factory does not count. +func TestSetLocalAddrFactoryOnce(t *testing.T) { //nolint:paralleltest // Replaces the package-level factory. + prevFactory := localAddrFactory.Load() + t.Cleanup(func() { localAddrFactory.Store(prevFactory) }) + localAddrFactory.Store(nil) + + first := &net.UDPAddr{Port: 1} + second := &net.UDPAddr{Port: 2} + + SetLocalAddrFactory(nil) + if addr := getLocalAddr(networkUDP); addr != nil { + t.Fatalf("unexpected local address %v without a factory", addr) + } + + SetLocalAddrFactory(func(string) net.Addr { return first }) + SetLocalAddrFactory(func(string) net.Addr { return second }) + if addr := getLocalAddr(networkUDP); addr != first { + t.Fatalf("local address is %v, expected the one of the first factory", addr) + } +} diff --git a/service/resolver/main.go b/service/resolver/main.go index a338d8372..9d06d7b9b 100644 --- a/service/resolver/main.go +++ b/service/resolver/main.go @@ -91,28 +91,14 @@ func start() error { }, ) - // Force resolvers to reconnect when SPN has connected. - module.instance.GetEventSPNConnected().AddCallback( - "force resolver reconnect", - func(ctx *mgr.WorkerCtx, _ struct{}) (bool, error) { - ForceResolverReconnect(ctx.Ctx()) - return false, nil - }) - // reload after config change - prevNameservers := strings.Join(configuredNameServers(), " ") module.instance.Config().EventConfigChange.AddCallback( "update nameservers", - func(_ *mgr.WorkerCtx, _ struct{}) (bool, error) { - newNameservers := strings.Join(configuredNameServers(), " ") - if newNameservers != prevNameservers { - prevNameservers = newNameservers - - loadResolvers() - log.Debug("resolver: reloaded nameservers due to config change") - } - return false, nil - }) + newNameserverConfigChangeHandler( + func() []string { return configuredNameServers() }, + loadResolvers, + ), + ) // Check failing resolvers regularly and when the network changes. module.failingResolverWorkerMgr = module.mgr.NewWorkerMgr("check failing resolvers", checkFailingResolvers, nil) @@ -137,18 +123,20 @@ func start() error { return nil } -var localAddrFactory func(network string) net.Addr +var localAddrFactory atomic.Pointer[func(network string) net.Addr] // SetLocalAddrFactory supplies the intel package with a function to get permitted local addresses for connections. func SetLocalAddrFactory(laf func(network string) net.Addr) { - if localAddrFactory == nil { - localAddrFactory = laf + if laf == nil { + // Setting no factory leaves it unset, so that it can still be set. + return } + localAddrFactory.CompareAndSwap(nil, &laf) } func getLocalAddr(network string) net.Addr { - if localAddrFactory != nil { - return localAddrFactory(network) + if laf := localAddrFactory.Load(); laf != nil && *laf != nil { + return (*laf)(network) } return nil } @@ -168,26 +156,36 @@ type LocalPortHooks struct { // connection could not be established. If unusable is set, the port could // not be bound and is skipped by future port selection for a while. Release func(network string, port uint16, unusable bool) + // ClearUDPFlow drops state the OS keeps for an earlier flow with the same + // addresses as the new UDP socket, before the first packet is sent. + ClearUDPFlow func(local, remote *net.UDPAddr) } -var localPortHooks LocalPortHooks +var localPortHooks atomic.Pointer[LocalPortHooks] // SetLocalPortHooks supplies the resolver with hooks to pre-authenticate local ports. func SetLocalPortHooks(hooks LocalPortHooks) { - if localPortHooks.Authorize == nil && localPortHooks.Release == nil { - localPortHooks = hooks + current := localPortHooks.Load() + if current == nil || (current.Authorize == nil && current.Release == nil && current.ClearUDPFlow == nil) { + localPortHooks.CompareAndSwap(current, &hooks) } } func authorizeLocalPort(network string, port uint16) { - if localPortHooks.Authorize != nil { - localPortHooks.Authorize(network, port) + if hooks := localPortHooks.Load(); hooks != nil && hooks.Authorize != nil { + hooks.Authorize(network, port) } } func releaseLocalPort(network string, port uint16, unusable bool) { - if localPortHooks.Release != nil { - localPortHooks.Release(network, port, unusable) + if hooks := localPortHooks.Load(); hooks != nil && hooks.Release != nil { + hooks.Release(network, port, unusable) + } +} + +func clearUDPFlow(local, remote *net.UDPAddr) { + if hooks := localPortHooks.Load(); hooks != nil && hooks.ClearUDPFlow != nil { + hooks.ClearUDPFlow(local, remote) } } @@ -325,6 +323,31 @@ func New(instance instance) (*ResolverModule, error) { type instance interface { NetEnv() *netenv.NetEnv Config() *config.Config - GetEventSPNConnected() *mgr.EventMgr[struct{}] ShuttingDown() <-chan struct{} } + +// newNameserverConfigChangeHandler returns a config change callback that calls +// reload when the configured nameservers (as returned by getNameservers) +// changed since the last reload. +// Event callbacks run concurrently, so the check and the reload are serialized: +// otherwise a callback that read an older config could store it as the last +// state after a newer callback already reloaded, and a later change back to +// that older value would then be skipped. +func newNameserverConfigChangeHandler(getNameservers func() []string, reload func()) mgr.EventCallbackFunc[struct{}] { + var lock sync.Mutex + prevNameservers := strings.Join(getNameservers(), " ") + + return func(_ *mgr.WorkerCtx, _ struct{}) (bool, error) { + lock.Lock() + defer lock.Unlock() + + newNameservers := strings.Join(getNameservers(), " ") + if newNameservers != prevNameservers { + prevNameservers = newNameservers + + reload() + log.Debug("resolver: reloaded nameservers due to config change") + } + return false, nil + } +} diff --git a/service/resolver/main_test.go b/service/resolver/main_test.go index eea3f3d92..2d98f4433 100644 --- a/service/resolver/main_test.go +++ b/service/resolver/main_test.go @@ -1,15 +1,16 @@ package resolver import ( + "flag" "fmt" "os" "testing" + "time" "github.com/safing/portmaster/base/api" "github.com/safing/portmaster/base/config" "github.com/safing/portmaster/base/database/dbmodule" "github.com/safing/portmaster/service/core/base" - "github.com/safing/portmaster/service/mgr" "github.com/safing/portmaster/service/netenv" "github.com/safing/portmaster/service/ui" "github.com/safing/portmaster/service/updates" @@ -24,9 +25,6 @@ type testInstance struct { netenv *netenv.NetEnv } -func (stub *testInstance) GetEventSPNConnected() *mgr.EventMgr[struct{}] { - return mgr.NewEventMgr[struct{}]("spn connect", nil) -} func (stub *testInstance) IntelUpdates() *updates.Updater { return nil } func (stub *testInstance) Config() *config.Config { return stub.config } func (stub *testInstance) NetEnv() *netenv.NetEnv { return stub.netenv } @@ -49,6 +47,14 @@ func runTest(m *testing.M) error { } defer func() { _ = os.RemoveAll(_dataDir) }() + // The network-dependent tests (skipped with -short) need a more lenient + // request timeout. Set it here, before any module or test goroutine is + // started, as it is read concurrently by the resolvers. + flag.Parse() + if !testing.Short() { + defaultRequestTimeout = 30 * time.Second + } + // Set the default API listen address api.SetDefaultAPIListenAddress("0.0.0.0:8080") @@ -74,6 +80,14 @@ func runTest(m *testing.M) error { if err != nil { return fmt.Errorf("failed to create module: %w", err) } + // Do not resolve the DNS test query in the online status check. The check + // runs in the background whenever netenv triggers it and resolves through + // the global resolvers, which read the package-level local address and + // port hooks that tests replace without synchronization. The check then + // skips the DNS query and reports the remaining checks only. This must + // happen before netenv starts its online status worker. + netenv.DNSTestQueryFunc = nil + err = stub.db.Start() if err != nil { return fmt.Errorf("Failed to start database: %w", err) @@ -95,6 +109,12 @@ func runTest(m *testing.M) error { return fmt.Errorf("Failed to start module: %w", err) } + // Stop the regular check of failing resolvers. Its first run starts with + // the module and, on a loaded machine, may only get to the resolver list + // after a test replaced it. It then asks the test's failing resolvers and + // clears their failing state. Tests that need the check run it themselves. + module.failingResolverWorkerMgr.Stop() + m.Run() return nil } diff --git a/service/resolver/namerecord.go b/service/resolver/namerecord.go index 075b53287..96e57ddc4 100644 --- a/service/resolver/namerecord.go +++ b/service/resolver/namerecord.go @@ -5,6 +5,9 @@ import ( "errors" "fmt" "sync" + "sync/atomic" + + "github.com/miekg/dns" "github.com/safing/portmaster/base/api" "github.com/safing/portmaster/base/database" @@ -50,6 +53,21 @@ type NameRecord struct { Expires int64 Resolver *ResolverInfo + + // parsed holds the parsed resource records of Answer, Ns and Extra. It is + // set by GetRRCache when all entries could be parsed, so that a record + // served again from the database cache does not need to be parsed again. + // A NameRecord is not changed after it is created, so the parsed records + // stay in sync with the string entries. The parsed records are never + // handed out, only copies of them. + parsed atomic.Pointer[parsedNameRecord] +} + +// parsedNameRecord holds the parsed resource records of a NameRecord. +type parsedNameRecord struct { + answer []dns.RR + ns []dns.RR + extra []dns.RR } // IsValid returns whether the NameRecord is valid and may be used. Otherwise, diff --git a/service/resolver/nameserver_config_test.go b/service/resolver/nameserver_config_test.go new file mode 100644 index 000000000..285105b04 --- /dev/null +++ b/service/resolver/nameserver_config_test.go @@ -0,0 +1,81 @@ +package resolver + +import ( + "sync/atomic" + "testing" + "time" +) + +// TestNameserverConfigChangeHandlerConcurrent checks that the resolvers end up +// loaded with the configured nameservers when config change callbacks run +// concurrently, as they do when the EventMgr runs each callback in its own +// worker. +func TestNameserverConfigChangeHandlerConcurrent(t *testing.T) { + t.Parallel() + + var ( + configured atomic.Value // string: currently configured nameservers + loaded atomic.Value // string: nameservers used by the last reload + + // When set, the next config read is held up until released, + // simulating a callback that is preempted right after reading. + blockNextRead atomic.Bool + blocked = make(chan struct{}) + release = make(chan struct{}) + ) + configured.Store("X") + loaded.Store("X") + + getNameservers := func() []string { + v, _ := configured.Load().(string) + if blockNextRead.CompareAndSwap(true, false) { + close(blocked) + <-release + } + return []string{v} + } + reload := func() { + // loadResolvers reads the current config itself. + loaded.Store(configured.Load()) + } + + handler := newNameserverConfigChangeHandler(getNameservers, reload) + call := func() <-chan struct{} { + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = handler(nil, struct{}{}) + }() + return done + } + + // Change X -> Y: the callback reads Y and is then held up. + configured.Store("Y") + blockNextRead.Store(true) + first := call() + <-blocked + + // Change Y -> Z while the first callback is still running. + configured.Store("Z") + second := call() + select { + case <-second: + case <-time.After(200 * time.Millisecond): + // The second callback waits for the first one. + } + + // Let the first callback finish, then wait for both. + close(release) + <-first + <-second + + // Change Z -> Y. + configured.Store("Y") + <-call() + + got, _ := loaded.Load().(string) + want, _ := configured.Load().(string) + if got != want { + t.Fatalf("resolvers loaded with nameservers %q, but %q are configured", got, want) + } +} diff --git a/service/resolver/resolve_bench_test.go b/service/resolver/resolve_bench_test.go new file mode 100644 index 000000000..7d59ca836 --- /dev/null +++ b/service/resolver/resolve_bench_test.go @@ -0,0 +1,171 @@ +package resolver + +import ( + "context" + "fmt" + "net" + "testing" + "time" + + "github.com/miekg/dns" +) + +// benchActiveResolver returns an active resolver, so that cached entries pass +// the resolver check in checkCache. +func benchActiveResolver(b *testing.B) *Resolver { + b.Helper() + + resolversLock.RLock() + defer resolversLock.RUnlock() + for _, r := range globalResolvers { + if _, ok := activeResolvers[r.Info.ID()]; ok { + return r + } + } + b.Skip("no active resolver configured") + return nil +} + +// benchRRCache returns a typical answer: a CNAME followed by several A or AAAA +// records. +func benchRRCache(domain string, qtype uint16, resolver *Resolver) *RRCache { + rrCache := &RRCache{ + Domain: domain, + Question: dns.Type(qtype), + RCode: dns.RcodeSuccess, + Resolver: resolver.Info.Copy(), + } + target := "edge." + domain + rrCache.Answer = append(rrCache.Answer, &dns.CNAME{ + Hdr: dns.RR_Header{Name: domain, Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: 300}, + Target: target, + }) + for i := range 4 { + hdr := dns.RR_Header{Name: target, Rrtype: qtype, Class: dns.ClassINET, Ttl: 300} + if qtype == dns.TypeAAAA { + rrCache.Answer = append(rrCache.Answer, &dns.AAAA{Hdr: hdr, AAAA: net.ParseIP(fmt.Sprintf("2001:db8::%d", i+1))}) + } else { + rrCache.Answer = append(rrCache.Answer, &dns.A{Hdr: hdr, A: net.IPv4(192, 0, 2, byte(i+1))}) + } + } + rrCache.Expires = time.Now().Add(time.Hour).Unix() + return rrCache +} + +func benchQueries(b *testing.B, n int) []*Query { + b.Helper() + + resolver := benchActiveResolver(b) + queries := make([]*Query, 0, n) + for i := range n { + qtype := dns.TypeA + if i%2 == 1 { + qtype = dns.TypeAAAA + } + domain := fmt.Sprintf("bench-%d.cachehit.example.com.", i) + err := benchRRCache(domain, qtype, resolver).Save() + if err != nil { + b.Fatal(err) + } + queries = append(queries, &Query{FQDN: domain, QType: dns.Type(qtype)}) + } + return queries +} + +// BenchmarkResolveCacheHit measures a cache hit through Resolve, including the +// conversion to a reply, as the nameserver does for every cached answer. +// Several domains are queried in turn, as a single repeated query triggers the +// cache reset of shouldResetCache. +func BenchmarkResolveCacheHit(b *testing.B) { + queries := benchQueries(b, 64) + ctx := context.Background() + request := new(dns.Msg) + + b.ReportAllocs() + b.ResetTimer() + for i := 0; b.Loop(); i++ { + q := queries[i%len(queries)] + rrCache, err := Resolve(ctx, &Query{FQDN: q.FQDN, QType: q.QType}) + if err != nil { + b.Fatal(err) + } + if !rrCache.ServedFromCache || len(rrCache.Answer) != 5 { + b.Fatalf("unexpected cache result: fromCache=%v answers=%d", rrCache.ServedFromCache, len(rrCache.Answer)) + } + request.SetQuestion(q.FQDN, uint16(q.QType)) + reply := rrCache.ReplyWithDNS(ctx, request) + reply.Extra = append(reply.Extra, rrCache.GetExtraRRs(ctx, request)...) + _ = rrCache.ToDNSRequestContext() + } +} + +// BenchmarkGetRRCache measures loading a cached entry and converting it from +// a NameRecord to an RRCache. +func BenchmarkGetRRCache(b *testing.B) { + queries := benchQueries(b, 64) + + b.ReportAllocs() + b.ResetTimer() + for i := 0; b.Loop(); i++ { + q := queries[i%len(queries)] + rrCache, err := GetRRCache(q.FQDN, q.QType) + if err != nil { + b.Fatal(err) + } + if len(rrCache.Answer) != 5 { + b.Fatal("unexpected answer count") + } + } +} + +// BenchmarkRRCacheSave measures saving a freshly resolved entry. +func BenchmarkRRCacheSave(b *testing.B) { + resolver := benchActiveResolver(b) + caches := make([]*RRCache, 64) + for i := range caches { + caches[i] = benchRRCache(fmt.Sprintf("bench-%d.save.example.com.", i), dns.TypeA, resolver) + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; b.Loop(); i++ { + err := caches[i%len(caches)].Save() + if err != nil { + b.Fatal(err) + } + } +} + +// BenchmarkIPInfoUpdate measures the IPInfo update done for every resolved +// address of a DNS answer (see firewall.SaveIPsInCache): get, add the domain +// and save. +func BenchmarkIPInfoUpdate(b *testing.B) { + resolver := benchActiveResolver(b) + rrCache := benchRRCache("ipinfo.example.com.", dns.TypeA, resolver) + record := ResolvedDomain{ + Domain: rrCache.Domain, + CNAMEs: []string{"edge.ipinfo.example.com."}, + Resolver: rrCache.Resolver, + DNSRequestContext: rrCache.ToDNSRequestContext(), + Expires: rrCache.Expires, + } + ips := make([]string, 64) + for i := range ips { + ips[i] = net.IPv4(198, 51, 100, byte(i)).String() + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; b.Loop(); i++ { + ip := ips[i%len(ips)] + info, err := GetIPInfo("bench-profile", ip) + if err != nil { + info = &IPInfo{IP: ip, ProfileID: "bench-profile"} + } + info.AddDomain(record) + err = info.Save() + if err != nil { + b.Fatal(err) + } + } +} diff --git a/service/resolver/resolver-mdns.go b/service/resolver/resolver-mdns.go index 5577d431a..dc45cabcd 100644 --- a/service/resolver/resolver-mdns.go +++ b/service/resolver/resolver-mdns.go @@ -29,6 +29,9 @@ var ( multicast6Conn *net.UDPConn unicast4Conn *net.UDPConn unicast6Conn *net.UDPConn + // unicastConnsLock locks unicast4Conn and unicast6Conn, which are set by + // the mDNS listener and used by queries. + unicastConnsLock sync.RWMutex questions = make(map[uint16]*savedQuestion) questionsLock sync.Mutex @@ -97,7 +100,9 @@ func listenToMDNS(wc *mgr.WorkerCtx) error { }() } + unicastConnsLock.Lock() unicast4Conn, err = net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0}) + unicastConnsLock.Unlock() if err != nil { // TODO: retry after some time log.Warningf("intel(mdns): failed to create udp4 listen socket: %s", err) @@ -124,7 +129,9 @@ func listenToMDNS(wc *mgr.WorkerCtx) error { }() } + unicastConnsLock.Lock() unicast6Conn, err = net.ListenUDP("udp6", &net.UDPAddr{IP: net.IPv6zero, Port: 0}) + unicastConnsLock.Unlock() if err != nil { // TODO: retry after some time log.Warningf("intel(mdns): failed to create udp6 listen socket: %s", err) @@ -378,6 +385,11 @@ func listenForDNSPackets(ctx context.Context, conn *net.UDPConn, messages chan * } func queryMulticastDNS(ctx context.Context, q *Query) (*RRCache, error) { + // get connections + unicastConnsLock.RLock() + unicast4Conn, unicast6Conn := unicast4Conn, unicast6Conn + unicastConnsLock.RUnlock() + // check for active connections if unicast4Conn == nil && unicast6Conn == nil { return nil, errors.New("unicast mdns connections not initialized") diff --git a/service/resolver/resolver-mdns_test.go b/service/resolver/resolver-mdns_test.go new file mode 100644 index 000000000..042f7babe --- /dev/null +++ b/service/resolver/resolver-mdns_test.go @@ -0,0 +1,101 @@ +package resolver + +import ( + "net" + "strings" + "testing" + "time" + + "github.com/miekg/dns" +) + +// TestMDNSQueryReceivesResponse checks that a mDNS response is handed to the +// waiting query right away, instead of the query running into its timeout. +// Run with -race: queries use the unicast connections set up by the mDNS +// listener worker. +func TestMDNSQueryReceivesResponse(t *testing.T) { + t.Parallel() + + ctx := t.Context() + + // Run a separate message handler, so that we can inject a response. + messages := make(chan *dns.Msg) + go func() { + _ = handleMDNSMessages(ctx, messages) + }() + + q := &Query{ + FQDN: "portmaster-mdns-test.local.", + QType: dns.Type(dns.TypeA), + } + + type queryResult struct { + rrCache *RRCache + err error + took time.Duration + } + resultCh := make(chan queryResult, 1) + started := time.Now() + go func() { + rrCache, err := queryMulticastDNS(ctx, q) + resultCh <- queryResult{rrCache, err, time.Since(started)} + }() + + // Answer the query, like a mDNS responder on the network would, until the + // query returns. + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case res := <-resultCh: + if res.err != nil { + if strings.Contains(res.err.Error(), "not initialized") || + strings.Contains(res.err.Error(), "failed to send query") { + t.Skipf("mDNS not available here: %s", res.err) + } + t.Fatal(res.err) + } + if res.rrCache.RCode != dns.RcodeSuccess || len(res.rrCache.Answer) == 0 { + t.Fatalf("unexpected result: rcode=%d answers=%d", res.rrCache.RCode, len(res.rrCache.Answer)) + } + // The query waits 1s for a response before falling back to the cache. + if res.took > 900*time.Millisecond { + t.Fatalf("query took %s although a response was available immediately", res.took) + } + return + + case <-ticker.C: + var ( + id uint16 + found bool + ) + questionsLock.Lock() + for msgID, savedQ := range questions { + if savedQ.question.Name == q.FQDN { + id = msgID + found = true + } + } + questionsLock.Unlock() + if !found { + continue + } + + reply := new(dns.Msg) + reply.Id = id + reply.Response = true + reply.Answer = []dns.RR{&dns.A{ + Hdr: dns.RR_Header{Name: q.FQDN, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, + A: net.IPv4(192, 168, 1, 1), + }} + select { + case messages <- reply: + case <-time.After(time.Second): + t.Fatal("message handler is stuck") + } + + case <-time.After(5 * time.Second): + t.Fatal("query did not return") + } + } +} diff --git a/service/resolver/resolver-plain.go b/service/resolver/resolver-plain.go index 024a83808..2464df1f7 100644 --- a/service/resolver/resolver-plain.go +++ b/service/resolver/resolver-plain.go @@ -19,6 +19,12 @@ var ( defaultRequestTimeout = 3 * time.Second // dns query defaultConnectTimeout = 5 * time.Second // tcp/tls maxRequestTimeout = 5 * time.Second + + // plainRetransmitInterval is the time after which a plain UDP query is + // sent again if no reply arrived, as stub resolvers do (RFC 1035 4.2.1). + // A single lost packet would otherwise fail the query after the full + // request timeout. + plainRetransmitInterval = 1 * time.Second ) var errUnexpectedLocalAddr = errors.New("unexpected local address of udp connection") @@ -135,9 +141,86 @@ func (pr *PlainResolver) exchange(ctx context.Context, dnsClient *dns.Client, dn } localPort := uint16(localAddr.Port) //nolint:gosec // Ports of net.Addr are within the uint16 range. authorizeLocalPort(networkUDP, localPort) + // The OS may hand out the port of a recently closed socket, whose query to + // the same server was redirected to the Portmaster nameserver. Its + // conntrack entry would redirect this query back to Portmaster itself. + if remoteAddr, ok := rawConn.RemoteAddr().(*net.UDPAddr); ok { + clearUDPFlow(localAddr, remoteAddr) + } // The first packet consumes the pre-authentication. Release it afterwards // in case no packet was sent, which is a no-op otherwise. defer releaseLocalPort(networkUDP, localPort, false) - return dnsClient.ExchangeWithConnContext(ctx, dnsQuery, conn) + return exchangeWithRetransmit(ctx, conn, dnsQuery, dnsClient.Timeout, plainRetransmitInterval) +} + +// exchangeWithRetransmit sends query over the UDP conn and waits for the +// reply. If none arrives within retransmitAfter, the query is sent again on +// the same socket, until timeout (and the context deadline) is reached. +// Replies to an earlier transmission are equally valid, as they have the same +// ID. A zero timeout means the default request timeout. +func exchangeWithRetransmit(ctx context.Context, conn *dns.Conn, query *dns.Msg, timeout, retransmitAfter time.Duration) (*dns.Msg, time.Duration, error) { + started := time.Now() + if timeout <= 0 { + timeout = defaultRequestTimeout + } + deadline := started.Add(timeout) + if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) { + deadline = ctxDeadline + } + + // Abort a pending read when the context is canceled. + stop := context.AfterFunc(ctx, func() { + _ = conn.SetReadDeadline(time.Now()) + }) + defer stop() + + for { + err := conn.SetWriteDeadline(deadline) + if err != nil { + return nil, time.Since(started), err + } + err = conn.WriteMsg(query) + if err != nil { + return nil, time.Since(started), err + } + + readUntil := time.Now().Add(retransmitAfter) + if readUntil.After(deadline) { + readUntil = deadline + } + reply, err := readReply(conn, query.Id, readUntil) + switch { + case err == nil: + return reply, time.Since(started), nil + case ctx.Err() != nil: + return nil, time.Since(started), ctx.Err() + case !isTimeout(err) || !time.Now().Before(deadline): + return nil, time.Since(started), err + } + } +} + +// readReply reads from conn until a message with the given ID arrives or the +// deadline passes. Messages with other IDs (late replies to other queries) +// are skipped. +func readReply(conn *dns.Conn, id uint16, deadline time.Time) (*dns.Msg, error) { + err := conn.SetReadDeadline(deadline) + if err != nil { + return nil, err + } + for { + reply, err := conn.ReadMsg() + if err != nil { + return nil, err + } + if reply.Id == id { + return reply, nil + } + } +} + +func isTimeout(err error) bool { + var netErr net.Error + return errors.As(err, &netErr) && netErr.Timeout() } diff --git a/service/resolver/resolver-plain_retransmit_test.go b/service/resolver/resolver-plain_retransmit_test.go new file mode 100644 index 000000000..f3bc07f3e --- /dev/null +++ b/service/resolver/resolver-plain_retransmit_test.go @@ -0,0 +1,154 @@ +package resolver + +import ( + "context" + "errors" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/miekg/dns" +) + +// startScriptedDNSServer listens on a loopback UDP port and calls respond for +// every query it receives, with the number of the query (starting at 1). It +// sends whatever respond returns; nil sends nothing. +func startScriptedDNSServer(t *testing.T, respond func(n int, query *dns.Msg) []*dns.Msg) (addr string, queries *atomic.Int32) { + t.Helper() + + pc, err := net.ListenPacket("udp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("failed to listen: %s", err) + } + t.Cleanup(func() { _ = pc.Close() }) + + queries = new(atomic.Int32) + go func() { + buf := make([]byte, dns.MinMsgSize) + for { + n, from, err := pc.ReadFrom(buf) + if err != nil { + return // Closed by the cleanup. + } + query := new(dns.Msg) + err = query.Unpack(buf[:n]) + if err != nil { + continue + } + for _, reply := range respond(int(queries.Add(1)), query) { + packed, err := reply.Pack() + if err != nil { + continue + } + _, _ = pc.WriteTo(packed, from) + } + } + }() + + return pc.LocalAddr().String(), queries +} + +func dialTestConn(t *testing.T, addr string) *dns.Conn { + t.Helper() + + rawConn, err := net.Dial(networkUDP, addr) + if err != nil { + t.Fatalf("failed to dial: %s", err) + } + t.Cleanup(func() { _ = rawConn.Close() }) + return &dns.Conn{Conn: rawConn, UDPSize: 1024} +} + +func testQuery() *dns.Msg { + query := new(dns.Msg) + query.SetQuestion("example.com.", dns.TypeA) + return query +} + +func TestExchangeRetransmitsLostQuery(t *testing.T) { + t.Parallel() + + // Drop the first query, answer the second. + addr, queries := startScriptedDNSServer(t, func(n int, query *dns.Msg) []*dns.Msg { + if n == 1 { + return nil + } + return []*dns.Msg{new(dns.Msg).SetReply(query)} + }) + conn := dialTestConn(t, addr) + + query := testQuery() + reply, _, err := exchangeWithRetransmit(context.Background(), conn, query, 2*time.Second, 100*time.Millisecond) + if err != nil { + t.Fatalf("exchange failed: %s", err) + } + if reply.Id != query.Id { + t.Errorf("reply has ID %d, expected %d", reply.Id, query.Id) + } + if got := queries.Load(); got != 2 { + t.Errorf("server received %d queries, expected 2", got) + } +} + +func TestExchangeSkipsRepliesWithOtherIDs(t *testing.T) { + t.Parallel() + + // Send a stale reply with another ID before the real one. + addr, _ := startScriptedDNSServer(t, func(_ int, query *dns.Msg) []*dns.Msg { + stale := new(dns.Msg).SetReply(query) + stale.Id = query.Id + 1 + stale.Rcode = dns.RcodeServerFailure + return []*dns.Msg{stale, new(dns.Msg).SetReply(query)} + }) + conn := dialTestConn(t, addr) + + query := testQuery() + reply, _, err := exchangeWithRetransmit(context.Background(), conn, query, 2*time.Second, time.Second) + if err != nil { + t.Fatalf("exchange failed: %s", err) + } + if reply.Id != query.Id || reply.Rcode != dns.RcodeSuccess { + t.Errorf("got reply with ID %d and rcode %d, expected ID %d and success", reply.Id, reply.Rcode, query.Id) + } +} + +func TestExchangeTimesOutAfterRetransmits(t *testing.T) { + t.Parallel() + + addr, queries := startScriptedDNSServer(t, func(int, *dns.Msg) []*dns.Msg { return nil }) + conn := dialTestConn(t, addr) + + started := time.Now() + _, _, err := exchangeWithRetransmit(context.Background(), conn, testQuery(), 350*time.Millisecond, 100*time.Millisecond) + took := time.Since(started) + if !isTimeout(err) { + t.Fatalf("expected a timeout error, got %v", err) + } + if took < 300*time.Millisecond || took > 2*time.Second { + t.Errorf("exchange took %s, expected about 350ms", took) + } + // Sent at 0, 100, 200 and 300ms; allow for a slow scheduler. + if got := queries.Load(); got < 3 { + t.Errorf("server received %d queries, expected at least 3", got) + } +} + +func TestExchangeStopsOnContextCancel(t *testing.T) { + t.Parallel() + + addr, _ := startScriptedDNSServer(t, func(int, *dns.Msg) []*dns.Msg { return nil }) + conn := dialTestConn(t, addr) + + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(100*time.Millisecond, cancel) + + started := time.Now() + _, _, err := exchangeWithRetransmit(ctx, conn, testQuery(), 5*time.Second, time.Second) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if took := time.Since(started); took > time.Second { + t.Errorf("exchange took %s after the cancel", took) + } +} diff --git a/service/resolver/resolver-plain_test.go b/service/resolver/resolver-plain_test.go index a10188dbd..3a972fc87 100644 --- a/service/resolver/resolver-plain_test.go +++ b/service/resolver/resolver-plain_test.go @@ -27,8 +27,8 @@ func TestPlainResolverPreAuthenticatesBoundPort(t *testing.T) { //nolint:paralle authorized = make(map[uint16]string) // port -> network released = make(map[uint16]bool) // port -> marked unusable ) - previousHooks := localPortHooks - localPortHooks = LocalPortHooks{ + previousHooks := localPortHooks.Load() + localPortHooks.Store(&LocalPortHooks{ Authorize: func(network string, port uint16) { hooksLock.Lock() defer hooksLock.Unlock() @@ -39,8 +39,8 @@ func TestPlainResolverPreAuthenticatesBoundPort(t *testing.T) { //nolint:paralle defer hooksLock.Unlock() released[port] = unusable }, - } - t.Cleanup(func() { localPortHooks = previousHooks }) + }) + t.Cleanup(func() { localPortHooks.Store(previousHooks) }) // Query the local server through the plain resolver. pr := NewPlainResolver(&Resolver{ diff --git a/service/resolver/resolver-tcp.go b/service/resolver/resolver-tcp.go index fb436e718..24b001bad 100644 --- a/service/resolver/resolver-tcp.go +++ b/service/resolver/resolver-tcp.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "net" + "sync/atomic" "time" "github.com/miekg/dns" @@ -40,6 +41,21 @@ type TCPResolver struct { resolverConn *tcpResolverConn // resolverConnInstanceID holds the current ID of the resolverConn. resolverConnInstanceID int + // heartbeatTimeout defines how long the connection may take to respond + // to an alive check before it is replaced. + heartbeatTimeout time.Duration + // clientTTL defines after which time a connection is recycled. + clientTTL time.Duration + // dialSlot is held while a new connection is established, so that + // concurrent queries share one new connection instead of each dialing + // their own. It is a channel, so that waiting can be canceled. + dialSlot chan struct{} + // dialCount counts the completed attempts to establish a connection. + dialCount int + // dialErr holds the error of the last attempt to establish a connection, + // if the server could not be reached. Queries that waited for this + // attempt fail with it instead of each dialing again. + dialErr error } // tcpResolverConn represents a single connection to an upstream DNS server. @@ -60,17 +76,48 @@ type tcpResolverConn struct { responses chan *dns.Msg // inFlightQueries holds all in-flight queries of this connection. inFlightQueries map[uint16]*tcpQuery + // inFlightTimeout defines after which time unanswered in-flight queries + // are removed from inFlightQueries. + inFlightTimeout time.Duration + // ttl defines after which time the connection is recycled. + // Zero means defaultClientTTL. + ttl time.Duration // heartbeat is a alive-checking channel from which the resolver conn must // always read asap. heartbeat chan struct{} // abandoned signifies if the resolver conn has been abandoned. abandoned *abool.AtomicBool + // stopped is closed when the handler has stopped. Queries are not taken + // anymore then, and the response channels of all in-flight queries are + // already closed. + stopped chan struct{} } +// errTCPConnStopped is returned when the connection stopped before it took +// the query. The query was not sent and may be retried on a new connection. +var errTCPConnStopped = fmt.Errorf("%w: connection stopped before sending the query", ErrFailure) + // tcpQuery holds the query information for a tcpResolverConn. type tcpQuery struct { - Query *Query + Query *Query + // Response receives the reply. It holds one reply, so that the handler + // never blocks on it and the reply is not lost when it arrives before + // the query waits for it. Response chan *dns.Msg + // settled is set by whoever is first: the handler when it delivers the + // reply, or the query when it stops waiting. A reply that arrives after + // the query stopped waiting is cached instead. + settled atomic.Bool + // expires is set when the query is sent and is only used by the handler. + expires time.Time +} + +// newTCPQuery returns a new tcpQuery for the given query. +func newTCPQuery(q *Query) *tcpQuery { + return &tcpQuery{ + Query: q, + Response: make(chan *dns.Msg, 1), + } } // MakeCacheRecord creates an RRCache record from a reply. @@ -86,6 +133,25 @@ func (tq *tcpQuery) MakeCacheRecord(reply *dns.Msg, resolverInfo *ResolverInfo) } } +// deliver hands the reply to the waiting query. It never blocks. It returns +// false if the query stopped waiting. +func (tq *tcpQuery) deliver(reply *dns.Msg) bool { + if !tq.settled.CompareAndSwap(false, true) { + return false + } + tq.Response <- reply + return true +} + +// stopWaiting marks the query as no longer waiting for the reply. If the +// reply was delivered already, it is returned. +func (tq *tcpQuery) stopWaiting() *dns.Msg { + if tq.settled.CompareAndSwap(false, true) { + return nil + } + return <-tq.Response +} + // NewTCPResolver returns a new TPCResolver. func NewTCPResolver(resolver *Resolver) *TCPResolver { newResolver := &TCPResolver{ @@ -97,6 +163,9 @@ func NewTCPResolver(resolver *Resolver) *TCPResolver { Timeout: defaultConnectTimeout, WriteTimeout: tcpWriteTimeout, }, + heartbeatTimeout: heartbeatTimeout, + clientTTL: defaultClientTTL, + dialSlot: make(chan struct{}, 1), } newResolver.BasicResolverConn.init() return newResolver @@ -122,6 +191,7 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve existingConn = tr.resolverConn } seenInstanceID := tr.resolverConnInstanceID + seenDialCount := tr.dialCount tr.Unlock() // Check if we have a resolver. @@ -130,8 +200,13 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve select { case existingConn.heartbeat <- struct{}{}: return existingConn, nil - case <-time.After(heartbeatTimeout): + case <-existingConn.stopped: + // The connection stopped after it was checked above. Create a new one. + case <-time.After(tr.heartbeatTimeout): log.Warningf("resolver: heartbeat for dns client %s failed", tr.resolver.Info.DescriptiveName()) + // Abandon the connection, so that it is shut down once it handled + // its in-flight queries, as it is replaced by a new one below. + existingConn.abandoned.Set() case <-ctx.Done(): return nil, ctx.Err() case <-module.mgr.Done(): @@ -148,6 +223,41 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve } } + // Establish only one new connection at a time. Concurrent queries wait + // for it and use it. + select { + case tr.dialSlot <- struct{}{}: + defer func() { <-tr.dialSlot }() + case <-ctx.Done(): + return nil, ctx.Err() + case <-module.mgr.Done(): + return nil, ErrShuttingDown + } + + // Use the connection another query created while this one was waiting. + // If another query failed to reach the server meanwhile, fail with its + // error instead of dialing again, so that waiting queries do not each + // wait for a dial to time out, one after another. + var sharedDialErr error + tr.Lock() + if tr.resolverConn != nil && + tr.resolverConnInstanceID != seenInstanceID && + tr.resolverConn.abandoned.IsNotSet() { + existingConn = tr.resolverConn + } else { + existingConn = nil + if tr.dialCount != seenDialCount { + sharedDialErr = tr.dialErr + } + } + tr.Unlock() + if existingConn != nil { + return existingConn, nil + } + if sharedDialErr != nil { + return nil, sharedDialErr + } + // Do not dial a new upstream connection once the instance has started // shutting down. The instance shuts down before this module does, and // once interception has stopped a new connection could be pended by the @@ -165,15 +275,12 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve // Nothing left the host if the local port could not be bound. Do not // count this against the resolver or the network. if errors.Is(err, ErrLocalBind) { - // Concurrent queries dial at the same time. Use the connection - // another one has created in the meantime, if there is one. + // Do not share this failure: queries waiting for this dial try + // other local ports themselves. tr.Lock() - newConn := tr.resolverConn - newInstanceID := tr.resolverConnInstanceID + tr.dialCount++ + tr.dialErr = nil tr.Unlock() - if newConn != nil && newInstanceID != seenInstanceID && newConn.abandoned.IsNotSet() { - return newConn, nil - } return nil, err } @@ -181,7 +288,19 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve netenv.ReportFailedConnection() log.Debugf("resolver: failed to connect to %s: %s", tr.resolver.Info.DescriptiveName(), err) - return nil, fmt.Errorf("%w: failed to connect to %s: %w", ErrFailure, tr.resolver.Info.DescriptiveName(), err) + err = fmt.Errorf("%w: failed to connect to %s: %w", ErrFailure, tr.resolver.Info.DescriptiveName(), err) + + // Fail the queries waiting for this dial with the same error, unless + // the dial was ended by the context of this query. They dial + // themselves then. + tr.Lock() + tr.dialCount++ + tr.dialErr = nil + if ctx.Err() == nil { + tr.dialErr = err + } + tr.Unlock() + return nil, err } // Hint network environment at successful connection. @@ -196,6 +315,8 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve // Thread-safe resolverConn creation. tr.Lock() defer tr.Unlock() + tr.dialCount++ + tr.dialErr = nil // Create resolver connection. tr.resolverConnInstanceID++ @@ -206,8 +327,13 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve queries: make(chan *tcpQuery, 10), responses: make(chan *dns.Msg, 10), inFlightQueries: make(map[uint16]*tcpQuery, 10), + // Query() gives up waiting for a reply after defaultRequestTimeout. + // Keep unanswered queries a bit longer in order to still cache late replies. + inFlightTimeout: 2 * defaultRequestTimeout, + ttl: tr.clientTTL, heartbeat: make(chan struct{}), abandoned: abool.New(), + stopped: make(chan struct{}), } // Start worker. @@ -223,21 +349,61 @@ func (tr *TCPResolver) getOrCreateResolverConn(ctx context.Context) (*tcpResolve func (tr *TCPResolver) Query(ctx context.Context, q *Query) (*RRCache, error) { queryStarted := time.Now() - // Get resolver connection. - resolverConn, err := tr.getOrCreateResolverConn(ctx) + // The connection may stop right after it was handed out to this query, + // e.g. when it is recycled. Send the query on a new connection then. + tq := newTCPQuery(q) + reply, err := tr.query(ctx, tq) + if errors.Is(err, errTCPConnStopped) { + tq = newTCPQuery(q) + reply, err = tr.query(ctx, tq) + } if err != nil { return nil, err } - // Create query request. - tq := &tcpQuery{ - Query: q, - Response: make(chan *dns.Msg), + // Check if the reply was blocked upstream. + if tr.resolver.IsBlockedUpstream(reply) { + return nil, &BlockedUpstreamError{tr.resolver.Info.DescriptiveName()} + } + + // Report request duration for metrics. + reportRequestDuration(queryStarted, tr.resolver) + + // Create RRCache from reply and return it. + return tq.MakeCacheRecord(reply, tr.resolver.Info), nil +} + +// ForceReconnect forces the resolver to re-establish the connection to the server. +func (tr *TCPResolver) ForceReconnect(ctx context.Context) { + tr.Lock() + defer tr.Unlock() + + // Do nothing if no connection is available. + if tr.resolverConn == nil { + return + } + + // Set the abandoned to force a new connection on next request. + // This will leave the previous connection and handler running until all requests are handled. + tr.resolverConn.abandoned.Set() + + log.Tracer(ctx).Tracef("resolver: marked %s for reconnecting", tr.resolver) +} + +// query sends the query on a connection and waits for the reply. It returns +// errTCPConnStopped if the connection stopped before it took the query. +func (tr *TCPResolver) query(ctx context.Context, tq *tcpQuery) (*dns.Msg, error) { + // Get resolver connection. + resolverConn, err := tr.getOrCreateResolverConn(ctx) + if err != nil { + return nil, err } // Submit query request to live connection. select { case resolverConn.queries <- tq: + case <-resolverConn.stopped: + return nil, errTCPConnStopped case <-ctx.Done(): return nil, ctx.Err() case <-module.mgr.Done(): @@ -250,12 +416,29 @@ func (tr *TCPResolver) Query(ctx context.Context, q *Query) (*RRCache, error) { var reply *dns.Msg select { case reply = <-tq.Response: + case <-resolverConn.stopped: + // The handler closed the response channels of all queries it took + // before it stopped. Any other query is still in the queue and was + // never sent. + select { + case reply = <-tq.Response: + default: + return nil, errTCPConnStopped + } case <-ctx.Done(): - return nil, ctx.Err() + err = ctx.Err() case <-module.mgr.Done(): - return nil, ErrShuttingDown + err = ErrShuttingDown case <-time.After(defaultRequestTimeout): - return nil, ErrTimeout + err = ErrTimeout + } + if err != nil { + // Use the reply if it was delivered meanwhile. Otherwise it is cached + // when it arrives. + reply = tq.stopWaiting() + if reply == nil { + return nil, err + } } // Check if we have a reply. @@ -264,34 +447,7 @@ func (tr *TCPResolver) Query(ctx context.Context, q *Query) (*RRCache, error) { // there is a connection error. return nil, ErrFailure } - - // Check if the reply was blocked upstream. - if tr.resolver.IsBlockedUpstream(reply) { - return nil, &BlockedUpstreamError{tr.resolver.Info.DescriptiveName()} - } - - // Report request duration for metrics. - reportRequestDuration(queryStarted, tr.resolver) - - // Create RRCache from reply and return it. - return tq.MakeCacheRecord(reply, tr.resolver.Info), nil -} - -// ForceReconnect forces the resolver to re-establish the connection to the server. -func (tr *TCPResolver) ForceReconnect(ctx context.Context) { - tr.Lock() - defer tr.Unlock() - - // Do nothing if no connection is available. - if tr.resolverConn == nil { - return - } - - // Set the abandoned to force a new connection on next request. - // This will leave the previous connection and handler running until all requests are handled. - tr.resolverConn.abandoned.Set() - - log.Tracer(ctx).Tracef("resolver: marked %s for reconnecting", tr.resolver) + return reply, nil } // dial connects to the resolver from a pre-authenticated local port, so that @@ -353,32 +509,43 @@ func (trc *tcpResolverConn) shutdown() { // Set abandoned status and close connection to the DNS server. trc.abandoned.Set() _ = trc.conn.Close() + // Stop the reader, which may be blocked handing a response to the + // response queue that is not drained anymore. + trc.cancelCtx() // Close all response channels for in-flight queries. for _, tq := range trc.inFlightQueries { close(tq.Response) } - // Respond to any incoming queries for some time in order to not leave them - // hanging longer than necessary. - for { - select { - case tq := <-trc.queries: - close(tq.Response) - case <-time.After(100 * time.Millisecond): - return - } - } + // Signal that no queries are taken anymore. Queries submitted before or + // after are never sent and are retried by Query on a new connection. + close(trc.stopped) } func (trc *tcpResolverConn) handler(workerCtx *mgr.WorkerCtx) error { + // The worker manager restarts the handler after a panic. The deferred + // shutdown of the panicked run already shut the connection down, and it + // must not be shut down twice. The connection is replaced by the next + // query, so the restarted handler has nothing to do. + select { + case <-trc.stopped: + return nil + default: + } + // Set up context and cleanup. trc.ctx, trc.cancelCtx = context.WithCancel(workerCtx.Ctx()) defer trc.shutdown() // Set up variables. - var readyToRecycle bool - ttlTimer := time.After(defaultClientTTL) + ttl := trc.ttl + if ttl <= 0 { + ttl = defaultClientTTL + } + ttlTimer := time.After(ttl) + cleanupTicker := time.NewTicker(trc.inFlightTimeout) + defer cleanupTicker.Stop() // Start connection reader. module.mgr.Go("dns client reader", trc.reader) @@ -394,8 +561,11 @@ func (trc *tcpResolverConn) handler(workerCtx *mgr.WorkerCtx) error { return nil case <-ttlTimer: - // Recycle the connection after the TTL is reached. - readyToRecycle = true + // Recycle the connection after the TTL is reached: stop handing + // it out to new queries, so that it drains and the next query + // creates a new one. Otherwise a busy connection that always has a + // query in flight is never recycled. + trc.abandoned.Set() // Send dummy response to trigger the check. select { case trc.responses <- nil: @@ -412,9 +582,19 @@ func (trc *tcpResolverConn) handler(workerCtx *mgr.WorkerCtx) error { msg.SetQuestion(tq.Query.FQDN, uint16(tq.Query.QType)) // Assign a unique message ID. - trc.assignUniqueID(msg) + if !trc.assignUniqueID(msg) { + // All message IDs are in use, fail the query. + log.Warningf( + "resolver: no free message ID for query to %s, %d queries in flight", + trc.resolverInfo.DescriptiveName(), + len(trc.inFlightQueries), + ) + close(tq.Response) + continue + } // Add query to in flight registry. + tq.expires = time.Now().Add(trc.inFlightTimeout) trc.inFlightQueries[msg.Id] = tq // Write query to connected DNS server. @@ -430,36 +610,59 @@ func (trc *tcpResolverConn) handler(workerCtx *mgr.WorkerCtx) error { trc.handleQueryResponse(msg) } - // If we are ready to recycle and we have no in-flight queries, we can - // shutdown the connection and create a new one for the next query. - if readyToRecycle || trc.abandoned.IsSet() { + // If the connection is abandoned (e.g. its TTL is reached) and we + // have no in-flight queries, we can shutdown the connection. The + // next query creates a new one. + if trc.abandoned.IsSet() { if len(trc.inFlightQueries) == 0 { log.Debugf("resolver: recycling connection to %s", trc.resolverInfo.DescriptiveName()) return nil } } + case <-cleanupTicker.C: + // Remove queries that were never answered. The waiting Query() call + // has given up already. + trc.pruneInFlightQueries() + + if trc.abandoned.IsSet() { + if len(trc.inFlightQueries) == 0 { + log.Debugf("resolver: recycling connection to %s", trc.resolverInfo.DescriptiveName()) + return nil + } + } } } } // assignUniqueID makes sure that ID assigned to msg is unique. -func (trc *tcpResolverConn) assignUniqueID(msg *dns.Msg) { +// Returns false if all IDs are in use. +func (trc *tcpResolverConn) assignUniqueID(msg *dns.Msg) bool { // try a random ID 10000 times for range 10000 { // don't try forever _, exists := trc.inFlightQueries[msg.Id] if !exists { - return // we are unique, yay! + return true // we are unique, yay! } msg.Id = dns.Id() // regenerate ID } // go through the complete space - var id uint16 - for ; id <= (1<<16)-1; id++ { // don't try forever - _, exists := trc.inFlightQueries[id] + for id := range 1 << 16 { + _, exists := trc.inFlightQueries[uint16(id)] if !exists { - msg.Id = id - return // we are unique, yay! + msg.Id = uint16(id) + return true // we are unique, yay! + } + } + return false +} + +// pruneInFlightQueries removes expired queries from the in-flight registry. +func (trc *tcpResolverConn) pruneInFlightQueries() { + now := time.Now() + for id, tq := range trc.inFlightQueries { + if now.After(tq.expires) { + delete(trc.inFlightQueries, id) } } } @@ -479,13 +682,11 @@ func (trc *tcpResolverConn) handleQueryResponse(msg *dns.Msg) { return } - // Send response to waiting query handler. - select { - case tq.Response <- msg: + // Hand the response to the waiting query. + if tq.deliver(msg) { return - default: - // No one is listening for that response. } + // The query stopped waiting for the response. // If caching is disabled for this query, we are done. if tq.Query.NoCaching { @@ -514,7 +715,12 @@ func (trc *tcpResolverConn) reader(workerCtx *mgr.WorkerCtx) error { trc.logConnectionError(err, true) return nil } - trc.responses <- msg + select { + case trc.responses <- msg: + case <-trc.ctx.Done(): + // The handler stopped and does not process responses anymore. + return nil + } } } diff --git a/service/resolver/resolver-tcp_dialfail_test.go b/service/resolver/resolver-tcp_dialfail_test.go new file mode 100644 index 000000000..b361c3112 --- /dev/null +++ b/service/resolver/resolver-tcp_dialfail_test.go @@ -0,0 +1,200 @@ +package resolver + +import ( + "context" + "errors" + "net" + "strconv" + "sync" + "testing" + "time" + + "github.com/miekg/dns" +) + +// TestTCPResolverWaitersShareFailedDial checks that queries waiting for +// another query to establish a connection get the failure of that dial, +// instead of each dialing again one after another. +func TestTCPResolverWaitersShareFailedDial(t *testing.T) { + t.Parallel() + + // The server fails the TLS handshake only after a while, like a server + // that does not respond and makes the dial fail after the connect + // timeout. The first connection is held until the test releases it. + const dialDuration = 300 * time.Millisecond + server := newSlowFailingDoTServer(t, dialDuration) + tr := NewTCPResolver(server.resolver()).UseTLS() + + // Query concurrently while the first dial is in progress. + const queries = 6 + errs := make(chan error, queries) + for i := range queries { + go func() { + _, err := tr.Query(t.Context(), &Query{ + FQDN: "q" + strconv.Itoa(i) + ".example.", + QType: dns.Type(dns.TypeA), + NoCaching: true, + }) + errs <- err + }() + } + server.waitForConns(t, 1) + // Give the other queries time to wait for the dial. + time.Sleep(500 * time.Millisecond) + + // Fail the first dial: all waiting queries must fail with it right away. + released := time.Now() + server.releaseFirst() + for range queries { + err := <-errs + if !errors.Is(err, ErrFailure) { + t.Errorf("expected connection failure, got: %v", err) + } + } + took := time.Since(released) + if got := server.acceptedConns(); got != 1 { + t.Errorf("expected 1 dial for %d concurrent queries, got %d", queries, got) + } + // Dialing one after another takes (queries-1) * dialDuration = 1.5s. + if took > time.Second { + t.Errorf("waiting queries failed only after %s", took) + } + + // A query after the failed dial dials again. + _, err := tr.Query(t.Context(), &Query{FQDN: "later.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + if !errors.Is(err, ErrFailure) { + t.Errorf("expected connection failure, got: %v", err) + } + if got := server.acceptedConns(); got != 2 { + t.Errorf("expected a new dial for a later query, got %d dials in total", got) + } +} + +// TestTCPResolverWaitersDialAfterCanceledDial checks that queries waiting +// for a dial that failed because the dialing query was canceled dial +// themselves instead of failing with that error. +func TestTCPResolverWaitersDialAfterCanceledDial(t *testing.T) { + t.Parallel() + + server := newSlowFailingDoTServer(t, 50*time.Millisecond) + tr := NewTCPResolver(server.resolver()).UseTLS() + + // Start a dial with a query that is canceled while dialing. + ctx, cancel := context.WithCancel(t.Context()) + firstErr := make(chan error, 1) + go func() { + _, err := tr.Query(ctx, &Query{FQDN: "canceled.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + firstErr <- err + }() + server.waitForConns(t, 1) + + // Queue more queries behind it. + const waiting = 2 + errs := make(chan error, waiting) + for i := range waiting { + go func() { + _, err := tr.Query(t.Context(), &Query{ + FQDN: "w" + strconv.Itoa(i) + ".example.", + QType: dns.Type(dns.TypeA), + NoCaching: true, + }) + errs <- err + }() + } + time.Sleep(200 * time.Millisecond) + + cancel() + server.releaseFirst() + <-firstErr + for range waiting { + err := <-errs + if !errors.Is(err, ErrFailure) || errors.Is(err, context.Canceled) { + t.Errorf("expected connection failure of an own dial, got: %v", err) + } + } + // One waiting query dials again, the other one waits for that dial and + // fails with it. + if got := server.acceptedConns(); got != 2 { + t.Errorf("expected the waiting queries to dial again once, got %d dials in total", got) + } +} + +// slowFailingDoTServer is a DNS-over-TLS server that accepts connections but +// closes them after a delay, so that the TLS handshake and thereby the dial +// fails only then. The first connection is held until releaseFirst is called. +type slowFailingDoTServer struct { + port uint16 + release chan struct{} + once sync.Once + + lock sync.Mutex + accepted int +} + +func newSlowFailingDoTServer(t *testing.T, failAfter time.Duration) *slowFailingDoTServer { + t.Helper() + + listener, port := listenTCP(t) + s := &slowFailingDoTServer{port: port, release: make(chan struct{})} + t.Cleanup(s.releaseFirst) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + s.lock.Lock() + s.accepted++ + first := s.accepted == 1 + s.lock.Unlock() + go func() { + if first { + <-s.release + } else { + time.Sleep(failAfter) + } + _ = conn.Close() + }() + } + }() + return s +} + +func (s *slowFailingDoTServer) resolver() *Resolver { + return &Resolver{ + ServerAddress: net.JoinHostPort("127.0.0.1", strconv.Itoa(int(s.port))), + Info: &ResolverInfo{ + Name: "test-dot-failing", + Type: ServerTypeDoT, + Source: ServerSourceConfigured, + IP: net.IPv4(127, 0, 0, 1), + Domain: "dot.example", + Port: s.port, + }, + } +} + +// releaseFirst makes the first connection fail. +func (s *slowFailingDoTServer) releaseFirst() { + s.once.Do(func() { close(s.release) }) +} + +// acceptedConns returns how many connections the server accepted so far. +func (s *slowFailingDoTServer) acceptedConns() int { + s.lock.Lock() + defer s.lock.Unlock() + return s.accepted +} + +// waitForConns waits until the server accepted n connections. +func (s *slowFailingDoTServer) waitForConns(t *testing.T, n int) { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + for s.acceptedConns() < n { + if time.Now().After(deadline) { + t.Fatalf("server accepted only %d of %d connections", s.acceptedConns(), n) + } + time.Sleep(time.Millisecond) + } +} diff --git a/service/resolver/resolver-tcp_restart_test.go b/service/resolver/resolver-tcp_restart_test.go new file mode 100644 index 000000000..9dc69cc75 --- /dev/null +++ b/service/resolver/resolver-tcp_restart_test.go @@ -0,0 +1,91 @@ +package resolver + +import ( + "net" + "sync" + "testing" + "time" + + "github.com/miekg/dns" + "github.com/tevino/abool" + + "github.com/safing/portmaster/service/mgr" +) + +// TestTCPResolverConnHandlerRestartAfterPanic checks that a connection +// handler that is restarted by the worker manager after a panic does not +// panic again on the connection that the first run already shut down. +func TestTCPResolverConnHandlerRestartAfterPanic(t *testing.T) { + t.Parallel() + + clientSide, serverSide := net.Pipe() + defer func() { + _ = serverSide.Close() + }() + trc := &tcpResolverConn{ + conn: &dns.Conn{Conn: clientSide}, + resolverInfo: &ResolverInfo{Name: "PipeRestartTest", Type: ServerTypeTCP}, + queries: make(chan *tcpQuery, 10), + responses: make(chan *dns.Msg, 10), + inFlightQueries: make(map[uint16]*tcpQuery, 10), + inFlightTimeout: time.Minute, + heartbeat: make(chan struct{}), + abandoned: abool.New(), + stopped: make(chan struct{}), + } + + // Run the handler as getOrCreateResolverConn does, recording each run and + // whether it panicked. The worker manager recovers a panic and restarts + // the worker after a backoff (2s for the first restart). + var ( + lock sync.Mutex + runs int + finished int + panics []any + ) + module.mgr.Go("test dns client restart", func(w *mgr.WorkerCtx) error { + lock.Lock() + runs++ + lock.Unlock() + defer func() { + r := recover() + lock.Lock() + if r != nil { + panics = append(panics, r) + } else { + finished++ + } + lock.Unlock() + if r != nil { + panic(r) + } + }() + return trc.handler(w) + }) + + // Make the handler panic: the missing Query of a query is dereferenced. + trc.queries <- &tcpQuery{Response: make(chan *dns.Msg)} + select { + case <-trc.stopped: + case <-time.After(5 * time.Second): + t.Fatal("connection did not stop after the handler panicked") + } + + // The restarted handler must finish without panicking. + deadline := time.Now().Add(10 * time.Second) + for { + lock.Lock() + gotRuns, gotFinished, gotPanics := runs, finished, panics + lock.Unlock() + if len(gotPanics) > 1 { + t.Fatalf("restarted handler panicked again (run %d): %v", gotRuns, gotPanics[1:]) + } + if gotFinished > 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("restarted handler did not finish (runs %d, panics %v)", gotRuns, gotPanics) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/service/resolver/resolver-tcp_test.go b/service/resolver/resolver-tcp_test.go index d6a49476e..b5a699773 100644 --- a/service/resolver/resolver-tcp_test.go +++ b/service/resolver/resolver-tcp_test.go @@ -1,13 +1,19 @@ package resolver import ( + "context" "errors" + "io" "net" + "runtime" "slices" "strconv" + "strings" "sync" "testing" + "time" + "github.com/miekg/dns" "github.com/tevino/abool" ) @@ -15,25 +21,46 @@ import ( // that cannot be bound is released as unusable and the dial is retried with // the next port. func TestTCPResolverDialRetriesOnBindError(t *testing.T) { //nolint:paralleltest // Replaces the package-level hooks. - bt := newTCPBindTest(t) - freePort := freeTCPPort(t) - bt.usePorts(bt.heldPort, freePort) + // The second port is only free at the time it is picked: another process + // may take it before the dial binds it. This is detected by the second + // port being released as unusable, and the test is repeated with a new + // port, so it only asserts the retry when the port could actually be used. + const maxTries = 20 + for try := 1; try <= maxTries; try++ { + bt := newTCPBindTest(t) + freePort := freeTCPPort(t) + bt.usePorts(bt.heldPort, freePort) - conn, err := bt.resolver.dial(t.Context()) - if err != nil { - t.Fatalf("dial failed: %s", err) - } - _ = conn.Close() + conn, err := bt.resolver.dial(t.Context()) + got := bt.releasedPorts() - // The occupied port is released as unusable, the connected port is - // released as usable after the dial. - expected := []releasedPort{ - {port: bt.heldPort, unusable: true}, - {port: freePort, unusable: false}, - } - if got := bt.releasedPorts(); !slices.Equal(got, expected) { - t.Errorf("expected releases %v, got %v", expected, got) + // Stolen port: the first release is still the held port, but the + // second port was not bindable. + if len(got) >= 2 && got[1].port == freePort && got[1].unusable { + t.Logf("port %d was taken by another process (try %d of %d), retrying", freePort, try, maxTries) + if err == nil { + _ = conn.Close() + } + continue + } + + if err != nil { + t.Fatalf("dial failed: %s", err) + } + _ = conn.Close() + + // The occupied port is released as unusable, the connected port is + // released as usable after the dial. + expected := []releasedPort{ + {port: bt.heldPort, unusable: true}, + {port: freePort, unusable: false}, + } + if !slices.Equal(got, expected) { + t.Errorf("expected releases %v, got %v", expected, got) + } + return } + t.Fatalf("no usable free port found in %d tries", maxTries) } // TestTCPResolverDialGivesUpOnBindErrors checks that the dial fails with @@ -59,9 +86,12 @@ func TestTCPResolverDialGivesUpOnBindErrors(t *testing.T) { //nolint:paralleltes } } -// TestTCPResolverUsesConcurrentConnOnBindError checks that a connection -// created by a concurrent query while binding fails is used instead of -// reporting the bind error. +// TestTCPResolverUsesConcurrentConnOnBindError checks that the bind error is +// passed on, and that a query waiting for a concurrent query to establish a +// connection uses that connection instead of failing to bind a port itself. +// +// A connection can only be created while holding the dial slot, so it cannot +// appear while a query that holds the slot is binding. func TestTCPResolverUsesConcurrentConnOnBindError(t *testing.T) { //nolint:paralleltest // Replaces the package-level hooks. bt := newTCPBindTest(t) bt.usePorts(bt.heldPort) @@ -73,30 +103,48 @@ func TestTCPResolverUsesConcurrentConnOnBindError(t *testing.T) { //nolint:paral t.Errorf("expected ErrLocalBind, got: %v", err) } - // Simulate a concurrent query that creates a connection while this one - // fails to bind: set the connection from within the port selection, which - // runs after getOrCreateResolverConn has noted the current connection. + // Simulate a concurrent query that holds the dial slot and creates a + // connection while this one waits for the slot. concurrentConn := &tcpResolverConn{ abandoned: abool.New(), heartbeat: make(chan struct{}), } - selectPort := localAddrFactory - localAddrFactory = func(network string) net.Addr { - tr.Lock() - if tr.resolverConn == nil { - tr.resolverConnInstanceID++ - concurrentConn.id = tr.resolverConnInstanceID - tr.resolverConn = concurrentConn + // Answer alive checks, in case the connection is already set when the + // query looks for one. + stopHeartbeat := make(chan struct{}) + defer close(stopHeartbeat) + go func() { + for { + select { + case <-concurrentConn.heartbeat: + case <-stopHeartbeat: + return + } } - tr.Unlock() - return selectPort(network) + }() + tr.dialSlot <- struct{}{} + type result struct { + conn *tcpResolverConn + err error } + results := make(chan result, 1) + go func() { + conn, err := tr.getOrCreateResolverConn(t.Context()) + results <- result{conn, err} + }() + time.Sleep(50 * time.Millisecond) + tr.Lock() + tr.resolverConnInstanceID++ + concurrentConn.id = tr.resolverConnInstanceID + tr.resolverConn = concurrentConn + tr.Unlock() + <-tr.dialSlot - resolverConn, err := tr.getOrCreateResolverConn(t.Context()) - if err != nil { - t.Fatalf("expected the concurrently created connection, got error: %s", err) + res := <-results + if res.err != nil { + t.Fatalf("expected the concurrently created connection, got error: %s", res.err) } - if resolverConn != concurrentConn { + if res.conn != concurrentConn { t.Error("expected the concurrently created connection to be returned") } } @@ -150,9 +198,9 @@ func newTCPBindTest(t *testing.T) *tcpBindTest { // Record the released tcp ports. The started module may run UDP queries // concurrently that use the same hooks, so other networks are ignored. - previousHooks := localPortHooks - previousFactory := localAddrFactory - localPortHooks = LocalPortHooks{ + previousHooks := localPortHooks.Load() + previousFactory := localAddrFactory.Load() + localPortHooks.Store(&LocalPortHooks{ Authorize: func(network string, port uint16) { if network == networkTCP { t.Errorf("the tcp resolver must not authorize ports itself, got port %d", port) @@ -166,10 +214,10 @@ func newTCPBindTest(t *testing.T) *tcpBindTest { defer bt.lock.Unlock() bt.released = append(bt.released, releasedPort{port: port, unusable: unusable}) }, - } + }) t.Cleanup(func() { - localPortHooks = previousHooks - localAddrFactory = previousFactory + localPortHooks.Store(previousHooks) + localAddrFactory.Store(previousFactory) }) return bt @@ -179,7 +227,7 @@ func newTCPBindTest(t *testing.T) *tcpBindTest { // the last one, in place of the ports the firewall hands out. func (bt *tcpBindTest) usePorts(ports ...uint16) { var next int - localAddrFactory = func(network string) net.Addr { + factory := func(network string) net.Addr { if network != networkTCP { bt.t.Errorf("expected network tcp, got %q", network) } @@ -189,6 +237,7 @@ func (bt *tcpBindTest) usePorts(ports ...uint16) { next++ return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: int(port)} } + localAddrFactory.Store(&factory) } // releasedPorts returns the ports released so far, in order. @@ -223,3 +272,658 @@ func freeTCPPort(t *testing.T) uint16 { _ = listener.Close() return port } + +// TestTCPResolverConnUnansweredQuery checks that a query the server never +// answers does not stay in the in-flight registry forever, which would keep +// an abandoned connection (and its handler and reader) alive indefinitely. +func TestTCPResolverConnUnansweredQuery(t *testing.T) { + t.Parallel() + + clientSide, serverSide := net.Pipe() + defer func() { + _ = serverSide.Close() + }() + trc := &tcpResolverConn{ + conn: &dns.Conn{Conn: clientSide}, + resolverInfo: &ResolverInfo{Name: "PipeTest", Type: ServerTypeTCP}, + queries: make(chan *tcpQuery, 10), + responses: make(chan *dns.Msg, 10), + inFlightQueries: make(map[uint16]*tcpQuery, 10), + inFlightTimeout: 100 * time.Millisecond, + heartbeat: make(chan struct{}), + abandoned: abool.New(), + stopped: make(chan struct{}), + } + module.mgr.Go("test dns client", trc.handler) + + // Submit a query and receive it on the server side, but never answer it. + trc.queries <- &tcpQuery{ + Query: &Query{FQDN: "unanswered.example.", QType: dns.Type(dns.TypeA), NoCaching: true}, + Response: make(chan *dns.Msg), + } + server := &dns.Conn{Conn: serverSide} + _ = serverSide.SetReadDeadline(time.Now().Add(2 * time.Second)) + _, err := server.ReadMsg() + if err != nil { + t.Fatalf("server failed to read query: %s", err) + } + + // Abandon the connection, like ForceReconnect does. + trc.abandoned.Set() + + // The handler must close the connection once the query expired. + _ = serverSide.SetReadDeadline(time.Now().Add(2 * time.Second)) + _, err = server.ReadMsg() + if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrClosedPipe) { + t.Fatalf("abandoned connection with unanswered query was not closed: %v", err) + } +} + +// TestTCPAssignUniqueIDExhausted checks that assigning a message ID terminates +// when all 65536 IDs are in flight. +func TestTCPAssignUniqueIDExhausted(t *testing.T) { + t.Parallel() + + trc := &tcpResolverConn{ + inFlightQueries: make(map[uint16]*tcpQuery, 1<<16), + } + for id := range 1 << 16 { + trc.inFlightQueries[uint16(id)] = &tcpQuery{} + } + + done := make(chan bool, 1) + go func() { + done <- trc.assignUniqueID(&dns.Msg{}) + }() + select { + case ok := <-done: + if ok { + t.Fatal("assignUniqueID reported success although all IDs are in use") + } + case <-time.After(5 * time.Second): + t.Fatal("assignUniqueID did not return with all IDs in use") + } + + // With exactly one free ID, it must be found. + delete(trc.inFlightQueries, 4242) + msg := &dns.Msg{} + if !trc.assignUniqueID(msg) || msg.Id != 4242 { + t.Fatalf("expected to get free ID 4242, got ID %d", msg.Id) + } +} + +// TestTCPResolverConnReaderExitsWithFullResponseQueue checks that the reader +// of a connection terminates when the handler stops while the reader is +// blocked handing a response to the full response queue. Nobody drains the +// queue after the handler stopped, so the reader would otherwise block +// forever and keep the connection, its buffers and its worker alive. +func TestTCPResolverConnReaderExitsWithFullResponseQueue(t *testing.T) { + t.Parallel() + + clientSide, serverSide := net.Pipe() + defer func() { + _ = serverSide.Close() + }() + trc := &tcpResolverConn{ + conn: &dns.Conn{Conn: clientSide}, + resolverInfo: &ResolverInfo{Name: "PipeTest", Type: ServerTypeTCP}, + queries: make(chan *tcpQuery, 10), + responses: make(chan *dns.Msg, 10), + inFlightQueries: make(map[uint16]*tcpQuery, 10), + inFlightTimeout: time.Minute, + heartbeat: make(chan struct{}), + abandoned: abool.New(), + stopped: make(chan struct{}), + } + // Readers blocked on a response queue that do not belong to this test. + foreignReaders := blockedTCPReaders() + module.mgr.Go("test dns client", trc.handler) + + // Submit a query and read only the start of it on the server side, so that + // the handler is stuck writing it and does not process responses. + trc.queries <- &tcpQuery{ + Query: &Query{FQDN: "flood.example.", QType: dns.Type(dns.TypeA), NoCaching: true}, + Response: make(chan *dns.Msg, 1), + } + _ = serverSide.SetDeadline(time.Now().Add(5 * time.Second)) + _, err := io.ReadFull(serverSide, make([]byte, 2)) + if err != nil { + t.Fatalf("server failed to read query: %s", err) + } + + // Send more responses than the response queue holds. With the pipe, a + // write returns only after the reader read it completely, so the reader + // then blocks handing the last response to the full queue. + server := &dns.Conn{Conn: serverSide} + for i := range cap(trc.responses) + 1 { + reply := &dns.Msg{} + reply.SetQuestion("flood.example.", dns.TypeA) + reply.Id = uint16(i) //nolint:gosec // Small loop counter. + reply.Response = true + err = server.WriteMsg(reply) + if err != nil { + t.Fatalf("server failed to write response %d: %s", i, err) + } + } + var readers []string + deadline := time.Now().Add(5 * time.Second) + for len(readers) == 0 { + if time.Now().After(deadline) { + t.Fatal("reader did not block on the full response queue") + } + time.Sleep(time.Millisecond) + for _, id := range blockedTCPReaders() { + if !slices.Contains(foreignReaders, id) { + readers = append(readers, id) + } + } + } + + // Fail the pending write by closing the server side: the handler stops + // and shuts down the connection. + _ = serverSide.Close() + + // The reader must terminate. + deadline = time.Now().Add(5 * time.Second) + for { + stacks := allGoroutineStacks() + var leaked []string + for _, id := range readers { + if strings.Contains(stacks, "goroutine "+id+" [") { + leaked = append(leaked, id) + } + } + if len(leaked) == 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("reader goroutine(s) %v leaked after the connection was shut down", leaked) + } + time.Sleep(5 * time.Millisecond) + } +} + +// blockedTCPReaders returns the goroutine IDs of the tcp resolver connection +// readers that are blocked handing a response to the response queue, i.e. +// that are blocked in the reader function itself and not in reading. +func blockedTCPReaders() []string { + var ids []string + for g := range strings.SplitSeq(allGoroutineStacks(), "\n\n") { + header, frames, _ := strings.Cut(g, "\n") + if !strings.Contains(header, "[chan send") && !strings.Contains(header, "[select") { + continue + } + // Find the innermost frame outside of the runtime. + var topFrame string + for line := range strings.SplitSeq(frames, "\n") { + if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, "runtime.") { + topFrame = line + break + } + } + if !strings.Contains(topFrame, "/service/resolver.(*tcpResolverConn).reader(") { + continue + } + fields := strings.Fields(header) + if len(fields) >= 2 { + ids = append(ids, fields[1]) + } + } + return ids +} + +// allGoroutineStacks returns the stacks of all goroutines. +func allGoroutineStacks() string { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + return string(buf[:n]) + } + buf = make([]byte, 2*len(buf)) + } +} + +// TestTCPResolverQueryOnStoppedConn checks that a query handed to a +// connection whose handler stopped after the query obtained the connection +// does not wait for a response that can never arrive, but is sent on a new +// connection. +func TestTCPResolverQueryOnStoppedConn(t *testing.T) { + t.Parallel() + + server := newTCPTestServer(t) + tr := NewTCPResolver(server.resolver()) + + // Establish a connection with a first query. + _, err := tr.Query(t.Context(), &Query{FQDN: "first.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + if err != nil { + t.Fatalf("first query failed: %s", err) + } + tr.Lock() + staleConn := tr.resolverConn + tr.Unlock() + + // Close the connection on the server side: the handler stops. + server.closeConns() + deadline := time.Now().Add(5 * time.Second) + for staleConn.abandoned.IsNotSet() { + if time.Now().After(deadline) { + t.Fatal("connection was not abandoned after the server closed it") + } + time.Sleep(time.Millisecond) + } + // Let the shutdown of the handler complete. + time.Sleep(300 * time.Millisecond) + + // Recreate the state of a query that obtained the connection right before + // it stopped: the connection is not abandoned yet and the heartbeat + // succeeds. Abandon it afterwards, as the shutdown does. + staleConn.abandoned.UnSet() + go func() { + select { + case <-staleConn.heartbeat: + staleConn.abandoned.Set() + case <-time.After(5 * time.Second): + } + }() + + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) + defer cancel() + started := time.Now() + rrCache, err := tr.Query(ctx, &Query{FQDN: "second.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + took := time.Since(started) + if err != nil { + t.Fatalf("query on stopped connection failed after %s: %s", took, err) + } + if len(rrCache.Answer) != 1 { + t.Errorf("expected one answer, got %v", rrCache.Answer) + } + if took > time.Second { + t.Errorf("query on stopped connection took %s", took) + } +} + +// TestTCPResolverAbandonsConnWithFailedHeartbeat checks that a connection +// that failed the alive check and was replaced is shut down once it handled +// its in-flight queries, instead of running until its TTL. +func TestTCPResolverAbandonsConnWithFailedHeartbeat(t *testing.T) { + t.Parallel() + + server := newTCPTestServer(t) + tr := NewTCPResolver(server.resolver()) + tr.heartbeatTimeout = 50 * time.Millisecond + + // Set up a connection whose server side is controlled by the test. + clientSide, serverSide := net.Pipe() + defer func() { + _ = serverSide.Close() + }() + oldConn := &tcpResolverConn{ + conn: &dns.Conn{Conn: clientSide}, + resolverInfo: tr.resolver.Info, + queries: make(chan *tcpQuery, 10), + responses: make(chan *dns.Msg, 10), + inFlightQueries: make(map[uint16]*tcpQuery, 10), + inFlightTimeout: time.Minute, + heartbeat: make(chan struct{}), + abandoned: abool.New(), + stopped: make(chan struct{}), + } + tr.Lock() + tr.resolverConnInstanceID++ + oldConn.id = tr.resolverConnInstanceID + tr.resolverConn = oldConn + tr.Unlock() + module.mgr.Go("test dns client", oldConn.handler) + + // Submit a query and read only the start of it on the server side, so that + // the handler is stuck writing it and does not respond to alive checks. + oldConn.queries <- &tcpQuery{ + Query: &Query{FQDN: "slow.example.", QType: dns.Type(dns.TypeA), NoCaching: true}, + Response: make(chan *dns.Msg, 1), + } + _ = serverSide.SetDeadline(time.Now().Add(5 * time.Second)) + lengthPrefix := make([]byte, 2) + _, err := io.ReadFull(serverSide, lengthPrefix) + if err != nil { + t.Fatalf("server failed to read query: %s", err) + } + + // The heartbeat fails, and the query is sent on a new connection. + _, err = tr.Query(t.Context(), &Query{FQDN: "new.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + if err != nil { + t.Fatalf("query on new connection failed: %s", err) + } + tr.Lock() + replaced := tr.resolverConn != oldConn + tr.Unlock() + if !replaced { + t.Fatal("connection with failed heartbeat was not replaced") + } + + // Let the old connection complete its pending query. + packed := make([]byte, int(lengthPrefix[0])<<8|int(lengthPrefix[1])) + _, err = io.ReadFull(serverSide, packed) + if err != nil { + t.Fatalf("server failed to read query: %s", err) + } + query := &dns.Msg{} + err = query.Unpack(packed) + if err != nil { + t.Fatalf("server failed to unpack query: %s", err) + } + reply := &dns.Msg{} + reply.SetReply(query) + serverConn := &dns.Conn{Conn: serverSide} + err = serverConn.WriteMsg(reply) + if err != nil { + t.Fatalf("server failed to write reply: %s", err) + } + + // The old connection must be closed now that it has no in-flight queries. + _ = serverSide.SetReadDeadline(time.Now().Add(2 * time.Second)) + _, err = serverConn.ReadMsg() + if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrClosedPipe) { + t.Fatalf("replaced connection was not closed: %v", err) + } +} + +// tcpTestServer is a DNS server on a loopback TCP port that answers every A +// query with 127.0.0.1. +type tcpTestServer struct { + port uint16 + + lock sync.Mutex + conns []net.Conn + accepted int +} + +func newTCPTestServer(t *testing.T) *tcpTestServer { + t.Helper() + + listener, port := listenTCP(t) + s := &tcpTestServer{port: port} + t.Cleanup(s.closeConns) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + s.lock.Lock() + s.conns = append(s.conns, conn) + s.accepted++ + s.lock.Unlock() + go s.serve(&dns.Conn{Conn: conn}) + } + }() + return s +} + +func (s *tcpTestServer) resolver() *Resolver { + return &Resolver{ + ServerAddress: net.JoinHostPort("127.0.0.1", strconv.Itoa(int(s.port))), + Info: &ResolverInfo{ + Name: "test-tcp-server", + Type: ServerTypeTCP, + Source: ServerSourceConfigured, + IP: net.IPv4(127, 0, 0, 1), + Port: s.port, + }, + } +} + +func (s *tcpTestServer) serve(conn *dns.Conn) { + for { + query, err := conn.ReadMsg() + if err != nil { + return + } + reply := &dns.Msg{} + reply.SetReply(query) + reply.Answer = append(reply.Answer, &dns.A{ + Hdr: dns.RR_Header{Name: query.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, + A: net.IPv4(127, 0, 0, 1), + }) + if conn.WriteMsg(reply) != nil { + return + } + } +} + +// closeConns closes all connections accepted so far. +func (s *tcpTestServer) closeConns() { + s.lock.Lock() + defer s.lock.Unlock() + for _, conn := range s.conns { + _ = conn.Close() + } + s.conns = nil +} + +// acceptedConns returns how many connections the server accepted so far. +func (s *tcpTestServer) acceptedConns() int { + s.lock.Lock() + defer s.lock.Unlock() + return s.accepted +} + +// TestTCPResolverConcurrentReconnectDialsOnce checks that concurrent queries +// that find the connection broken establish a single new connection that +// they all use, instead of each dialing its own and orphaning all but the +// last one. +func TestTCPResolverConcurrentReconnectDialsOnce(t *testing.T) { + t.Parallel() + + server := newTCPTestServer(t) + tr := NewTCPResolver(server.resolver()) + + // Establish a connection with a first query. + _, err := tr.Query(t.Context(), &Query{FQDN: "first.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + if err != nil { + t.Fatalf("first query failed: %s", err) + } + tr.Lock() + brokenConn := tr.resolverConn + tr.Unlock() + + // Break the connection on the server side and wait for the handler to stop. + server.closeConns() + select { + case <-brokenConn.stopped: + case <-time.After(5 * time.Second): + t.Fatal("connection did not stop after the server closed it") + } + + // Query concurrently. + const queries = 20 + start := make(chan struct{}) + errs := make(chan error, queries) + for i := range queries { + go func() { + <-start + _, err := tr.Query(t.Context(), &Query{ + FQDN: "q" + strconv.Itoa(i) + ".example.", + QType: dns.Type(dns.TypeA), + NoCaching: true, + }) + errs <- err + }() + } + close(start) + for range queries { + err := <-errs + if err != nil { + t.Errorf("concurrent query failed: %s", err) + } + } + + // Exactly one new connection must have been established. + if got := server.acceptedConns(); got != 2 { + t.Errorf("expected 1 new connection for %d concurrent queries, got %d", queries, got-1) + } +} + +// TestTCPResolverWaitForDialHonorsContext checks that a query waiting for +// another query to establish a connection gives up when its context ends. +func TestTCPResolverWaitForDialHonorsContext(t *testing.T) { + t.Parallel() + + server := newTCPTestServer(t) + tr := NewTCPResolver(server.resolver()) + + // Simulate a dial in progress by another query. + tr.dialSlot <- struct{}{} + defer func() { <-tr.dialSlot }() + + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) + defer cancel() + started := time.Now() + _, err := tr.Query(ctx, &Query{FQDN: "waiting.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("expected context deadline error, got: %v", err) + } + if took := time.Since(started); took > time.Second { + t.Errorf("waiting query gave up only after %s", took) + } + if got := server.acceptedConns(); got != 0 { + t.Errorf("expected no connection, got %d", got) + } +} + +// TestTCPResolverRecyclesBusyConn checks that a connection that always has a +// query in flight is still recycled after its TTL. +func TestTCPResolverRecyclesBusyConn(t *testing.T) { + t.Parallel() + + // A server that answers every query after a delay, so that queries + // overlap. It records for each accepted connection whether the client + // closed it. + listener, port := listenTCP(t) + var ( + lock sync.Mutex + closed []bool + ) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + t.Cleanup(func() { _ = conn.Close() }) + lock.Lock() + index := len(closed) + closed = append(closed, false) + lock.Unlock() + go func() { + dnsConn := &dns.Conn{Conn: conn} + var writeLock sync.Mutex + for { + query, err := dnsConn.ReadMsg() + if err != nil { + lock.Lock() + closed[index] = true + lock.Unlock() + return + } + go func() { + time.Sleep(100 * time.Millisecond) + reply := &dns.Msg{} + reply.SetReply(query) + writeLock.Lock() + defer writeLock.Unlock() + _ = dnsConn.WriteMsg(reply) + }() + } + }() + } + }() + server := &tcpTestServer{port: port} + tr := NewTCPResolver(server.resolver()) + tr.clientTTL = 200 * time.Millisecond + + // Keep queries in flight all the time. + ctx, cancel := context.WithCancel(t.Context()) + var wg sync.WaitGroup + for i := range 4 { + wg.Go(func() { + time.Sleep(time.Duration(i) * 25 * time.Millisecond) + for ctx.Err() == nil { + _, _ = tr.Query(ctx, &Query{FQDN: "busy.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + } + }) + } + + // The first connection must be replaced and closed. + deadline := time.Now().Add(2 * time.Second) + for { + lock.Lock() + recycled := len(closed) >= 2 && closed[0] + accepted := len(closed) + lock.Unlock() + if recycled { + break + } + if time.Now().After(deadline) { + cancel() + wg.Wait() + t.Fatalf("busy connection was not recycled 10x past its TTL (%d connections accepted)", accepted) + } + time.Sleep(10 * time.Millisecond) + } + cancel() + wg.Wait() +} + +// TestTCPResolverConnReplyBeforeQueryWaits checks that a reply that the +// handler receives before the query waits for it is not dropped. The query +// hands itself to the handler through a buffered queue and may not wait for +// the reply yet when the reply arrives, e.g. under CPU load. The query then +// timed out although the server answered. +func TestTCPResolverConnReplyBeforeQueryWaits(t *testing.T) { + t.Parallel() + + trc := &tcpResolverConn{ + resolverInfo: &ResolverInfo{Name: "ReplyTest", Type: ServerTypeTCP}, + inFlightQueries: make(map[uint16]*tcpQuery, 1), + } + newReply := func(tq *tcpQuery, id uint16) *dns.Msg { + trc.inFlightQueries[id] = tq + reply := &dns.Msg{} + reply.SetQuestion(tq.Query.FQDN, dns.TypeA) + reply.Id = id + reply.Response = true + return reply + } + + // The reply arrives before the query waits for it. + tq := newTCPQuery(&Query{FQDN: "early.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + reply := newReply(tq, 1) + trc.handleQueryResponse(reply) + select { + case got := <-tq.Response: + if got != reply { + t.Errorf("expected the reply, got %v", got) + } + case <-time.After(time.Second): + t.Fatal("reply that arrived before the query waited for it was dropped") + } + + // The reply arrives right before the query stops waiting: it is used. + tq = newTCPQuery(&Query{FQDN: "late.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + reply = newReply(tq, 2) + trc.handleQueryResponse(reply) + if got := tq.stopWaiting(); got != reply { + t.Errorf("expected the delivered reply when giving up, got %v", got) + } + + // The reply arrives after the query stopped waiting: it is not delivered. + tq = newTCPQuery(&Query{FQDN: "gone.example.", QType: dns.Type(dns.TypeA), NoCaching: true}) + if got := tq.stopWaiting(); got != nil { + t.Errorf("expected no reply, got %v", got) + } + trc.handleQueryResponse(newReply(tq, 3)) + if len(tq.Response) != 0 { + t.Error("reply was delivered to a query that stopped waiting") + } +} diff --git a/service/resolver/resolver.go b/service/resolver/resolver.go index 35d71329b..c1015c228 100644 --- a/service/resolver/resolver.go +++ b/service/resolver/resolver.go @@ -82,7 +82,7 @@ type Resolver struct { // ResolverInfo is a subset of resolver attributes that is attached to answers // from that server in order to use it later for decision making. It must not // be changed by anyone after creation and initialization is complete. -type ResolverInfo struct { //nolint:golint,maligned // TODO +type ResolverInfo struct { // Name describes the name given to the resolver. The name is configured in the config URL using the name parameter. Name string @@ -211,7 +211,7 @@ func (resolver *Resolver) String() string { } // ResolverConn is an interface to implement different types of query backends. -type ResolverConn interface { //nolint:golint // TODO +type ResolverConn interface { Query(ctx context.Context, q *Query) (*RRCache, error) ReportFailure() IsFailing() bool diff --git a/service/resolver/resolver_test.go b/service/resolver/resolver_test.go index 2d3fa41f6..025fbbeea 100644 --- a/service/resolver/resolver_test.go +++ b/service/resolver/resolver_test.go @@ -49,8 +49,6 @@ func TestSingleResolving(t *testing.T) { t.Skip() } - defaultRequestTimeout = 30 * time.Second - // create separate resolver for this test resolver, _, err := createResolver(testResolver, "config") if err != nil { @@ -81,8 +79,6 @@ func TestBulkResolving(t *testing.T) { t.Skip() } - defaultRequestTimeout = 30 * time.Second - // create separate resolver for this test resolver, _, err := createResolver(testResolver, "config") if err != nil { diff --git a/service/resolver/rrcache.go b/service/resolver/rrcache.go index 3a64dfa6c..f0c1795d3 100644 --- a/service/resolver/rrcache.go +++ b/service/resolver/rrcache.go @@ -16,8 +16,6 @@ import ( // RRCache is a single-use structure to hold a DNS response. // Persistence is handled through NameRecords because of a limitation of the // underlying dns library. -// -//nolint:maligned type RRCache struct { // Respnse Header Domain string @@ -199,14 +197,32 @@ func GetRRCache(domain string, question dns.Type) (*RRCache, error) { rrCache.RCode = nameRecord.RCode rrCache.Expires = nameRecord.Expires - for _, entry := range nameRecord.Answer { - rrCache.Answer = parseRR(rrCache.Answer, entry) - } - for _, entry := range nameRecord.Ns { - rrCache.Ns = parseRR(rrCache.Ns, entry) - } - for _, entry := range nameRecord.Extra { - rrCache.Extra = parseRR(rrCache.Extra, entry) + if parsed := nameRecord.parsed.Load(); parsed != nil { + // The entries were already parsed, use copies of the parsed records. + rrCache.Answer = copyRRs(parsed.answer) + rrCache.Ns = copyRRs(parsed.ns) + rrCache.Extra = copyRRs(parsed.extra) + } else { + for _, entry := range nameRecord.Answer { + rrCache.Answer = parseRR(rrCache.Answer, entry) + } + for _, entry := range nameRecord.Ns { + rrCache.Ns = parseRR(rrCache.Ns, entry) + } + for _, entry := range nameRecord.Extra { + rrCache.Extra = parseRR(rrCache.Extra, entry) + } + // Keep copies of the parsed records if all entries could be parsed. + // Otherwise, parse again next time, so that failures are logged again. + if len(rrCache.Answer) == len(nameRecord.Answer) && + len(rrCache.Ns) == len(nameRecord.Ns) && + len(rrCache.Extra) == len(nameRecord.Extra) { + nameRecord.parsed.Store(&parsedNameRecord{ + answer: copyRRs(rrCache.Answer), + ns: copyRRs(rrCache.Ns), + extra: copyRRs(rrCache.Extra), + }) + } } rrCache.Resolver = nameRecord.Resolver @@ -215,6 +231,19 @@ func GetRRCache(domain string, question dns.Type) (*RRCache, error) { return rrCache, nil } +// copyRRs returns a deep copy of the given resource records. It returns nil +// for an empty section, like a section without any parsed entries. +func copyRRs(section []dns.RR) []dns.RR { + if len(section) == 0 { + return nil + } + copied := make([]dns.RR, len(section)) + for i, rr := range section { + copied[i] = dns.Copy(rr) + } + return copied +} + func parseRR(section []dns.RR, entry string) []dns.RR { rr, err := dns.NewRR(entry) switch { diff --git a/service/resolver/rrcache_test.go b/service/resolver/rrcache_test.go index a78df4396..367786c8f 100644 --- a/service/resolver/rrcache_test.go +++ b/service/resolver/rrcache_test.go @@ -1,11 +1,68 @@ package resolver import ( + "net" "testing" + "time" "github.com/miekg/dns" + "github.com/stretchr/testify/assert" ) +func TestGetRRCacheParsedCopies(t *testing.T) { + t.Parallel() + + domain := "parsed-copies.example.com." + saved := &RRCache{ + Domain: domain, + Question: dns.Type(dns.TypeA), + RCode: dns.RcodeSuccess, + Answer: []dns.RR{ + &dns.CNAME{Hdr: dns.RR_Header{Name: domain, Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: 17}, Target: "edge.example.net."}, + &dns.A{Hdr: dns.RR_Header{Name: "edge.example.net.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 17}, A: net.IPv4(192, 0, 2, 1)}, + }, + Ns: []dns.RR{ + &dns.NS{Hdr: dns.RR_Header{Name: domain, Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 17}, Ns: "ns.parsed-copies.example.com."}, + }, + Expires: time.Now().Add(time.Hour).Unix(), + Resolver: &ResolverInfo{Type: ServerTypeDNS}, + } + err := saved.Save() + if err != nil { + t.Fatal(err) + } + + // The first call parses the entries, the second uses the parsed records. + first, err := GetRRCache(domain, dns.Type(dns.TypeA)) + if err != nil { + t.Fatal(err) + } + second, err := GetRRCache(domain, dns.Type(dns.TypeA)) + if err != nil { + t.Fatal(err) + } + for _, rrCache := range []*RRCache{first, second} { + assert.Equal(t, saved.Answer, rrCache.Answer) + assert.Equal(t, saved.Ns, rrCache.Ns) + assert.Nil(t, rrCache.Extra) + } + + // Changes to returned records must not affect later results. + second.ReplaceAnswerNames("PARSED-COPIES.example.com.") + aRecord, ok := second.Answer[1].(*dns.A) + if !ok { + t.Fatal("expected A record") + } + aRecord.A[len(aRecord.A)-1] = 99 + aRecord.Hdr.Ttl = 1 + third, err := GetRRCache(domain, dns.Type(dns.TypeA)) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, saved.Answer, third.Answer) + assert.Equal(t, saved.Ns, third.Ns) +} + func TestCaching(t *testing.T) { t.Parallel() diff --git a/service/resolver/scopes.go b/service/resolver/scopes.go index 0535ef103..e5c187fca 100644 --- a/service/resolver/scopes.go +++ b/service/resolver/scopes.go @@ -127,7 +127,7 @@ var ( ".bbs.", ".chan.", ".dyn.", - ".free.", + // ".free." is now an ICANN TLD (IANA root zone) and is resolved normally. ".fur.", ".geek.", ".glue.", diff --git a/service/resolver/scopes_icann_test.go b/service/resolver/scopes_icann_test.go new file mode 100644 index 000000000..0da3c915f --- /dev/null +++ b/service/resolver/scopes_icann_test.go @@ -0,0 +1,24 @@ +package resolver + +import ( + "strings" + "testing" + + "golang.org/x/net/publicsuffix" +) + +// TestSpecialServiceDomainsNotICANN checks that no special-service domain +// (blocked by "Block Unofficial TLDs") is an official ICANN TLD. +func TestSpecialServiceDomainsNotICANN(t *testing.T) { + t.Parallel() + + for _, d := range specialServiceDomains { + tld := strings.Trim(d, ".") + if tld == "onion" { // RFC 7686 special-use name, listed as ICANN in the PSL. + continue + } + if _, icann := publicsuffix.PublicSuffix("example." + tld); icann { + t.Errorf("%s is an ICANN TLD, remove it from specialServiceDomains", d) + } + } +} diff --git a/service/splittun/proxy/tcp_idle_test.go b/service/splittun/proxy/tcp_idle_test.go new file mode 100644 index 000000000..2bcc1f42c --- /dev/null +++ b/service/splittun/proxy/tcp_idle_test.go @@ -0,0 +1,132 @@ +package proxy + +import ( + "context" + "io" + "net" + "testing" + "time" +) + +// TestTCPProxy_OneWayTransferOutlivesReadTimeout checks that a session which +// is only active in one direction (a long upload with a silent server) is not +// treated as idle. The server answers only after the whole upload was +// received; that answer must reach the client. +func TestTCPProxy_OneWayTransferOutlivesReadTimeout(t *testing.T) { + t.Parallel() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() //nolint:errcheck + + const ( + chunks = 12 + interval = 40 * time.Millisecond + ) + serverErr := make(chan error, 1) + go func() { + c, err := ln.Accept() + if err != nil { + serverErr <- err + return + } + defer c.Close() //nolint:errcheck + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + // Read the full upload (until the client half-closes), then answer. + n, err := io.Copy(io.Discard, c) + if err != nil { + serverErr <- err + return + } + if n != chunks { + _, _ = c.Write([]byte("SHORT")) + serverErr <- nil + return + } + _, err = c.Write([]byte("OK")) + serverErr <- err + }() + + cfg := DefaultConfig() + cfg.ReadTimeout = 150 * time.Millisecond + p, err := NewTCPProxyWithConfig("127.0.0.1:0", "tcp4", passThroughDecider(ln.Addr().String()), nil, cfg, "") + if err != nil { + t.Fatalf("NewTCPProxy: %v", err) + } + defer p.Shutdown(context.Background()) //nolint:errcheck + + conn, err := net.DialTimeout("tcp", p.Addr().String(), 2*time.Second) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() //nolint:errcheck + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + + // Upload for about 3x ReadTimeout while the server stays silent. + for range chunks { + _, err = conn.Write([]byte{'x'}) + if err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(interval) + } + tcpConn, ok := conn.(*net.TCPConn) + if !ok { + t.Fatalf("unexpected conn type %T", conn) + } + err = tcpConn.CloseWrite() + if err != nil { + t.Fatalf("close write: %v", err) + } + + reply, err := io.ReadAll(conn) + if err != nil { + t.Fatalf("read reply: %v", err) + } + if string(reply) != "OK" { + t.Fatalf("got reply %q, want %q", reply, "OK") + } + err = <-serverErr + if err != nil { + t.Fatalf("server: %v", err) + } +} + +// TestTCPProxy_IdleSessionTimesOut checks that a session without traffic in +// either direction is still closed after ReadTimeout. +func TestTCPProxy_IdleSessionTimesOut(t *testing.T) { + t.Parallel() + + echoAddr, stopEcho := startTCPEchoServer(t) + defer stopEcho() + + cfg := DefaultConfig() + cfg.ReadTimeout = 100 * time.Millisecond + p, err := NewTCPProxyWithConfig("127.0.0.1:0", "tcp4", passThroughDecider(echoAddr), nil, cfg, "") + if err != nil { + t.Fatalf("NewTCPProxy: %v", err) + } + defer p.Shutdown(context.Background()) //nolint:errcheck + + conn, err := net.DialTimeout("tcp", p.Addr().String(), 2*time.Second) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() //nolint:errcheck + _ = conn.SetDeadline(time.Now().Add(2 * time.Second)) + + // The proxy must close the idle session, which the client sees as EOF. + _, err = conn.Read(make([]byte, 1)) + if err == nil { + t.Fatal("expected idle session to be closed") + } + deadline := time.Now().Add(time.Second) + for p.Metrics().ActiveSessions != 0 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if active := p.Metrics().ActiveSessions; active != 0 { + t.Fatalf("idle session not cleaned up: active=%d", active) + } +} diff --git a/service/splittun/proxy/tcp_proxy.go b/service/splittun/proxy/tcp_proxy.go index 00b571d1a..49e03a124 100644 --- a/service/splittun/proxy/tcp_proxy.go +++ b/service/splittun/proxy/tcp_proxy.go @@ -302,6 +302,12 @@ func (p *TCPProxy) pipe(dst, src net.Conn, connCtx *ConnContext) int64 { } if readErr != nil { if errors.Is(readErr, os.ErrDeadlineExceeded) { + // The deadline only covers this direction. If the opposite + // direction transferred data recently, the session is not + // idle (e.g. a long one-way upload or download). + if time.Since(connCtx.LastSeen()) < p.cfg.ReadTimeout { + continue + } p.log.Debug(p.logPrefix+"session read timeout", "session", connCtx.id, "dest_ip", connCtx.destIP, "dest_port", connCtx.destPort, "timeout", p.cfg.ReadTimeout) } else if !isClosedConnErr(readErr) { p.log.Debug(p.logPrefix+"session read error", "session", connCtx.id, "dest_ip", connCtx.destIP, "dest_port", connCtx.destPort, "err", readErr) diff --git a/service/splittun/proxy/udp_idle_test.go b/service/splittun/proxy/udp_idle_test.go new file mode 100644 index 000000000..cf422da77 --- /dev/null +++ b/service/splittun/proxy/udp_idle_test.go @@ -0,0 +1,61 @@ +package proxy + +import ( + "context" + "net" + "testing" + "time" +) + +// TestUDPProxy_OneWayFlowKeepsSession checks that a client which keeps sending +// to a silent upstream keeps its NAT session (and thus its upstream source +// port) instead of having it torn down and recreated every ReadTimeout. +func TestUDPProxy_OneWayFlowKeepsSession(t *testing.T) { + t.Parallel() + + sink, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatalf("listen: %v", err) + } + defer sink.Close() //nolint:errcheck + go func() { + buf := make([]byte, 2048) + for { + _, _, readErr := sink.ReadFromUDP(buf) + if readErr != nil { + return + } + } + }() + + cfg := DefaultConfig() + cfg.ReadTimeout = 150 * time.Millisecond + p, err := NewUDPProxyWithConfig("127.0.0.1:0", "udp4", passThroughDecider(sink.LocalAddr().String()), nil, cfg, "") + if err != nil { + t.Fatalf("NewUDPProxy: %v", err) + } + defer p.Shutdown(context.Background()) //nolint:errcheck + + proxyAddr, ok := p.Addr().(*net.UDPAddr) + if !ok { + t.Fatalf("unexpected addr type %T", p.Addr()) + } + client, err := net.DialUDP("udp", nil, proxyAddr) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer client.Close() //nolint:errcheck + + // Send for about 3x ReadTimeout while the upstream stays silent. + for range 15 { + _, err = client.Write([]byte("ping")) + if err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(30 * time.Millisecond) + } + + if created := p.Metrics().TotalCreated; created != 1 { + t.Fatalf("active one-way flow was recreated: %d sessions created, want 1", created) + } +} diff --git a/service/splittun/proxy/udp_proxy.go b/service/splittun/proxy/udp_proxy.go index cb02ce384..b8ab3519e 100644 --- a/service/splittun/proxy/udp_proxy.go +++ b/service/splittun/proxy/udp_proxy.go @@ -330,6 +330,11 @@ func (p *UDPProxy) forwardFromRemote(ctx context.Context, sess *udpSession, clie return default: if isTimeoutErr(err) { + // The read deadline only covers upstream → client. If the + // client sent data recently, the session is not idle. + if time.Since(sess.connCtx.LastSeen()) < p.cfg.ReadTimeout { + continue + } p.log.Debug(p.logPrefix+"session idle timeout", "session", sess.connCtx.id, "dest_ip", sess.connCtx.destIP, "dest_port", sess.connCtx.destPort, "client", clientAddr) return } diff --git a/service/status/status.go b/service/status/status.go index 0e78a8eb3..33769ebdd 100644 --- a/service/status/status.go +++ b/service/status/status.go @@ -36,6 +36,17 @@ func (s *Status) handleModuleStatusUpdate(_ *mgr.WorkerCtx, update mgr.StateUpda s.statesLock.Lock() defer s.statesLock.Unlock() + // State update callbacks run in their own goroutines, so updates of the + // same module may arrive out of order. Use the module's current states, + // read under the lock, so that the last callback always applies the + // latest states instead of a stale update. + for _, current := range s.instance.GetStates() { + if current.Module == update.Module { + update = current + break + } + } + s.states[update.Module] = update s.deriveNotificationsFromStateUpdate(update) s.triggerPublishStatus() @@ -92,7 +103,7 @@ func (s *Status) buildSystemStatus() *SystemStatusRecord { // Check if state is worst so far. for _, state := range newStateUpdate.States { if state.Type.Severity() > status.WorstState.Type.Severity() { - s.mgr.Error("new worst state", "state", state) + s.mgr.Debug("new worst state", "state", state) status.WorstState.State = state status.WorstState.Module = newStateUpdate.Module } diff --git a/service/status/status_test.go b/service/status/status_test.go new file mode 100644 index 000000000..1c0e5e13d --- /dev/null +++ b/service/status/status_test.go @@ -0,0 +1,78 @@ +package status + +import ( + "sync" + "testing" + "time" + + "github.com/safing/portmaster/base/notifications" + "github.com/safing/portmaster/service/mgr" + "github.com/safing/portmaster/service/netenv" +) + +var notificationsSetupOnce sync.Once + +type statusTestInstance struct { + states *mgr.StateMgr +} + +func (i *statusTestInstance) NetEnv() *netenv.NetEnv { return nil } +func (i *statusTestInstance) GetStates() []mgr.StateUpdate { + return []mgr.StateUpdate{i.states.Export()} +} + +func (i *statusTestInstance) AddStatesCallback(callbackName string, callback mgr.EventCallbackFunc[mgr.StateUpdate]) { + i.states.AddCallback(callbackName, callback) +} + +// TestModuleStatusConvergesToLatestState checks that the status module ends up +// with the latest module state, even though state update callbacks are +// executed in separate goroutines and may therefore run out of order. +// A state that was added and immediately removed again (a common pattern for +// error states) must not stay in the system status, nor its notification. +// +//nolint:paralleltest // Uses the global notification storage. +func TestModuleStatusConvergesToLatestState(t *testing.T) { + notificationsSetupOnce.Do(func() { + _, err := notifications.New(struct{}{}) + if err != nil { + t.Fatalf("failed to create notifications module: %s", err) + } + }) + + moduleMgr := mgr.New("TestModule") + inst := &statusTestInstance{states: mgr.NewStateMgr(moduleMgr)} + statusMgr := mgr.New("Status") + s := &Status{ + mgr: statusMgr, + instance: inst, + triggerUpdate: make(chan struct{}, 1), + states: make(map[string]mgr.StateUpdate), + notifications: make(map[string]map[string]*notifications.Notification), + } + inst.AddStatesCallback("status update", s.handleModuleStatusUpdate) + + const stateID = "test:transient-error" + for range 300 { + inst.states.Add(mgr.State{ + ID: stateID, + Name: "Transient error", + Message: "Transient error", + Type: mgr.StateTypeError, + }) + inst.states.Remove(stateID) + } + if !moduleMgr.WaitForWorkers(5 * time.Second) { + t.Fatal("state update callbacks did not finish") + } + + s.statesLock.Lock() + got := s.states[moduleMgr.Name()] + s.statesLock.Unlock() + if len(got.States) != 0 { + t.Errorf("status kept stale module states: %+v", got.States) + } + if n := notifications.Get(stateID); n != nil { + t.Errorf("notification for removed state %q still shown", stateID) + } +} diff --git a/service/sync/profile.go b/service/sync/profile.go index 02ae07fa7..60d007f3e 100644 --- a/service/sync/profile.go +++ b/service/sync/profile.go @@ -18,7 +18,7 @@ import ( ) // ProfileExport holds an export of a profile. -type ProfileExport struct { //nolint:maligned +type ProfileExport struct { Type Type `json:"type" yaml:"type"` // Identification @@ -274,10 +274,10 @@ func ExportProfile(scopedID string) (*ProfileExport, error) { // Remove presentation path if both Name and Icon are set. if export.Name != "" && export.IconData != "" { - p.UsePresentationPath = false + export.UsePresentationPath = false } - if !p.UsePresentationPath { - p.PresentationPath = "" + if !export.UsePresentationPath { + export.PresentationPath = "" } return export, nil @@ -294,6 +294,9 @@ func ImportProfile(r *ProfileImportRequest, requiredProfileSource profile.Profil if r.Export.Source != "" && r.Export.Source != requiredProfileSource { return nil, ErrMismatch } + // The profile is always imported to the required source, so use it for all + // checks below, even if the export does not specify a source. + r.Export.Source = requiredProfileSource // Convert fingerprints to internal representation. fingerprints := convertFingerprintsToInternal(r.Export.Fingerprints) if len(fingerprints) == 0 { diff --git a/service/sync/profile_test.go b/service/sync/profile_test.go new file mode 100644 index 000000000..7bc80bcb9 --- /dev/null +++ b/service/sync/profile_test.go @@ -0,0 +1,137 @@ +package sync + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/database" + _ "github.com/safing/portmaster/base/database/storage/hashmap" + "github.com/safing/portmaster/service/profile" +) + +func TestMain(m *testing.M) { + // Initialize the global database system with an in-memory "core" database. + dir, err := os.MkdirTemp("", "portmaster-sync-test-") + if err != nil { + panic(err) + } + err = database.Initialize(dir) + if err != nil { + panic(err) + } + _, err = database.Register(&database.Database{ + Name: "core", + Description: "test", + StorageType: "hashmap", + }) + if err != nil { + panic(err) + } + + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} + +// TestImportProfileWithoutSourceDetectsExisting checks that importing a +// profile export that does not specify a source checks for an existing +// profile (and merged profiles) in the source it is actually imported to. +// +//nolint:paralleltest // Uses the global database. +func TestImportProfileWithoutSourceDetectsExisting(t *testing.T) { + fingerprints := []profile.Fingerprint{{ + Type: profile.FingerprintTypePathID, + Operation: profile.FingerprintOperationEqualsID, + Value: "/usr/bin/test-app", + }} + id := profile.DeriveProfileID(fingerprints) + + // Create existing local profiles. + existing := &profile.Profile{ + ID: id, + Source: profile.SourceLocal, + Name: "existing", + Fingerprints: fingerprints, + Config: map[string]any{}, + } + existing.SetKey(profile.MakeProfileKey(existing.Source, existing.ID)) + require.NoError(t, existing.Save()) + merged := &profile.Profile{ + ID: "merged", + Source: profile.SourceLocal, + Name: "merged", + Config: map[string]any{}, + } + merged.SetKey(profile.MakeProfileKey(merged.Source, merged.ID)) + require.NoError(t, merged.Save()) + + newRequest := func(validateOnly bool) *ProfileImportRequest { + return &ProfileImportRequest{ + ImportRequest: ImportRequest{ValidateOnly: validateOnly}, + Export: &ProfileExport{ + Type: TypeProfile, + Name: "imported", + Fingerprints: []ProfileFingerprint{{ + Type: profile.FingerprintTypePathID, + Operation: profile.FingerprintOperationEqualsID, + Value: "/usr/bin/test-app", + MergedFrom: "local/merged", + }}, + }, + } + } + + // Validation must report that the existing profiles are replaced. + result, err := ImportProfile(newRequest(true), profile.SourceLocal) + require.NoError(t, err) + assert.True(t, result.ReplacesExisting, "validation must report that the existing profile is replaced") + assert.Equal(t, []string{"local/merged"}, result.ReplacesProfiles) + + // Import must not replace the existing profile without AllowReplace. + _, err = ImportProfile(newRequest(false), profile.SourceLocal) + require.ErrorIs(t, err, ErrImportFailed) + r, err := db.Get(profile.MakeProfileKey(profile.SourceLocal, id)) + require.NoError(t, err) + p, err := profile.EnsureProfile(r) + require.NoError(t, err) + assert.Equal(t, "existing", p.Name, "existing profile must not be replaced") +} + +// TestExportProfileOmitsUnusedPresentationPath checks that the export does not +// contain the presentation path if it is not used, and that exporting does not +// modify the stored profile. +// +//nolint:paralleltest // Uses the global database. +func TestExportProfileOmitsUnusedPresentationPath(t *testing.T) { + fingerprints := []profile.Fingerprint{{ + Type: profile.FingerprintTypePathID, + Operation: profile.FingerprintOperationEqualsID, + Value: "/usr/bin/export-app", + }} + p := &profile.Profile{ + ID: profile.DeriveProfileID(fingerprints), + Source: profile.SourceLocal, + Name: "export-app", + PresentationPath: "/home/someone/private/export-app", + UsePresentationPath: false, + Fingerprints: fingerprints, + Config: map[string]any{}, + } + p.SetKey(profile.MakeProfileKey(p.Source, p.ID)) + require.NoError(t, p.Save()) + + export, err := ExportProfile(p.ScopedID()) + require.NoError(t, err) + assert.Empty(t, export.PresentationPath, "unused presentation path must not be exported") + assert.False(t, export.UsePresentationPath) + + // The stored profile must be unchanged. + r, err := db.Get(profile.MakeProfileKey(p.Source, p.ID)) + require.NoError(t, err) + stored, err := profile.EnsureProfile(r) + require.NoError(t, err) + assert.Equal(t, "/home/someone/private/export-app", stored.PresentationPath, "export must not modify the profile") +} diff --git a/service/sync/setting_single.go b/service/sync/setting_single.go index 9566fe0f8..150051e63 100644 --- a/service/sync/setting_single.go +++ b/service/sync/setting_single.go @@ -250,6 +250,9 @@ func ImportSingeSetting(r *SingleSettingImportRequest) (*ImportResult, error) { } // Set imported setting on profile. + if p.Config == nil { + p.Config = make(map[string]any) + } config.PutValueIntoHierarchicalConfig(p.Config, r.Export.ID, r.Export.Value) // Mark profile as edited by user. diff --git a/service/sync/settings.go b/service/sync/settings.go index 372f63db2..c621d990f 100644 --- a/service/sync/settings.go +++ b/service/sync/settings.go @@ -286,6 +286,9 @@ func ImportSettings(r *SettingsImportRequest) (*ImportResult, error) { if r.Reset { p.Config = config.Expand(settings) } else { + if p.Config == nil { + p.Config = make(map[string]any) + } for k, v := range settings { config.PutValueIntoHierarchicalConfig(p.Config, k, v) } diff --git a/service/sync/settings_nilconfig_test.go b/service/sync/settings_nilconfig_test.go new file mode 100644 index 000000000..fc6d2c922 --- /dev/null +++ b/service/sync/settings_nilconfig_test.go @@ -0,0 +1,106 @@ +package sync + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/config" + "github.com/safing/portmaster/service/profile" +) + +const nilConfigTestOptionKey = "test/sync/nilconfig" + +// saveNilConfigProfile stores a profile with a nil Config map, as is the case +// for a stored record with `"config": null`. +func saveNilConfigProfile(t *testing.T, id string) { + t.Helper() + + p := &profile.Profile{ + ID: id, + Source: profile.SourceLocal, + Name: "nil config", + Config: nil, + } + p.SetKey(profile.MakeProfileKey(p.Source, p.ID)) + require.NoError(t, p.Save()) +} + +func registerNilConfigTestOption(t *testing.T) { + t.Helper() + + _, err := config.GetOption(nilConfigTestOptionKey) + if err == nil { + return + } + require.NoError(t, config.Register(&config.Option{ + Name: "Nil Config Test", + Key: nilConfigTestOptionKey, + Description: "test option", + OptType: config.OptTypeBool, + DefaultValue: false, + Annotations: config.Annotations{ + config.SettablePerAppAnnotation: true, + }, + })) +} + +func loadNilConfigProfile(t *testing.T, id string) *profile.Profile { + t.Helper() + + r, err := db.Get(profile.MakeProfileKey(profile.SourceLocal, id)) + require.NoError(t, err) + p, err := profile.EnsureProfile(r) + require.NoError(t, err) + return p +} + +// TestImportSettingsIntoNilConfigProfile checks that importing settings into a +// profile with a nil Config map does not panic. +// +//nolint:paralleltest // Uses the global database. +func TestImportSettingsIntoNilConfigProfile(t *testing.T) { + registerNilConfigTestOption(t) + saveNilConfigProfile(t, "nilconfig-settings") + + req := &SettingsImportRequest{ + ImportRequest: ImportRequest{Target: "local/nilconfig-settings"}, + Export: &SettingsExport{ + Type: TypeSettings, + Config: map[string]any{nilConfigTestOptionKey: true}, + }, + } + require.NotPanics(t, func() { + _, err := ImportSettings(req) + require.NoError(t, err) + }) + + p := loadNilConfigProfile(t, "nilconfig-settings") + assert.Equal(t, true, config.Flatten(p.Config)[nilConfigTestOptionKey]) +} + +// TestImportSingleSettingIntoNilConfigProfile checks that importing a single +// setting into a profile with a nil Config map does not panic. +// +//nolint:paralleltest // Uses the global database. +func TestImportSingleSettingIntoNilConfigProfile(t *testing.T) { + registerNilConfigTestOption(t) + saveNilConfigProfile(t, "nilconfig-single") + + req := &SingleSettingImportRequest{ + ImportRequest: ImportRequest{Target: "local/nilconfig-single"}, + Export: &SingleSettingExport{ + Type: TypeSingleSetting, + ID: nilConfigTestOptionKey, + Value: true, + }, + } + require.NotPanics(t, func() { + _, err := ImportSingeSetting(req) + require.NoError(t, err) + }) + + p := loadNilConfigProfile(t, "nilconfig-single") + assert.Equal(t, true, config.Flatten(p.Config)[nilConfigTestOptionKey]) +} diff --git a/service/ui/module.go b/service/ui/module.go index 946cb1e20..f9a12a1c7 100644 --- a/service/ui/module.go +++ b/service/ui/module.go @@ -1,10 +1,12 @@ package ui import ( + "net/http" "os" "path/filepath" "sync" "sync/atomic" + "time" "github.com/safing/portmaster/base/api" "github.com/safing/portmaster/base/log" @@ -18,7 +20,7 @@ type UI struct { mgr *mgr.Manager instance instance - archives map[string]*zipfs.FileSystem + archives map[string]*archive archivesLock sync.RWMutex upgradeLock atomic.Bool @@ -31,7 +33,7 @@ func New(instance instance) (*UI, error) { mgr: m, instance: instance, - archives: make(map[string]*zipfs.FileSystem), + archives: make(map[string]*archive), } if err := ui.registerAPIEndpoints(); err != nil { @@ -78,39 +80,89 @@ func (ui *UI) Stop() error { return nil } -func (ui *UI) getArchive(name string) (archive *zipfs.FileSystem, ok bool) { - ui.archivesLock.RLock() - defer ui.archivesLock.RUnlock() +// archive is an opened UI archive with the number of files that are currently +// being served from it. +type archive struct { + fs *zipfs.FileSystem - archive, ok = ui.archives[name] - return + // inUse counts the files opened from the archive that are not closed yet. + // The archive must not be closed while files are read from it: on Windows, + // closing a file while it is being read concurrently can block forever + // (Go 1.26, golang/go#77404). + inUse sync.WaitGroup } -func (ui *UI) setArchive(name string, archive *zipfs.FileSystem) { - ui.archivesLock.Lock() - defer ui.archivesLock.Unlock() +// open opens a file from the archive. The caller must hold the archives lock, +// so that the archive is not retired at the same time. +func (a *archive) open(archiveName, path string) (file http.File, servedPath string, status int, err error) { + a.inUse.Add(1) + file, servedPath, status, err = openFileFromArchive(archiveName, a.fs, path) + if err != nil { + a.inUse.Done() + return nil, servedPath, status, err + } + return &archiveFile{File: file, done: a.inUse.Done}, servedPath, status, nil +} + +// archiveFile is a file opened from an archive, which releases the archive +// when closed. +type archiveFile struct { + http.File - ui.archives[name] = archive + done func() + doneOnce sync.Once } +// Close closes the file and releases the archive. +func (f *archiveFile) Close() error { + err := f.File.Close() + f.doneOnce.Do(f.done) + return err +} + +// archiveCloseWait is how long CloseArchives waits for files that are still +// being served before it leaves closing the archive to the background. +var archiveCloseWait = 30 * time.Second + // CloseArchives closes all open archives. +// Archives are removed from the cache immediately, but each one is only +// closed once all files served from it are closed. CloseArchives waits for +// that for a limited time and then leaves closing to the background. func (ui *UI) CloseArchives() { if ui == nil { return } + // Remove archives from the cache, so that no new files are opened from + // them. Do not wait for them while holding the lock, so that requests + // are not blocked. ui.archivesLock.Lock() - defer ui.archivesLock.Unlock() - - // Close archives. - for _, archive := range ui.archives { - if err := archive.Close(); err != nil { - ui.mgr.Warn("failed to close ui archive", "err", err) - } + retired := make([]*archive, 0, len(ui.archives)) + for _, a := range ui.archives { + retired = append(retired, a) } - - // Reset map. clear(ui.archives) + ui.archivesLock.Unlock() + + deadline := time.After(archiveCloseWait) + for _, a := range retired { + released := make(chan struct{}) + go func() { + a.inUse.Wait() + close(released) + }() + + select { + case <-released: + ui.closeArchive(a) + case <-deadline: + ui.mgr.Warn("ui archive still in use, closing it when released") + go func() { + <-released + ui.closeArchive(a) + }() + } + } } // EnableUpgradeLock enables the upgrade lock and closes all open archives. @@ -137,3 +189,10 @@ type instance interface { API() *api.API GetBinaryUpdateFile(name string) (path string, err error) } + +func (ui *UI) closeArchive(a *archive) { + err := a.fs.Close() + if err != nil { + ui.mgr.Warn("failed to close ui archive", "err", err) + } +} diff --git a/service/ui/serve.go b/service/ui/serve.go index 24bda7aaf..0312da6b0 100644 --- a/service/ui/serve.go +++ b/service/ui/serve.go @@ -44,6 +44,9 @@ func (ui *UI) registerRoutes() error { return nil } +// indexFile is the file served for directories and as the SPA fallback. +const indexFile = "index.html" + type archiveServer struct { ui *UI defaultModuleName string @@ -73,63 +76,136 @@ func (bs *archiveServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { resPath, ok := ar.URLVars["resPath"] if !ok || strings.HasSuffix(resPath, "/") { - resPath = "index.html" + resPath = indexFile } - archiveFS, ok := bs.ui.getArchive(moduleName) - if ok { - ServeFileFromArchive(w, r, moduleName, archiveFS, resPath) + readCloser, servedPath, status, err := bs.ui.openArchiveFile(moduleName, resPath) + switch { + case errors.Is(err, errUpgradeInProgress): + http.Error(w, "Resources locked, upgrade in progress.", status) return + case err != nil: + http.Error(w, err.Error(), status) + return + } + defer func() { + _ = readCloser.Close() + }() + + serveFile(w, r, readCloser, servedPath) +} + +var errUpgradeInProgress = errors.New("resources locked, upgrade in progress") + +// openArchiveFile opens the requested file from the archive of the given +// module, loading the archive if needed. +// The file is opened while holding the archives lock and keeps the archive in +// use until it is closed, so that CloseArchives (eg. via EnableUpgradeLock) +// does not close the archive while it is read. Also, no archive is loaded or cached while the upgrade lock is enabled. +func (ui *UI) openArchiveFile(moduleName, resPath string) (file http.File, servedPath string, status int, err error) { + // Fast path: archive is already loaded. + ui.archivesLock.RLock() + a, ok := ui.archives[moduleName] + if ok { + file, servedPath, status, err = a.open(moduleName, resPath) + ui.archivesLock.RUnlock() + return file, servedPath, status, err } + ui.archivesLock.RUnlock() + + // Slow path: load archive. // Check if the upgrade lock is enabled. - if bs.ui.upgradeLock.Load() { - http.Error(w, "Resources locked, upgrade in progress.", http.StatusLocked) - return + if ui.upgradeLock.Load() { + return nil, "", http.StatusLocked, errUpgradeInProgress } - // get file from update system - zipFile, err := bs.ui.instance.GetBinaryUpdateFile(fmt.Sprintf("%s.zip", moduleName)) + // Get file from update system. + // Note: This must not be called while holding the archives lock, as the + // updater holds its index lock while enabling the upgrade lock, which in + // turn acquires the archives lock. + zipFile, err := ui.instance.GetBinaryUpdateFile(fmt.Sprintf("%s.zip", moduleName)) if err != nil { log.Tracef("ui: error loading module %s: %s", moduleName, err) - http.Error(w, err.Error(), http.StatusInternalServerError) - return + return nil, "", http.StatusInternalServerError, err } // Open archive from disk. - archiveFS, err = zipfs.New(zipFile) + newArchiveFS, err := zipfs.New(zipFile) if err != nil { log.Tracef("ui: error prepping module %s: %s", moduleName, err) - http.Error(w, err.Error(), http.StatusInternalServerError) - return + return nil, "", http.StatusInternalServerError, err } - bs.ui.setArchive(moduleName, archiveFS) - ServeFileFromArchive(w, r, moduleName, archiveFS, resPath) + ui.archivesLock.Lock() + defer ui.archivesLock.Unlock() + + switch a, ok = ui.archives[moduleName]; { + case ui.upgradeLock.Load(): + // The upgrade lock was enabled in the meantime, do not keep the archive + // open. This is checked while holding the archives lock, as + // EnableUpgradeLock enables the lock before closing all archives. + _ = newArchiveFS.Close() + return nil, "", http.StatusLocked, errUpgradeInProgress + case ok: + // Another request loaded the archive in the meantime. + _ = newArchiveFS.Close() + default: + a = &archive{fs: newArchiveFS} + ui.archives[moduleName] = a + } + + return a.open(moduleName, resPath) } // ServeFileFromArchive serves a file from the given archive. func ServeFileFromArchive(w http.ResponseWriter, r *http.Request, archiveName string, archiveFS *zipfs.FileSystem, path string) { + readCloser, servedPath, status, err := openFileFromArchive(archiveName, archiveFS, path) + if err != nil { + http.Error(w, err.Error(), status) + return + } + defer func() { + _ = readCloser.Close() + }() + + serveFile(w, r, readCloser, servedPath) +} + +// openFileFromArchive opens the given path from the archive, falling back to +// the index.html if the path does not exist. +func openFileFromArchive(archiveName string, archiveFS *zipfs.FileSystem, path string) (file http.File, servedPath string, status int, err error) { readCloser, err := archiveFS.Open(path) + if err == nil { + // Directories cannot be served, handle them like missing files. + info, statErr := readCloser.Stat() + if statErr == nil && info.IsDir() { + _ = readCloser.Close() + err = fs.ErrNotExist + } + } if err != nil { if errors.Is(err, fs.ErrNotExist) { // Check if there is a base index.html file we can serve instead. var indexErr error - path = "index.html" - readCloser, indexErr = archiveFS.Open(path) + readCloser, indexErr = archiveFS.Open(indexFile) if indexErr != nil { // If we cannot get an index, continue with handling the original error. log.Tracef("ui: requested resource \"%s\" not found in archive %s: %s", path, archiveName, err) - http.Error(w, err.Error(), http.StatusNotFound) - return + return nil, "", http.StatusNotFound, err } - } else { - log.Tracef("ui: error opening module %s: %s", archiveName, err) - http.Error(w, err.Error(), http.StatusInternalServerError) - return + return readCloser, indexFile, http.StatusOK, nil } + + log.Tracef("ui: error opening module %s: %s", archiveName, err) + return nil, "", http.StatusInternalServerError, err } + return readCloser, path, http.StatusOK, nil +} + +// serveFile writes the given file to the response. +func serveFile(w http.ResponseWriter, r *http.Request, file io.Reader, path string) { // set content type _, ok := w.Header()["Content-Type"] if !ok { @@ -139,14 +215,12 @@ func ServeFileFromArchive(w http.ResponseWriter, r *http.Request, archiveName st w.WriteHeader(http.StatusOK) if r.Method != http.MethodHead { - _, err = io.Copy(w, readCloser) + _, err := io.Copy(w, file) if err != nil { log.Errorf("ui: failed to serve file: %s", err) return } } - - _ = readCloser.Close() } // redirectToDefault redirects the request to the default UI module. diff --git a/service/ui/serve_test.go b/service/ui/serve_test.go new file mode 100644 index 000000000..7944e6c06 --- /dev/null +++ b/service/ui/serve_test.go @@ -0,0 +1,348 @@ +package ui + +import ( + "archive/zip" + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/base/api" + "github.com/safing/portmaster/service/mgr" +) + +type testInstance struct { + zipPath string + calls atomic.Int32 + hook func() +} + +func (ti *testInstance) DataDir() string { return "" } + +func (ti *testInstance) API() *api.API { return nil } + +func (ti *testInstance) GetBinaryUpdateFile(_ string) (string, error) { + ti.calls.Add(1) + if ti.hook != nil { + ti.hook() + } + return ti.zipPath, nil +} + +func newTestUI(t *testing.T) (*UI, *testInstance) { + t.Helper() + + zipPath := filepath.Join(t.TempDir(), "portmaster.zip") + f, err := os.Create(zipPath) + require.NoError(t, err) + zw := zip.NewWriter(f) + w, err := zw.Create(indexFile) + require.NoError(t, err) + _, err = w.Write([]byte(strings.Repeat("\n", 1000))) + require.NoError(t, err) + require.NoError(t, zw.Close()) + require.NoError(t, f.Close()) + + ti := &testInstance{zipPath: zipPath} + ui := &UI{ + mgr: mgr.New("UI"), + instance: ti, + archives: make(map[string]*archive), + } + t.Cleanup(ui.CloseArchives) + return ui, ti +} + +func serveTestRequest(ui *UI) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodGet, "/ui/modules/portmaster/index.html", nil) + r = r.WithContext(context.WithValue(r.Context(), api.RequestContextKey, &api.Request{ + Request: r, + URLVars: map[string]string{"moduleName": "portmaster", "resPath": indexFile}, + })) + w := httptest.NewRecorder() + (&archiveServer{ui: ui}).ServeHTTP(w, r) + return w +} + +// countOpenFDs returns how many file descriptors of this process point to path. +func countOpenFDs(t *testing.T, path string) int { + t.Helper() + + entries, err := os.ReadDir("/proc/self/fd") + if err != nil { + t.Skip("cannot inspect open file descriptors:", err) + } + var n int + for _, e := range entries { + target, err := os.Readlink(filepath.Join("/proc/self/fd", e.Name())) + if err == nil && target == path { + n++ + } + } + return n +} + +// TestServeConcurrentWithUpgradeLock checks that serving from a cached archive +// does not race with the archives being closed by the upgrade lock. +func TestServeConcurrentWithUpgradeLock(t *testing.T) { + t.Parallel() + + ui, _ := newTestUI(t) + + var wg sync.WaitGroup + stop := make(chan struct{}) + for range 4 { + wg.Go(func() { + for { + select { + case <-stop: + return + default: + } + serveTestRequest(ui) + // Let the upgrade lock loop run, also with GOMAXPROCS=1. + runtime.Gosched() + } + }) + } + for range 200 { + ui.EnableUpgradeLock() + ui.DisableUpgradeLock() + time.Sleep(100 * time.Microsecond) + } + close(stop) + wg.Wait() +} + +// TestNoArchiveCachedDuringUpgrade checks that a request that started before +// the upgrade lock was enabled does not leave an archive (and its open file) +// cached while the upgrade is in progress. +func TestNoArchiveCachedDuringUpgrade(t *testing.T) { + t.Parallel() + + ui, ti := newTestUI(t) + + // Simulate the upgrade starting right after the request checked the + // upgrade lock, but before it opened the archive. + // Note: The updater holds its index lock (which GetBinaryUpdateFile needs) + // while calling EnableUpgradeLock, so this must not deadlock either. + ti.hook = ui.EnableUpgradeLock + + w := serveTestRequest(ui) + assert.Equal(t, http.StatusLocked, w.Code) + + ui.archivesLock.RLock() + cached := len(ui.archives) + ui.archivesLock.RUnlock() + assert.Equal(t, 0, cached, "no archive may be cached while the upgrade lock is enabled") + assert.Equal(t, 0, countOpenFDs(t, ti.zipPath), "archive file must not be kept open during the upgrade") + + // After the upgrade, the archive is loaded again. + ti.hook = nil + ui.DisableUpgradeLock() + w = serveTestRequest(ui) + assert.Equal(t, http.StatusOK, w.Code) +} + +// TestConcurrentArchiveLoadDoesNotLeak checks that concurrent first requests +// for the same module do not leak an opened archive. +func TestConcurrentArchiveLoadDoesNotLeak(t *testing.T) { + t.Parallel() + + ui, ti := newTestUI(t) + + // Let both requests load the archive at the same time. + ti.hook = func() { + deadline := time.Now().Add(200 * time.Millisecond) + for ti.calls.Load() < 2 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + } + + var wg sync.WaitGroup + for range 2 { + wg.Go(func() { + w := serveTestRequest(ui) + assert.Equal(t, http.StatusOK, w.Code) + }) + } + wg.Wait() + + ui.CloseArchives() + assert.Equal(t, 0, countOpenFDs(t, ti.zipPath), "all opened archives must be closed by CloseArchives") +} + +// writeTestZip writes a zip archive with the given entries to a new file. +// Entry names ending in "/" are directory entries. +func writeTestZip(t *testing.T, entries map[string]string) string { + t.Helper() + + zipPath := filepath.Join(t.TempDir(), "portmaster.zip") + f, err := os.Create(zipPath) + require.NoError(t, err) + zw := zip.NewWriter(f) + for name, content := range entries { + w, err := zw.Create(name) + require.NoError(t, err) + _, err = w.Write([]byte(content)) + require.NoError(t, err) + } + require.NoError(t, zw.Close()) + require.NoError(t, f.Close()) + return zipPath +} + +func serveTestPath(ui *UI, resPath string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodGet, "/ui/modules/portmaster/"+resPath, nil) + r = r.WithContext(context.WithValue(r.Context(), api.RequestContextKey, &api.Request{ + Request: r, + URLVars: map[string]string{"moduleName": "portmaster", "resPath": resPath}, + })) + w := httptest.NewRecorder() + (&archiveServer{ui: ui}).ServeHTTP(w, r) + return w +} + +// TestServeDirectoryEntry checks that a path naming a directory in the archive +// is handled like a non-existent path instead of returning an empty 200. +func TestServeDirectoryEntry(t *testing.T) { + t.Parallel() + + t.Run("fallback to index", func(t *testing.T) { + t.Parallel() + + ui, ti := newTestUI(t) + ti.zipPath = writeTestZip(t, map[string]string{ + "index.html": "index", + "assets/": "", + "assets/app.js": "console.log(1)", + }) + + missing := serveTestPath(ui, "does-not-exist") + require.Equal(t, http.StatusOK, missing.Code) + + w := serveTestPath(ui, "assets") + assert.Equal(t, missing.Code, w.Code) + assert.Equal(t, "index", w.Body.String()) + }) + + t.Run("not found without index", func(t *testing.T) { + t.Parallel() + + ui, ti := newTestUI(t) + ti.zipPath = writeTestZip(t, map[string]string{ + "assets/": "", + "assets/app.js": "console.log(1)", + }) + + missing := serveTestPath(ui, "does-not-exist") + require.Equal(t, http.StatusNotFound, missing.Code) + + w := serveTestPath(ui, "assets") + assert.Equal(t, http.StatusNotFound, w.Code) + }) +} + +// TestCloseArchivesWaitsForServedFiles checks that an archive is only closed +// once the files served from it are closed, and that new requests are not +// blocked meanwhile. +func TestCloseArchivesWaitsForServedFiles(t *testing.T) { //nolint:paralleltest // Modifies archiveCloseWait. + ui, _ := newTestUI(t) + + // Open a file and keep it open, as a slow request would. + file, _, _, err := ui.openArchiveFile("portmaster", indexFile) + require.NoError(t, err) + + closed := make(chan struct{}) + go func() { + ui.CloseArchives() + close(closed) + }() + + // New requests are served while the old archive waits to be closed. + served := make(chan int, 1) + go func() { served <- serveTestRequest(ui).Code }() + select { + case code := <-served: + assert.Equal(t, http.StatusOK, code) + case <-time.After(5 * time.Second): + t.Fatal("request blocked while an archive waits to be closed") + } + + select { + case <-closed: + t.Fatal("archive closed while a file served from it is still open") + case <-time.After(100 * time.Millisecond): + } + + // The open file can still be read. + buf := make([]byte, 6) + _, err = file.Read(buf) + require.NoError(t, err) + assert.Equal(t, "", string(buf)) + + require.NoError(t, file.Close()) + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("archive not closed after the served file was closed") + } +} + +// TestCloseArchivesGivesUpWaiting checks that CloseArchives does not wait +// forever for a file that is not closed, and closes the archive when it is. +func TestCloseArchivesGivesUpWaiting(t *testing.T) { //nolint:paralleltest // Modifies archiveCloseWait. + oldWait := archiveCloseWait + archiveCloseWait = 50 * time.Millisecond + t.Cleanup(func() { archiveCloseWait = oldWait }) + + ui, _ := newTestUI(t) + ui.archivesLock.RLock() + require.Empty(t, ui.archives) + ui.archivesLock.RUnlock() + + file, _, _, err := ui.openArchiveFile("portmaster", indexFile) + require.NoError(t, err) + ui.archivesLock.RLock() + a := ui.archives["portmaster"] + ui.archivesLock.RUnlock() + require.NotNil(t, a) + + closed := make(chan struct{}) + go func() { + ui.CloseArchives() + close(closed) + }() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("CloseArchives did not give up waiting for an open file") + } + + // The archive is closed in the background once the file is closed. + require.NoError(t, file.Close()) + released := make(chan struct{}) + go func() { + a.inUse.Wait() + close(released) + }() + select { + case <-released: + case <-time.After(5 * time.Second): + t.Fatal("archive still in use after the file was closed") + } + + // Closing a served file twice releases the archive only once; releasing + // it twice would panic. + assert.NotPanics(t, func() { _ = file.Close() }) +} diff --git a/service/updates/downloader.go b/service/updates/downloader.go index af51bbad8..3c05b75da 100644 --- a/service/updates/downloader.go +++ b/service/updates/downloader.go @@ -14,6 +14,7 @@ import ( "net/http" "os" "path/filepath" + "time" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/base/utils" @@ -104,8 +105,8 @@ func (d *Downloader) gatherExistingFiles(dir string) error { return err } - // Skip folders. - if entry.IsDir() { + // Skip folders and the upgrade marker. + if entry.IsDir() || isUpgradeMarker(entry.Name()) { return nil } @@ -220,7 +221,75 @@ func (d *Downloader) getArtifact(ctx context.Context, artifact *Artifact, url st return artifactData, nil } +// downloadStallTimeout is how long a download may make no progress, waiting +// for the response or for more data, before it is aborted. +var downloadStallTimeout = time.Minute + +// downloadRetryDelays are the pauses before the retries of a failed download. +// Downloads fail now and then on unstable connections, or when the server or +// a proxy resets the stream; a single failure would fail the whole update. +var downloadRetryDelays = []time.Duration{2 * time.Second, 10 * time.Second} + +// downloadData downloads the given URL, and retries on errors that may be +// temporary. func (d *Downloader) downloadData(ctx context.Context, url string) ([]byte, error) { + for attempt := 0; ; attempt++ { + data, err := d.downloadOnce(ctx, url) + if err == nil || attempt >= len(downloadRetryDelays) || !retryableDownloadError(ctx, err) { + return data, err + } + log.Debugf("updates/%s: download of %s failed, retrying: %s", d.name(), url, err) + select { + case <-time.After(downloadRetryDelays[attempt]): + case <-ctx.Done(): + return nil, err + } + } +} + +// retryableDownloadError reports whether a download that failed with err may +// succeed when tried again. +func retryableDownloadError(ctx context.Context, err error) bool { + if ctx.Err() != nil { + return false // Canceled by the caller. + } + if statusErr, ok := errors.AsType[*httpStatusError](err); ok { + // Client errors (e.g. 404) will not go away; server errors may. + return statusErr.code >= 500 || statusErr.code == http.StatusTooManyRequests + } + return true +} + +// httpStatusError is returned for responses with a status other than 200 OK. +type httpStatusError struct { + code int + status string +} + +func (e *httpStatusError) Error() string { + return fmt.Sprintf("server returned non-OK status: %d %s", e.code, e.status) +} + +func (d *Downloader) name() string { + if d.u == nil { + return "downloader" + } + return d.u.cfg.Name +} + +// downloadOnce downloads the given URL once. +func (d *Downloader) downloadOnce(ctx context.Context, url string) ([]byte, error) { + // Abort the download if it stalls. Without this, a connection on which + // the server stops sending blocks the updater forever, so that no more + // updates are done until a restart. Large files may take long on slow + // connections, so only a stall is limited, not the whole download. + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + stallTimer := time.AfterFunc(downloadStallTimeout, func() { + cancel(fmt.Errorf("%w: no progress for %s", errDownloadStalled, downloadStallTimeout)) + }) + defer stallTimer.Stop() + // Setup request. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) if err != nil { @@ -233,23 +302,50 @@ func (d *Downloader) downloadData(ctx context.Context, url string) ([]byte, erro // Start request with shared http client. resp, err := d.httpClient.Do(req) if err != nil { + cause := context.Cause(ctx) + if errors.Is(cause, errDownloadStalled) { + err = cause + } return nil, fmt.Errorf("failed a get file request to: %w", err) } defer func() { _ = resp.Body.Close() }() // Check for HTTP status errors. if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("server returned non-OK status: %d %s", resp.StatusCode, resp.Status) + return nil, &httpStatusError{code: resp.StatusCode, status: resp.Status} } - // Read the full body and return it. - content, err := io.ReadAll(resp.Body) + // Read the full body and return it. Every read with data resets the + // stall timer. + content, err := io.ReadAll(&progressReader{r: resp.Body, progress: func() { + stallTimer.Reset(downloadStallTimeout) + }}) if err != nil { + cause := context.Cause(ctx) + if errors.Is(cause, errDownloadStalled) { + err = cause + } return nil, fmt.Errorf("failed to read body of response: %w", err) } return content, nil } +var errDownloadStalled = errors.New("download stalled") + +// progressReader calls progress whenever a read returns data. +type progressReader struct { + r io.Reader + progress func() +} + +func (pr *progressReader) Read(p []byte) (int, error) { + n, err := pr.r.Read(p) + if n > 0 { + pr.progress() + } + return n, err +} + // Decompress decompresses the given data according to the specified type. func Decompress(cType string, fileBytes []byte) ([]byte, error) { switch cType { diff --git a/service/updates/downloader_retry_test.go b/service/updates/downloader_retry_test.go new file mode 100644 index 000000000..839f62516 --- /dev/null +++ b/service/updates/downloader_retry_test.go @@ -0,0 +1,52 @@ +package updates + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +// TestDownloadDataRetry checks that a download that fails midway is retried, +// and that a client error is not. +func TestDownloadDataRetry(t *testing.T) { //nolint:paralleltest // Changes the retry delays. + old := downloadRetryDelays + downloadRetryDelays = []time.Duration{10 * time.Millisecond, 10 * time.Millisecond} + t.Cleanup(func() { downloadRetryDelays = old }) + + var flakyCalls, missingCalls atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/flaky", func(w http.ResponseWriter, _ *http.Request) { + if flakyCalls.Add(1) <= 2 { + // Promise more data than is sent, then drop the connection. + w.Header().Set("Content-Length", "100") + _, _ = w.Write([]byte("partial")) + panic(http.ErrAbortHandler) + } + _, _ = w.Write([]byte("complete")) + }) + mux.HandleFunc("/missing", func(w http.ResponseWriter, _ *http.Request) { + missingCalls.Add(1) + http.NotFound(w, nil) + }) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + d := &Downloader{} + data, err := d.downloadData(t.Context(), server.URL+"/flaky") + if err != nil { + t.Fatalf("download failed despite retries: %s", err) + } + if string(data) != "complete" || flakyCalls.Load() != 3 { + t.Errorf("got %q after %d calls, want \"complete\" after 3", data, flakyCalls.Load()) + } + + _, err = d.downloadData(t.Context(), server.URL+"/missing") + if err == nil { + t.Fatal("download of a missing file succeeded") + } + if missingCalls.Load() != 1 { + t.Errorf("a 404 was requested %d times, want 1", missingCalls.Load()) + } +} diff --git a/service/updates/downloader_stall_test.go b/service/updates/downloader_stall_test.go new file mode 100644 index 000000000..a7799899b --- /dev/null +++ b/service/updates/downloader_stall_test.go @@ -0,0 +1,70 @@ +package updates + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +// TestDownloadDataStall checks that a download that stops making progress is +// aborted instead of blocking the updater forever, and that a slow but +// steady download is not. +func TestDownloadDataStall(t *testing.T) { //nolint:paralleltest // Changes the stall timeout. + old := downloadStallTimeout + downloadStallTimeout = 200 * time.Millisecond + t.Cleanup(func() { downloadStallTimeout = old }) + oldDelays := downloadRetryDelays + downloadRetryDelays = nil // Check a single download. + t.Cleanup(func() { downloadRetryDelays = oldDelays }) + + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + mux := http.NewServeMux() + mux.HandleFunc("/no-headers", func(_ http.ResponseWriter, r *http.Request) { + select { + case <-release: + case <-r.Context().Done(): + } + }) + mux.HandleFunc("/stalled-body", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("partial")) + w.(http.Flusher).Flush() //nolint:forcetypeassert // Test server supports flushing. + select { + case <-release: + case <-r.Context().Done(): + } + }) + mux.HandleFunc("/slow-body", func(w http.ResponseWriter, _ *http.Request) { + // 10 chunks with a pause of half the stall timeout: the whole + // download takes longer than the stall timeout, but never stalls. + for range 10 { + _, _ = w.Write([]byte("chunk")) + w.(http.Flusher).Flush() //nolint:forcetypeassert // Test server supports flushing. + time.Sleep(downloadStallTimeout / 2) + } + }) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + + d := &Downloader{} + for _, path := range []string{"/no-headers", "/stalled-body"} { + start := time.Now() + _, err := d.downloadData(t.Context(), server.URL+path) + if !errors.Is(err, errDownloadStalled) { + t.Errorf("%s: got error %v, want %v", path, err, errDownloadStalled) + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Errorf("%s: download was aborted only after %s", path, elapsed) + } + } + + data, err := d.downloadData(t.Context(), server.URL+"/slow-body") + if err != nil { + t.Fatalf("slow but steady download failed: %s", err) + } + if len(data) != 50 { + t.Errorf("got %d bytes, want 50", len(data)) + } +} diff --git a/service/updates/force_update_test.go b/service/updates/force_update_test.go new file mode 100644 index 000000000..2632a75f3 --- /dev/null +++ b/service/updates/force_update_test.go @@ -0,0 +1,59 @@ +package updates + +import ( + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/safing/portmaster/service/mgr" +) + +// newRestartTestUpdater returns an updater with version 1.0.0 installed and +// version 1.0.1 ready in the download directory, which needs a restart. +func newRestartTestUpdater(t *testing.T) (*Updater, string) { + t.Helper() + + installedDir := t.TempDir() + updateDir := t.TempDir() + now := time.Now() + require.NoError(t, GenerateMockFolder(installedDir, rollbackTestName, "1.0.0", now)) + require.NoError(t, GenerateMockFolder(updateDir, rollbackTestName, "1.0.1", now.Add(time.Minute))) + + updater, err := New(&testInstance{}, rollbackTestName, Config{ + Name: rollbackTestName, + Directory: installedDir, + DownloadDirectory: updateDir, + PurgeDirectory: t.TempDir(), + IndexFile: rollbackTestIndex, + AutoDownload: true, + AutoApply: true, + NeedsRestart: true, + Notify: true, + }) + require.NoError(t, err) + return updater, installedDir +} + +func TestUpgradeNeedingRestartReturnsErrRestartRequired(t *testing.T) { + t.Parallel() + + updater, _ := newRestartTestUpdater(t) + err := updater.m.Do("test", func(w *mgr.WorkerCtx) error { + return updater.updateAndUpgrade(w, nil, true, true) + }) + require.ErrorIs(t, err, ErrRestartRequired) + require.ErrorIs(t, err, ErrActionRequired) +} + +func TestForceUpdateNeedingRestartSucceeds(t *testing.T) { + t.Parallel() + + updater, installedDir := newRestartTestUpdater(t) + require.NoError(t, updater.ForceUpdate()) + + index, err := LoadIndex(filepath.Join(installedDir, rollbackTestIndex), updater.cfg.Platform, nil) + require.NoError(t, err) + require.Equal(t, "1.0.1", index.Version) +} diff --git a/service/updates/index.go b/service/updates/index.go index 91b928872..80a3c1a10 100644 --- a/service/updates/index.go +++ b/service/updates/index.go @@ -30,6 +30,9 @@ const currentPlatform = runtime.GOOS + "_" + runtime.GOARCH var zeroVersion = semver.Must(semver.NewVersion("0.0.0")) +// errReservedArtifactFilename is returned for an artifact filename that the updater uses itself. +var errReservedArtifactFilename = errors.New("reserved name") + // Artifact represents a single file with metadata. type Artifact struct { Filename string `json:"Filename"` @@ -207,6 +210,11 @@ func validateArtifactFilename(name string) error { return fmt.Errorf("invalid artifact filename %q: contains ':'", name) } + // Reject the name of the upgrade marker, which is not an artifact. + if isUpgradeMarker(n) { + return fmt.Errorf("invalid artifact filename %q: %w", name, errReservedArtifactFilename) + } + return nil } @@ -446,12 +454,14 @@ func copyAndCheckSHA256Sum(src, dst, sha256sum string, filePermission utils.FSPe tmpDst := dst + ".copy" err = os.WriteFile(tmpDst, fileData, filePermission.AsUnixPermission()) if err != nil { + _ = os.Remove(tmpDst) return fmt.Errorf("write temp dst file: %w", err) } // Rename/Move to actual location. err = os.Rename(tmpDst, dst) if err != nil { + _ = os.Remove(tmpDst) return fmt.Errorf("rename dst file after write: %w", err) } utils.SetFilePermission(dst, filePermission) diff --git a/service/updates/missing_resources_test.go b/service/updates/missing_resources_test.go new file mode 100644 index 000000000..642b306e7 --- /dev/null +++ b/service/updates/missing_resources_test.go @@ -0,0 +1,31 @@ +package updates + +import ( + "errors" + "testing" +) + +var errTestBroken = errors.New("broken") + +func TestMissingResources(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + updater *Updater + want bool + }{ + {"no index", &Updater{}, true}, + {"empty index", &Updater{index: &Index{}}, true}, + {"corrupted", &Updater{ + index: &Index{Artifacts: []*Artifact{{Filename: "a"}}}, + corruptedInstallation: errTestBroken, + }, true}, + {"installed", &Updater{index: &Index{Artifacts: []*Artifact{{Filename: "a"}}}}, false}, + } + for _, tc := range tests { + if got := tc.updater.missingResources(); got != tc.want { + t.Errorf("%s: missingResources() = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/service/updates/module.go b/service/updates/module.go index 1bf432ade..3380e24a9 100644 --- a/service/updates/module.go +++ b/service/updates/module.go @@ -48,6 +48,12 @@ var ( ErrAutoCheckDisabled = errors.New("automatic update checks are disabled") ErrNoUpdateAvailable = errors.New("no update available") ErrActionRequired = errors.New("action required") + // ErrRestartRequired is returned when an upgrade was installed and + // Portmaster must be restarted to use it. + ErrRestartRequired = fmt.Errorf("%w: restart required", ErrActionRequired) + // ErrReadOnlyInstallation is returned when the installation directory + // cannot be written, such as on immutable systems. + ErrReadOnlyInstallation = errors.New("installation directory is read-only") ) // UpdateCommandConfig defines the configuration for a shell command @@ -202,6 +208,17 @@ func New(instance instance, name string, cfg Config) (*Updater, error) { module.updateCheckWorkerMgr = m.NewWorkerMgr("update checker", module.updateCheckWorker, nil) module.upgradeWorkerMgr = m.NewWorkerMgr("upgrader", module.upgradeWorker, nil) + // Restore the installed version, if an upgrade was not committed. Its + // index is loaded below. + if module.hasUpgradeMarker() { + err := module.recoverFromFailedUpgrade(nil) + if err != nil { + log.Errorf("updates/%s: failed to restore files of a failed upgrade from %s: %s", cfg.Name, cfg.PurgeDirectory, err) + } else { + log.Warningf("updates/%s: restored files of a failed upgrade from %s", cfg.Name, cfg.PurgeDirectory) + } + } + // Load index. index, err := LoadIndex(filepath.Join(cfg.Directory, cfg.IndexFile), cfg.Platform, cfg.Verify) if err == nil { @@ -314,6 +331,29 @@ func (u *Updater) updateAndUpgrade(w *mgr.WorkerCtx, indexURLs []string, ignoreV } } + // An upgrade replaces the files in the installation directory. Do not + // start one that cannot finish, as on immutable systems where the + // directory is part of the read-only system image. + err = checkDirWritable(u.cfg.Directory) + if err != nil { + log.Warningf("updates/%s: update to v%s available, but cannot upgrade: %s", u.cfg.Name, downloader.index.Version, err) + if u.cfg.Notify && u.instance.Notifications() != nil { + u.instance.Notifications().Notify(¬ifications.Notification{ + EventID: updateAvailableNotificationID, + Type: notifications.Info, + Title: "New Update Available", + Message: "Portmaster v" + downloader.index.Version + " is available, but Portmaster cannot write to its installation directory " + u.cfg.Directory + ". Please update it through your system's package manager or image.", + AvailableActions: []*notifications.Action{ + { + ID: "ack", + Text: "OK", + }, + }, + }) + } + return fmt.Errorf("%w: %w", ErrReadOnlyInstallation, err) + } + // Check if automatic downloads are enabled. if !u.cfg.AutoDownload && !forceApply { log.Infof("updates/%s: new update to v%s available, action required to download and upgrade", u.cfg.Name, downloader.index.Version) @@ -442,7 +482,7 @@ func (u *Updater) updateAndUpgrade(w *mgr.WorkerCtx, indexURLs []string, ignoreV }) } - return fmt.Errorf("%w: restart required", ErrActionRequired) + return ErrRestartRequired } // Otherwise, trigger restart immediately. @@ -491,9 +531,17 @@ func (u *Updater) upgradeWorker(w *mgr.WorkerCtx) error { // ForceUpdate executes a forced update and upgrade directly and synchronously // and is intended to be used only within a tool, not a service. +// +// An upgrade that needs a restart of Portmaster is a success here: the tool +// installed it, and the service uses it when it is started again. func (u *Updater) ForceUpdate() error { return u.m.Do("update and upgrade", func(w *mgr.WorkerCtx) error { - return u.updateAndUpgrade(w, u.getIndexURLsWithLock(), true, true) + err := u.updateAndUpgrade(w, u.getIndexURLsWithLock(), true, true) + if errors.Is(err, ErrRestartRequired) { + log.Infof("updates/%s: update installed, restart Portmaster to use it", u.cfg.Name) + return nil + } + return err }) } @@ -561,9 +609,14 @@ func (u *Updater) Start() error { // Check for updates automatically, if enabled. if u.cfg.AutoCheck { - u.updateCheckWorkerMgr. - Repeat(updateTaskRepeatDuration). - Delay(15 * time.Second) + u.updateCheckWorkerMgr.Repeat(updateTaskRepeatDuration) + if u.missingResources() { + // Without usable resources, dependent modules (such as the filter + // lists) fail until the first download, so do not wait for it. + u.updateCheckWorkerMgr.Go() + } else { + u.updateCheckWorkerMgr.Delay(15 * time.Second) + } } u.started.SetTo(true) @@ -668,3 +721,12 @@ type instance interface { Notifications() *notifications.Notifications UI() *ui.UI } + +// missingResources reports whether the installed resources are absent or +// unusable, so that an update check should not be delayed. +func (u *Updater) missingResources() bool { + u.indexLock.Lock() + defer u.indexLock.Unlock() + + return u.index == nil || len(u.index.Artifacts) == 0 || u.corruptedInstallation != nil +} diff --git a/service/updates/readonly_test.go b/service/updates/readonly_test.go new file mode 100644 index 000000000..cb282fa6e --- /dev/null +++ b/service/updates/readonly_test.go @@ -0,0 +1,36 @@ +//go:build !windows + +package updates + +import ( + "os" + "path/filepath" + "testing" +) + +func TestCheckDirWritable(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + err := checkDirWritable(dir) + if err != nil { + t.Fatalf("writable dir reported as not writable: %s", err) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 0 { + t.Fatalf("check left %d files behind", len(entries)) + } + + if os.Geteuid() == 0 { + t.Skip("root can write to read-only directories") + } + readOnly := filepath.Join(dir, "ro") + err = os.Mkdir(readOnly, 0o500) + if err != nil { + t.Fatal(err) + } + err = checkDirWritable(readOnly) + if err == nil { + t.Fatal("read-only dir reported as writable") + } +} diff --git a/service/updates/rollback_test.go b/service/updates/rollback_test.go new file mode 100644 index 000000000..8fb40c03c --- /dev/null +++ b/service/updates/rollback_test.go @@ -0,0 +1,347 @@ +package updates + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +const ( + rollbackTestName = "Test" + rollbackTestIndex = "index.json" + + // rollbackTestExecutable is an executable file of both versions. + rollbackTestExecutable = "portmaster-core" + + // rollbackTestIgnored is a file of both versions that tests add to Config.Ignore. + rollbackTestIgnored = "portmaster" +) + +// snapshotDir returns all files below dir (relative path -> content, directories as empty). +func snapshotDir(t *testing.T, dir string) map[string]string { + t.Helper() + + root := os.DirFS(dir) + snapshot := make(map[string]string) + err := fs.WalkDir(root, ".", func(path string, d fs.DirEntry, err error) error { + if err != nil || path == "." { + return err + } + if d.IsDir() { + snapshot[path+"/"] = "" + return nil + } + content, err := fs.ReadFile(root, path) + snapshot[path] = string(content) + return err + }) + if err != nil { + t.Fatal(err) + } + return snapshot +} + +func compareSnapshots(t *testing.T, before, after map[string]string) { + t.Helper() + + for name, content := range after { + beforeContent, ok := before[name] + switch { + case !ok: + t.Errorf("unexpected leftover %q after rollback", name) + case beforeContent != content: + t.Errorf("%q changed by rollback", name) + } + } + for name := range before { + if _, ok := after[name]; !ok { + t.Errorf("%q missing after rollback", name) + } + } +} + +// newRollbackTestUpdater prepares an old version in the installed dir and a new +// version, which has an additional first artifact, in the update dir. +func newRollbackTestUpdater(t *testing.T, ignore []string) (updater *Updater, downloader *Downloader, installedDir string) { + t.Helper() + + installedDir = t.TempDir() + updateDir := t.TempDir() + now := time.Now() + + err := GenerateMockFolder(installedDir, rollbackTestName, "1.0.0", now) + if err != nil { + t.Fatal(err) + } + err = GenerateMockFolder(updateDir, rollbackTestName, "1.0.1", now.Add(1*time.Minute)) + if err != nil { + t.Fatal(err) + } + + updater, err = New(&testInstance{}, rollbackTestName, Config{ + Name: rollbackTestName, + Directory: installedDir, + DownloadDirectory: updateDir, + PurgeDirectory: t.TempDir(), + IndexFile: rollbackTestIndex, + Ignore: ignore, + }) + if err != nil { + t.Fatal(err) + } + + // Add a file that only exists in the new version and sorts before all others. + err = os.WriteFile(filepath.Join(updateDir, "aaa-new-only"), []byte("mock:new-only"), 0o600) + if err != nil { + t.Fatal(err) + } + _ = os.Remove(filepath.Join(updateDir, rollbackTestIndex)) // The index is not an artifact of itself. + index, err := GenerateIndexFromDir(updateDir, IndexScanConfig{Name: rollbackTestName, Version: "1.0.1"}) + if err != nil { + t.Fatal(err) + } + index.Published = now.Add(1 * time.Minute) + if len(index.Artifacts) < 3 || index.Artifacts[0].Filename != "aaa-new-only" { + t.Fatalf("unexpected test index: %+v", index.Artifacts) + } + indexJSON, err := json.Marshal(index) + if err != nil { + t.Fatal(err) + } + err = os.WriteFile(filepath.Join(updateDir, rollbackTestIndex), indexJSON, 0o600) + if err != nil { + t.Fatal(err) + } + + return updater, &Downloader{u: updater, index: index}, installedDir +} + +func TestRollbackRemovesNewOnlyFiles(t *testing.T) { + t.Parallel() + + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + before := snapshotDir(t, installedDir) + + // Make the upgrade fail midway: the last artifact is missing in the download dir. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + err := os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(downloader, true) + if err == nil { + t.Fatal("expected upgrade to fail") + } + compareSnapshots(t, before, snapshotDir(t, installedDir)) +} + +func TestRollbackRestoresIgnoredFileReplacedByArtifact(t *testing.T) { + t.Parallel() + + // "portmaster" is ignored by the upgrade, but the new version has an artifact of that name. + updater, downloader, installedDir := newRollbackTestUpdater(t, []string{rollbackTestIgnored}) + err := os.WriteFile(filepath.Join(installedDir, rollbackTestIgnored), []byte("ignored:portmaster"), 0o600) + if err != nil { + t.Fatal(err) + } + before := snapshotDir(t, installedDir) + + // Make the upgrade fail after "portmaster" was installed: the last artifact is missing. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + if last == rollbackTestIgnored { + t.Fatal("unexpected test index: portmaster must not be the last artifact") + } + err = os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(downloader, true) + if err == nil { + t.Fatal("expected upgrade to fail") + } + compareSnapshots(t, before, snapshotDir(t, installedDir)) +} + +func TestUpgradeIgnoredFiles(t *testing.T) { + t.Parallel() + + // "portmaster" is ignored, but replaced by an artifact; "keep" is ignored and stays. + updater, downloader, installedDir := newRollbackTestUpdater(t, []string{rollbackTestIgnored, "keep"}) + err := os.WriteFile(filepath.Join(installedDir, rollbackTestIgnored), []byte("ignored:portmaster"), 0o600) + if err != nil { + t.Fatal(err) + } + err = os.WriteFile(filepath.Join(installedDir, "keep"), []byte("ignored:keep"), 0o600) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(downloader, true) + if err != nil { + t.Fatalf("upgrade failed: %s", err) + } + installed := snapshotDir(t, installedDir) + if installed[rollbackTestIgnored] != "mock:portmaster" { + t.Errorf("artifact portmaster not installed, got %q", installed[rollbackTestIgnored]) + } + if installed["keep"] != "ignored:keep" { + t.Errorf("ignored file keep changed, got %q", installed["keep"]) + } +} + +func TestRollbackLeavesNoCopyFiles(t *testing.T) { + t.Parallel() + + // "portmaster" is ignored by the upgrade, so it stays in place. + updater, downloader, installedDir := newRollbackTestUpdater(t, []string{"portmaster"}) + + // Replace the file with a non-empty directory: neither rename nor the + // copy fallback can replace it, but the fallback creates "portmaster.copy" first. + blocker := filepath.Join(installedDir, "portmaster") + err := os.Remove(blocker) + if err != nil { + t.Fatal(err) + } + err = os.MkdirAll(blocker, 0o700) + if err != nil { + t.Fatal(err) + } + err = os.WriteFile(filepath.Join(blocker, "keep"), []byte("keep"), 0o600) + if err != nil { + t.Fatal(err) + } + before := snapshotDir(t, installedDir) + + err = updater.upgrade(downloader, true) + if err == nil { + t.Fatal("expected upgrade to fail") + } + compareSnapshots(t, before, snapshotDir(t, installedDir)) +} + +func TestRollbackRestoresDirectoryReplacedByArtifact(t *testing.T) { + t.Parallel() + + // The old version has a directory where the new version has the artifact "portmaster". + const name = "portmaster" + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + oldDir := filepath.Join(installedDir, name) + err := os.Remove(oldDir) + if err != nil { + t.Fatal(err) + } + err = os.MkdirAll(oldDir, 0o750) + if err != nil { + t.Fatal(err) + } + err = os.WriteFile(filepath.Join(oldDir, "keep"), []byte("old:keep"), 0o600) + if err != nil { + t.Fatal(err) + } + before := snapshotDir(t, installedDir) + + // Make the upgrade fail after "portmaster" was installed: the last artifact is missing. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + if last == name { + t.Fatal("unexpected test index: portmaster must not be the last artifact") + } + err = os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(downloader, true) + if err == nil { + t.Fatal("expected upgrade to fail") + } + if strings.Contains(err.Error(), "including recovery") { + t.Errorf("expected recovery to succeed, got: %s", err) + } + info, err := os.Stat(oldDir) + // Windows does not keep Unix permission bits. + if err != nil || !info.IsDir() || (runtime.GOOS != "windows" && info.Mode().Perm() != 0o750) { + t.Fatalf("directory not restored with its permissions: %v, %v", info, err) + } + compareSnapshots(t, before, snapshotDir(t, installedDir)) +} + +// snapshotModes returns the permissions of all files below dir (relative path -> mode). +func snapshotModes(t *testing.T, dir string) map[string]fs.FileMode { + t.Helper() + + modes := make(map[string]fs.FileMode) + err := fs.WalkDir(os.DirFS(dir), ".", func(path string, d fs.DirEntry, err error) error { + if err != nil || path == "." { + return err + } + info, err := d.Info() + if err != nil { + return err + } + modes[path] = info.Mode().Perm() + return nil + }) + if err != nil { + t.Fatal(err) + } + return modes +} + +//nolint:paralleltest // Replaces the package-level renameFile. +func TestRollbackRestoresFilePermissions(t *testing.T) { + if onWindows { + t.Skip("file permissions are ACLs on Windows") + } + + for _, tc := range []struct { + name string + rename func(oldpath, newpath string) error + }{ + {name: "rename", rename: os.Rename}, + {name: "copy fallback", rename: failRename}, + } { + t.Run(tc.name, func(t *testing.T) { + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + + // The old version has an executable and a non-executable file. + for name, mode := range map[string]fs.FileMode{ + rollbackTestExecutable: 0o755, + "assets.zip": 0o644, + } { + err := os.Chmod(filepath.Join(installedDir, name), mode) + if err != nil { + t.Fatal(err) + } + } + before := snapshotModes(t, installedDir) + + // Make the upgrade fail midway: the last artifact is missing in the download dir. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + err := os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + renameFile = tc.rename + defer func() { renameFile = os.Rename }() + + err = updater.upgrade(downloader, true) + if err == nil || strings.Contains(err.Error(), "including recovery") { + t.Fatalf("expected upgrade to fail with a successful recovery, got: %v", err) + } + after := snapshotModes(t, installedDir) + for name, mode := range before { + if after[name] != mode { + t.Errorf("%s: permissions %v before upgrade, %v after rollback", name, mode, after[name]) + } + } + }) + } +} diff --git a/service/updates/signature_test.go b/service/updates/signature_test.go index 7a4f9a0a5..b5aa9e04e 100644 --- a/service/updates/signature_test.go +++ b/service/updates/signature_test.go @@ -17,13 +17,15 @@ func newSigningKey(t *testing.T, name string) (signet *jess.Signet, trustStore * if err != nil { t.Fatal(err) } - if err := signet.AssignUUID(); err != nil { + err = signet.AssignUUID() + if err != nil { t.Fatal(err) } signet.Info = &jess.SignetInfo{Name: name} // Serialize the key into the signet; an envelope treats a signet // without serialized key as a reference into a trust store. - if err := signet.StoreKey(); err != nil { + err = signet.StoreKey() + if err != nil { t.Fatal(err) } @@ -32,7 +34,8 @@ func newSigningKey(t *testing.T, name string) (signet *jess.Signet, trustStore * t.Fatal(err) } trustStore = jess.NewMemTrustStore() - if err := trustStore.StoreSignet(rcpt); err != nil { + err = trustStore.StoreSignet(rcpt) + if err != nil { t.Fatal(err) } return signet, trustStore @@ -48,7 +51,8 @@ func TestParseIndexVerifiesSignature(t *testing.T) { _, otherTrustStore := newSigningKey(t, "other key") dir := t.TempDir() - if err := GenerateMockFolder(dir, "Test", "1.0.0", time.Now()); err != nil { + err := GenerateMockFolder(dir, "Test", "1.0.0", time.Now()) + if err != nil { t.Fatal(err) } index, err := LoadIndex(filepath.Join(dir, "index.json"), "", nil) @@ -64,20 +68,24 @@ func TestParseIndexVerifiesSignature(t *testing.T) { t.Fatal(err) } - if _, err := ParseIndex(signed, "", trustStore); err != nil { + _, err = ParseIndex(signed, "", trustStore) + if err != nil { t.Errorf("signed index must verify: %s", err) } - if _, err := ParseIndex(signed, "", otherTrustStore); err == nil { + _, err = ParseIndex(signed, "", otherTrustStore) + if err == nil { t.Error("index signed with an unknown key must fail") } - if _, err := ParseIndex(unsigned, "", trustStore); err == nil { + _, err = ParseIndex(unsigned, "", trustStore) + if err == nil { t.Error("unsigned index must fail") } tampered := bytes.Replace(signed, []byte(`"Test"`), []byte(`"Tampered"`), 1) if bytes.Equal(tampered, signed) { t.Fatal("test did not tamper with the index") } - if _, err := ParseIndex(tampered, "", trustStore); err == nil { + _, err = ParseIndex(tampered, "", trustStore) + if err == nil { t.Error("tampered index must fail") } } diff --git a/service/updates/updates_test.go b/service/updates/updates_test.go index 1f03b4149..0d5fc0911 100644 --- a/service/updates/updates_test.go +++ b/service/updates/updates_test.go @@ -193,3 +193,66 @@ func GenerateMockFolder(dir, name, version string, published time.Time) error { } return nil } + +func TestFailedPostUpgradeCommandRestoresIndex(t *testing.T) { + t.Parallel() + + stub := &testInstance{} + installedDir := t.TempDir() + updateDir := t.TempDir() + purgeDir := t.TempDir() + now := time.Now() + + err := GenerateMockFolder(installedDir, "Test", "1.0.0", now) + if err != nil { + t.Fatal(err) + } + err = GenerateMockFolder(updateDir, "Test", "1.0.1", now.Add(1*time.Minute)) + if err != nil { + t.Fatal(err) + } + + updater, err := New(stub, "Test", Config{ + Name: "Test", + Directory: installedDir, + DownloadDirectory: updateDir, + PurgeDirectory: purgeDir, + IndexFile: "index.json", + AutoDownload: true, + AutoApply: true, + PostUpgradeCommands: []UpdateCommandConfig{{ + Command: "false", + FailOnError: true, + }}, + }) + if err != nil { + t.Fatal(err) + } + + // The upgrade must fail because of the post-upgrade command and be rolled back. + m := mgr.New("updates rollback test") + err = m.Do("failing update and upgrade", func(w *mgr.WorkerCtx) error { + return updater.updateAndUpgrade(w, nil, false, false) + }) + if err == nil { + t.Fatal("expected upgrade to fail") + } + + // The files on disk have been rolled back to the old version. + diskIndex, err := LoadIndex(filepath.Join(installedDir, "index.json"), updater.cfg.Platform, nil) + if err != nil { + t.Fatal(err) + } + if diskIndex.Version != "1.0.0" { + t.Fatalf("expected rolled back index v1.0.0 on disk, found v%s", diskIndex.Version) + } + + // The active index must match the rolled back files. + index, err := updater.GetIndex() + if err != nil { + t.Fatal(err) + } + if index.Version != diskIndex.Version { + t.Fatalf("active index is v%s, but installed files were rolled back to v%s", index.Version, diskIndex.Version) + } +} diff --git a/service/updates/upgrade.go b/service/updates/upgrade.go index 89da6c8f4..8b724a737 100644 --- a/service/updates/upgrade.go +++ b/service/updates/upgrade.go @@ -6,13 +6,26 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "slices" "strings" + "syscall" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/base/utils" ) +// checkDirWritable checks that files can be created in dir. +func checkDirWritable(dir string) error { + f, err := os.CreateTemp(dir, ".write-check-*") + if err != nil { + return err + } + name := f.Name() + _ = f.Close() + return os.Remove(name) +} + func (u *Updater) upgrade(downloader *Downloader, ignoreVersion bool) error { // Lock index for the upgrade. u.indexLock.Lock() @@ -31,8 +44,24 @@ func (u *Updater) upgrade(downloader *Downloader, ignoreVersion bool) error { defer u.instance.UI().DisableUpgradeLock() } + // A previous upgrade was not committed (its rollback failed, or the process + // stopped during it): files of the installed version are still in the purge + // directory, which the upgrade resets. Restore them first. + if u.hasUpgradeMarker() { + err := u.recoverFromFailedUpgrade(nil) + if err != nil { + return fmt.Errorf("cannot upgrade: files of a failed upgrade in %s cannot be restored: %w", u.cfg.PurgeDirectory, err) + } + // The restored index is the active one now. + index, err := LoadIndex(filepath.Join(u.cfg.Directory, u.cfg.IndexFile), u.cfg.Platform, u.cfg.Verify) + if err == nil { + u.index = index + } + } + // Execute the upgrade. - upgradeError := u.upgradeMoveFiles(downloader) + previousIndex := u.index + installedFiles, upgradeError := u.upgradeMoveFiles(downloader) if upgradeError == nil { // Files upgraded successfully. // Applying post-upgrade tasks, if any. @@ -40,20 +69,31 @@ func (u *Updater) upgrade(downloader *Downloader, ignoreVersion bool) error { } if upgradeError == nil { - return nil + // Commit the upgrade: from now on, the purge directory holds only the + // previous version, which must not be restored anymore. + upgradeError = u.removeUpgradeMarker() + if upgradeError == nil { + return nil + } } // Attempt to recover from failed upgrade. - recoveryErr := u.recoverFromFailedUpgrade() + // The recovery moves the previous files (including the index file) back, + // so the previous index must be active again too. + u.index = previousIndex + recoveryErr := u.recoverFromFailedUpgrade(installedFiles) if recoveryErr == nil { return fmt.Errorf("upgrade failed, but recovery was successful: %w", upgradeError) } - // Recovery failed too. - return fmt.Errorf("upgrade (including recovery) failed: %w", upgradeError) + // Recovery failed too. The upgrade marker stays, so that the files are + // restored on the next start or before the next upgrade. + return fmt.Errorf("upgrade (including recovery) failed: %w (recovery: %w)", upgradeError, recoveryErr) } -func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { +// upgradeMoveFiles moves the new version into place. It returns the names of the +// new version's files that were moved into the main directory, also on failure. +func (u *Updater) upgradeMoveFiles(downloader *Downloader) (installedFiles []string, err error) { // Important: // We assume that the downloader has done its job and all artifacts are verified. // Files will just be moved here. @@ -61,9 +101,14 @@ func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { // Reset purge directory, so that we can do a clean rollback later. _ = os.RemoveAll(u.cfg.PurgeDirectory) - err := utils.EnsureDirectory(u.cfg.PurgeDirectory, utils.PublicReadExecPermission) + err = utils.EnsureDirectory(u.cfg.PurgeDirectory, utils.PublicReadExecPermission) if err != nil { - return fmt.Errorf("failed to create purge directory: %w", err) + return nil, fmt.Errorf("failed to create purge directory: %w", err) + } + // Mark the purge directory before it receives files of the installed version. + err = u.writeUpgradeMarker() + if err != nil { + return nil, err } // Move current version files into purge folder. @@ -73,17 +118,33 @@ func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { files, err := os.ReadDir(u.cfg.Directory) if err != nil { if !errors.Is(err, os.ErrNotExist) { - return fmt.Errorf("read current directory: %w", err) + return nil, fmt.Errorf("read current directory: %w", err) } - err := utils.EnsureDirectory(u.cfg.PurgeDirectory, utils.PublicReadExecPermission) + err := utils.EnsureDirectory(u.cfg.Directory, utils.PublicReadExecPermission) if err != nil { - return fmt.Errorf("create current directory: %w", err) + return nil, fmt.Errorf("create current directory: %w", err) } } else { + // Names the new version installs into the main directory. + newFiles := make(map[string]struct{}, len(downloader.index.Artifacts)+1) + newFiles[u.cfg.IndexFile] = struct{}{} + for _, artifact := range downloader.index.Artifacts { + newFiles[artifact.Filename] = struct{}{} + } + // Move files. for _, file := range files { // Check if file is ignored. + // An ignored file that a new file replaces is moved to the purge dir + // too, so that a rollback can restore it. if slices.Contains(u.cfg.Ignore, file.Name()) { + if _, replaced := newFiles[file.Name()]; !replaced || file.IsDir() { + continue + } + } + // A file with the name of the marker is no artifact (see + // validateArtifactFilename) and would replace the marker. + if isUpgradeMarker(file.Name()) { continue } // ignore PurgeDirectory itself @@ -94,9 +155,9 @@ func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { // Otherwise, move file to purge dir. src := filepath.Join(u.cfg.Directory, file.Name()) dst := filepath.Join(u.cfg.PurgeDirectory, file.Name()) - err := u.moveFile(src, dst, "", utils.PublicReadPermission) + err := u.moveInstalledFile(src, dst) if err != nil { - return fmt.Errorf("failed to move current file %s to purge dir: %w", file.Name(), err) + return nil, fmt.Errorf("failed to move current file %s to purge dir: %w", file.Name(), err) } } } @@ -107,8 +168,9 @@ func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { dst := filepath.Join(u.cfg.Directory, u.cfg.IndexFile) err = u.moveFile(src, dst, "", utils.PublicReadPermission) if err != nil { - return fmt.Errorf("failed to move index file to %s: %w", dst, err) + return nil, fmt.Errorf("failed to move index file to %s: %w", dst, err) } + installedFiles = append(installedFiles, u.cfg.IndexFile) // Move downloaded files to the current version folder. for _, artifact := range downloader.index.Artifacts { @@ -116,8 +178,9 @@ func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { dst = filepath.Join(u.cfg.Directory, artifact.Filename) err = u.moveFile(src, dst, artifact.SHA256, artifact.GetFileMode()) if err != nil { - return fmt.Errorf("failed to move file %s: %w", artifact.Filename, err) + return installedFiles, fmt.Errorf("failed to move file %s: %w", artifact.Filename, err) } else { + installedFiles = append(installedFiles, artifact.Filename) log.Debugf("updates/%s: %s moved", u.cfg.Name, artifact.Filename) } } @@ -126,48 +189,219 @@ func (u *Updater) upgradeMoveFiles(downloader *Downloader) error { u.index = downloader.index log.Infof("updates/%s: update complete (v%s from %s)", u.cfg.Name, u.index.Version, u.index.Published) - return nil + return installedFiles, nil } +// onWindows is true if file permissions are ACLs instead of Unix modes. +const onWindows = runtime.GOOS == "windows" + +// renameFile is os.Rename. Tests replace it to exercise the copy fallback of moveFile. +var renameFile = os.Rename + // moveFile moves a file and falls back to copying if it fails. +// The moved file gets filePermission. func (u *Updater) moveFile(currentPath, newPath string, sha256sum string, filePermission utils.FSPermission) error { + return u.moveFileWithPermission(currentPath, newPath, sha256sum, filePermission, false) +} + +// moveInstalledFile moves a file of the installed version between the main and +// the purge directory. On Unix, the file keeps its permissions, so that a +// rollback restores them: e.g. an executable must stay executable. +// On Windows, it gets PublicReadPermission like before, which grants the same +// ACLs as PublicReadExecPermission there. +func (u *Updater) moveInstalledFile(currentPath, newPath string) error { + return u.moveFileWithPermission(currentPath, newPath, "", utils.PublicReadPermission, !onWindows) +} + +func (u *Updater) moveFileWithPermission(currentPath, newPath string, sha256sum string, filePermission utils.FSPermission, keepUnixMode bool) error { // Try to simply move file. - err := os.Rename(currentPath, newPath) + err := renameFile(currentPath, newPath) if err == nil { // Moving was successful, return. - utils.SetFilePermission(newPath, filePermission) + if keepUnixMode { + // The file kept its permissions. + return nil + } + // A moved directory (of the old version) keeps its permissions: file + // permissions would make its contents inaccessible. + info, statErr := os.Lstat(newPath) + if statErr != nil || !info.IsDir() { + _ = utils.SetFilePermission(newPath, filePermission) + } return nil } log.Tracef("updates/%s: failed to move to %q, falling back to copy+delete: %s", u.cfg.Name, newPath, err) + // The copy must get the permissions of the source. + var srcInfo os.FileInfo + if keepUnixMode { + srcInfo, err = os.Stat(currentPath) + if err != nil { + return fmt.Errorf("move failed, copy+delete fallback failed: %w", err) + } + } + // Copy and check the checksum while we are at it. err = copyAndCheckSHA256Sum(currentPath, newPath, sha256sum, filePermission) if err != nil { return fmt.Errorf("move failed, copy+delete fallback failed: %w", err) } + if keepUnixMode { + err = os.Chmod(newPath, srcInfo.Mode().Perm()) + if err != nil { + // The source is still in place: remove the copy and keep the source. + _ = os.Remove(newPath) + return fmt.Errorf("move failed, copy+delete fallback failed to set permissions: %w", err) + } + } + + // Complete the move: the source must not remain, e.g. an old file in the main directory. + // The copy is in place, so a source that cannot be deleted (e.g. a file in + // use on Windows) does not fail the move. It is left behind as before. + err = os.Remove(currentPath) + if err != nil { + log.Warningf("updates/%s: copied %q to %q, but failed to delete the source: %s", u.cfg.Name, currentPath, newPath, err) + } return nil } // recoverFromFailedUpgrade attempts to roll back any moved files by the upgrade process. -func (u *Updater) recoverFromFailedUpgrade() error { +// installedFiles are the names of the new version's files that the upgrade moved +// into the main directory. +func (u *Updater) recoverFromFailedUpgrade(installedFiles []string) error { // Get list of files from purge dir. files, err := os.ReadDir(u.cfg.PurgeDirectory) if err != nil { return err } + files = slices.DeleteFunc(files, func(file os.DirEntry) bool { + return isUpgradeMarker(file.Name()) + }) + + // Remember which files had an old counterpart. + purged := make(map[string]struct{}, len(files)) + for _, file := range files { + purged[file.Name()] = struct{}{} + } // Move all files back to main dir. + var restoreErrs []error for _, file := range files { purgedFile := filepath.Join(u.cfg.PurgeDirectory, file.Name()) activeFile := filepath.Join(u.cfg.Directory, file.Name()) - err := u.moveFile(purgedFile, activeFile, "", utils.PublicReadPermission) + if file.IsDir() { + // A directory cannot be moved onto a file. The old version had this + // directory in the main directory, so a file in its place was + // installed by the upgrade: remove it. + info, err := os.Lstat(activeFile) + if err == nil && !info.IsDir() { + err = os.Remove(activeFile) + if err != nil { + log.Warningf("updates/%s: failed to remove new file %s while rolling back: %s", u.cfg.Name, file.Name(), err) + } + } + } + err := u.moveInstalledFile(purgedFile, activeFile) if err != nil { - // Only warn and continue to recover as many files as possible. + // Continue to recover as many files as possible, but report the + // failure: the file is only in the purge directory now. log.Warningf("updates/%s: failed to roll back file %s: %s", u.cfg.Name, file.Name(), err) + restoreErrs = append(restoreErrs, fmt.Errorf("roll back %s: %w", file.Name(), err)) + } + } + + // Remove files of the new version that had no counterpart in the old + // version: moving the old files back does not replace them. + // Only files that this upgrade installed are removed, never anything that + // was purged (it was restored above) or is ignored by the upgrade. + for _, name := range installedFiles { + if _, ok := purged[name]; ok || slices.Contains(u.cfg.Ignore, name) { + continue } + err := os.Remove(filepath.Join(u.cfg.Directory, name)) + if err != nil && !errors.Is(err, os.ErrNotExist) { + log.Warningf("updates/%s: failed to remove new file %s while rolling back: %s", u.cfg.Name, name, err) + } + } + + if len(restoreErrs) > 0 { + return errors.Join(restoreErrs...) } + // All files of the installed version are back in the main directory. + return u.removeUpgradeMarker() +} + +// upgradeMarkerName is the name of the upgrade marker in the purge directory. +// The marker exists while the upgrade is not committed: from before the +// installed version is moved to the purge directory until the new version is +// completely installed, or until the installed version is completely +// restored. While it exists, the purge directory holds files of the installed +// version: they are restored on start and before the next upgrade, instead of +// being deleted. It survives a restart, unlike state in memory. +// +// Phases of an upgrade and what the marker means for them: +// - Crash while moving the installed version to the purge directory: the +// restore moves the purged files back, the installed version is complete. +// - Crash while moving the new version in: the restore moves the installed +// version back over the new files. Files that only the new version has are +// left in the main directory, as the installed files are not recorded. +// - Failed rollback: the marker stays and the restore is retried; until it +// succeeds, upgrades are refused and the purge directory is kept. +// - Successful upgrade: the marker is removed as the last step of the +// upgrade, after the post-upgrade commands, so a restart afterwards does +// not restore (downgrade to) the previous version that stays in the purge +// directory. A crash right before the removal leaves the marker: the +// upgrade is then not committed and the restart rolls it back, which +// restores the complete previous version. If the marker cannot be +// removed, the upgrade fails and is rolled back. +// +// The name and its prefix are rejected as artifact filenames, so the marker +// cannot collide with an artifact. +const upgradeMarkerName = "portmaster-upgrade-uncommitted.marker" + +// isUpgradeMarker reports whether name is the upgrade marker or its temporary file. +func isUpgradeMarker(name string) bool { + return strings.HasPrefix(strings.ToLower(name), upgradeMarkerName) +} + +func (u *Updater) upgradeMarkerPath() string { + return filepath.Join(u.cfg.PurgeDirectory, upgradeMarkerName) +} + +// hasUpgradeMarker reports whether the purge directory holds files of an +// upgrade that was not committed. If that cannot be determined, it reports +// true, so that the files are not deleted. A purge directory that does not +// exist or is not a directory has no marker. +func (u *Updater) hasUpgradeMarker() bool { + _, err := os.Lstat(u.upgradeMarkerPath()) + return !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.ENOTDIR) +} + +// writeUpgradeMarker atomically creates the upgrade marker. +func (u *Updater) writeUpgradeMarker() error { + path := u.upgradeMarkerPath() + tmpPath := path + ".tmp" + content := "The upgrade of " + u.cfg.Name + " is not committed: the files in this directory belong to the installed version and are restored on the next start or upgrade.\n" + err := os.WriteFile(tmpPath, []byte(content), 0o600) + if err == nil { + err = os.Rename(tmpPath, path) + } + if err != nil { + _ = os.Remove(tmpPath) + return fmt.Errorf("failed to write upgrade marker: %w", err) + } + return nil +} + +// removeUpgradeMarker removes the upgrade marker, which commits the state of +// the main directory. +func (u *Updater) removeUpgradeMarker() error { + err := os.Remove(u.upgradeMarkerPath()) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("failed to remove upgrade marker: %w", err) + } return nil } diff --git a/service/updates/upgrade_marker_test.go b/service/updates/upgrade_marker_test.go new file mode 100644 index 000000000..6705c78fa --- /dev/null +++ b/service/updates/upgrade_marker_test.go @@ -0,0 +1,425 @@ +package updates + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +const ( + markerTestOldContent = "old:portmaster-core" + markerTestOldVersion = "1.0.0" + markerTestNewVersion = "1.0.1" +) + +// failedRollbackState is the state after an upgrade whose rollback could not +// restore the old version of rollbackTestExecutable. +type failedRollbackState struct { + updater *Updater + downloader *Downloader + installedDir string + before map[string]string // Main directory before the upgrade. + purged string // Unrestored old file in the purge directory. + blocker string // Blocks the restore of purged. +} + +// newFailedRollbackState runs an upgrade that fails and whose rollback cannot +// restore one file. It leaves renameFile replaced: the restore of that file +// keeps failing until unblock is called. +func newFailedRollbackState(t *testing.T) *failedRollbackState { + t.Helper() + + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + s := &failedRollbackState{ + updater: updater, + downloader: downloader, + installedDir: installedDir, + purged: filepath.Join(updater.cfg.PurgeDirectory, rollbackTestExecutable), + blocker: filepath.Join(installedDir, rollbackTestExecutable+".copy"), + } + + // Give the old file distinct content to tell it apart from the new one. + err := os.WriteFile(filepath.Join(installedDir, rollbackTestExecutable), []byte(markerTestOldContent), 0o600) + if err != nil { + t.Fatal(err) + } + s.before = snapshotDir(t, installedDir) + + // Make the upgrade fail after the new file was installed: the last artifact is missing. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + if last == rollbackTestExecutable { + t.Fatalf("unexpected test index: %s must not be the last artifact", rollbackTestExecutable) + } + err = os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + // Make the restore of the old file fail: the rename fails and a directory + // blocks the temporary file of the copy fallback. + renameFile = func(oldpath, newpath string) error { + if oldpath == s.purged { + err := os.MkdirAll(s.blocker, 0o700) + if err != nil { + return err + } + return failRename(oldpath, newpath) + } + return os.Rename(oldpath, newpath) + } + t.Cleanup(func() { renameFile = os.Rename }) + + err = updater.upgrade(downloader, true) + if err == nil || !strings.Contains(err.Error(), "including recovery") { + t.Fatalf("expected upgrade to report a failed recovery, got: %v", err) + } + s.checkPurged(t, "after failed rollback") + return s +} + +// unblock makes the restore of the purged file possible again. +func (s *failedRollbackState) unblock(t *testing.T) { + t.Helper() + + renameFile = os.Rename + err := os.RemoveAll(s.blocker) + if err != nil { + t.Fatal(err) + } +} + +func (s *failedRollbackState) checkPurged(t *testing.T, step string) { + t.Helper() + + content, err := os.ReadFile(s.purged) + if err != nil || string(content) != markerTestOldContent { + t.Fatalf("%s: old file not kept in purge directory: %q, %v", step, content, err) + } +} + +// checkRestored checks that the main directory holds exactly the old version. +func (s *failedRollbackState) checkRestored(t *testing.T) { + t.Helper() + + compareSnapshots(t, s.before, snapshotDir(t, s.installedDir)) +} + +// restartUpdater simulates a restart: it returns a new Updater on the same directories. +func restartUpdater(t *testing.T, u *Updater) *Updater { + t.Helper() + + restarted, err := New(&testInstance{}, u.cfg.Name, u.cfg) + if err != nil { + t.Fatal(err) + } + return restarted +} + +func markerPath(u *Updater) string { + return filepath.Join(u.cfg.PurgeDirectory, upgradeMarkerName) +} + +func checkMarker(t *testing.T, u *Updater, step string, want bool) { + t.Helper() + + _, err := os.Lstat(markerPath(u)) + if exists := err == nil; exists != want { + t.Errorf("%s: upgrade marker exists: %v, want %v (%v)", step, exists, want, err) + } +} + +// A restart between a failed rollback and the next upgrade must not lose the +// files that the rollback could not restore. +// +//nolint:paralleltest // Replaces the package-level renameFile. +func TestUpgradeAfterRestartRestoresFilesOfFailedRollback(t *testing.T) { + s := newFailedRollbackState(t) + + // Restart while the restore still fails: the start-up restore fails too. + updater := restartUpdater(t, s.updater) + s.checkPurged(t, "after restart") + + // Once the cause is gone, the next upgrade restores the file first. The + // upgrade itself fails then (the downloads were consumed) and is rolled back. + s.unblock(t) + err := updater.upgrade(s.downloader, true) + if err == nil || strings.Contains(err.Error(), "including recovery") { + t.Errorf("expected upgrade to fail with a successful recovery, got: %v", err) + } + s.checkRestored(t) +} + +// The upgrade is refused while the files of a failed rollback cannot be +// restored, also after a restart, and the purge directory is not touched. +// +//nolint:paralleltest // Replaces the package-level renameFile. +func TestUpgradeRefusedWhileMarkedFilesCannotBeRestored(t *testing.T) { + s := newFailedRollbackState(t) + checkMarker(t, s.updater, "after failed rollback", true) + + for _, step := range []string{"without restart", "after restart"} { + updater := s.updater + if step == "after restart" { + updater = restartUpdater(t, s.updater) + } + purgeBefore := snapshotDir(t, updater.cfg.PurgeDirectory) + err := updater.upgrade(s.downloader, true) + if err == nil || !strings.Contains(err.Error(), "cannot be restored") { + t.Errorf("%s: expected upgrade to be refused, got: %v", step, err) + } + s.checkPurged(t, step) + checkMarker(t, updater, step, true) + + // Only the file that cannot be restored is left. + purgeAfter := snapshotDir(t, updater.cfg.PurgeDirectory) + compareSnapshots(t, purgeBefore, purgeAfter) + for name := range purgeAfter { + if name != rollbackTestExecutable && name != upgradeMarkerName { + t.Errorf("%s: unexpected file %q in purge directory", step, name) + } + } + } +} + +// The start-up restores the files of an upgrade that was not committed. +// +//nolint:paralleltest // Replaces the package-level renameFile. +func TestStartRestoresFilesOfFailedRollback(t *testing.T) { + s := newFailedRollbackState(t) + s.unblock(t) + + updater := restartUpdater(t, s.updater) + s.checkRestored(t) + checkMarker(t, updater, "after start-up restore", false) + for name := range snapshotDir(t, updater.cfg.PurgeDirectory) { + t.Errorf("unexpected file %q left in purge directory", name) + } + if updater.index == nil || updater.index.Version != markerTestOldVersion { + t.Errorf("restored index not loaded: %+v", updater.index) + } + + // The next upgrade works normally: it installs the new version. + _, downloader, _ := newRollbackTestUpdater(t, nil) + updater.cfg.DownloadDirectory = downloader.u.cfg.DownloadDirectory + err := updater.upgrade(downloader, true) + if err != nil { + t.Fatalf("upgrade after restore failed: %s", err) + } + checkMarker(t, updater, "after upgrade", false) +} + +// errSimulatedCrash stops an upgrade like a crash: nothing is rolled back. +type errSimulatedCrash struct{} + +// crashUpgrade runs an upgrade that stops (without rollback) when crashAt is moved. +func crashUpgrade(t *testing.T, updater *Updater, downloader *Downloader, crashAt string) { + t.Helper() + + renameFile = func(oldpath, newpath string) error { + if oldpath == crashAt { + panic(errSimulatedCrash{}) + } + return os.Rename(oldpath, newpath) + } + defer func() { + renameFile = os.Rename + if r := recover(); r != (errSimulatedCrash{}) { + t.Fatalf("expected the upgrade to crash, got: %v", r) + } + }() + _ = updater.upgrade(downloader, true) +} + +// A restart after a crash during the upgrade restores the installed version. +// +//nolint:paralleltest // Replaces the package-level renameFile. +func TestStartRestoresFilesOfCrashedUpgrade(t *testing.T) { + for _, tc := range []struct { + name string + crashAt func(u *Updater, d *Downloader) string + // newOnly is left in the main directory: the restore does not know + // which files the crashed upgrade installed. + newOnly bool + }{ + { + name: "while purging the installed version", + crashAt: func(u *Updater, _ *Downloader) string { + return filepath.Join(u.cfg.Directory, rollbackTestExecutable) + }, + }, + { + name: "while installing the new version", + crashAt: func(u *Updater, d *Downloader) string { + return filepath.Join(u.cfg.DownloadDirectory, d.index.Artifacts[len(d.index.Artifacts)-1].Filename) + }, + newOnly: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + before := snapshotDir(t, installedDir) + + crashUpgrade(t, updater, downloader, tc.crashAt(updater, downloader)) + checkMarker(t, updater, "after crash", true) + + restarted := restartUpdater(t, updater) + after := snapshotDir(t, installedDir) + if tc.newOnly { + if _, ok := after["aaa-new-only"]; !ok { + t.Error("expected the new-only file to be left") + } + delete(after, "aaa-new-only") + } + compareSnapshots(t, before, after) + checkMarker(t, restarted, "after restart", false) + if restarted.index == nil || restarted.index.Version != markerTestOldVersion { + t.Errorf("restored index not loaded: %+v", restarted.index) + } + if restarted.corruptedInstallation != nil { + t.Errorf("restored installation reported as corrupted: %s", restarted.corruptedInstallation) + } + }) + } +} + +// The marker is written before the installed version is moved to the purge +// directory and removed when the upgrade is committed: a restart after a +// successful upgrade must not restore (downgrade to) the old version. +// +//nolint:paralleltest // Replaces the package-level renameFile. +func TestUpgradeMarkerLifecycle(t *testing.T) { + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + + // The purge directory of a previous successful upgrade is reset. + err := os.MkdirAll(updater.cfg.PurgeDirectory, 0o700) + if err != nil { + t.Fatal(err) + } + stale := filepath.Join(updater.cfg.PurgeDirectory, "stale") + err = os.WriteFile(stale, []byte("stale"), 0o600) + if err != nil { + t.Fatal(err) + } + + var purgedWithoutMarker []string + renameFile = func(oldpath, newpath string) error { + if filepath.Dir(newpath) == updater.cfg.PurgeDirectory { + _, err := os.Lstat(markerPath(updater)) + if err != nil { + purgedWithoutMarker = append(purgedWithoutMarker, oldpath) + } + } + return os.Rename(oldpath, newpath) + } + defer func() { renameFile = os.Rename }() + + err = updater.upgrade(downloader, true) + if err != nil { + t.Fatalf("upgrade failed: %s", err) + } + if len(purgedWithoutMarker) > 0 { + t.Errorf("files moved to the purge directory before the marker was written: %v", purgedWithoutMarker) + } + _, err = os.Lstat(stale) + if err == nil { + t.Error("purge directory of a previous upgrade not reset") + } + checkMarker(t, updater, "after upgrade", false) + + // The old version stays in the purge directory, but is not restored. + _, err = os.Lstat(filepath.Join(updater.cfg.PurgeDirectory, rollbackTestExecutable)) + if err != nil { + t.Errorf("old version not in purge directory: %s", err) + } + upgraded := snapshotDir(t, installedDir) + restarted := restartUpdater(t, updater) + compareSnapshots(t, upgraded, snapshotDir(t, installedDir)) + if restarted.index == nil || restarted.index.Version != markerTestNewVersion { + t.Errorf("upgraded index not loaded after restart: %+v", restarted.index) + } +} + +// The marker is never restored into the main directory, never treated as a +// purged file or as an existing artifact, and cannot be an artifact. +// +//nolint:paralleltest // Replaces the package-level renameFile. +func TestUpgradeMarkerIsNotAFile(t *testing.T) { + s := newFailedRollbackState(t) + checkMarker(t, s.updater, "after failed rollback", true) + + // The marker is not an existing file that an artifact could be copied from. + d := &Downloader{u: s.updater} + err := d.gatherExistingFiles(s.updater.cfg.PurgeDirectory) + if err != nil { + t.Fatal(err) + } + for _, path := range d.existingFiles { + if isUpgradeMarker(filepath.Base(path)) { + t.Errorf("marker gathered as existing file: %s", path) + } + } + if len(d.existingFiles) != 1 { + t.Errorf("expected only the purged file to be gathered, got %v", d.existingFiles) + } + + // The marker is not restored. + s.unblock(t) + err = s.updater.recoverFromFailedUpgrade(nil) + if err != nil { + t.Fatalf("restore failed: %s", err) + } + s.checkRestored(t) + checkMarker(t, s.updater, "after restore", false) + + // An artifact cannot have the name of the marker. + for _, name := range []string{upgradeMarkerName, upgradeMarkerName + ".tmp", strings.ToUpper(upgradeMarkerName)} { + if validateArtifactFilename(name) == nil { + t.Errorf("artifact filename %q accepted", name) + } + } +} + +// A file with the name of the marker in the main directory is not moved to +// the purge directory, where it would replace the marker. +func TestUpgradeKeepsMarkerNamedFileInMainDirectory(t *testing.T) { + t.Parallel() + + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + stray := filepath.Join(installedDir, upgradeMarkerName) + err := os.WriteFile(stray, []byte("stray"), 0o600) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(downloader, true) + if err != nil { + t.Fatalf("upgrade failed: %s", err) + } + content, err := os.ReadFile(stray) + if err != nil || string(content) != "stray" { + t.Errorf("file with the marker name not kept in main directory: %q, %v", content, err) + } + checkMarker(t, updater, "after upgrade", false) +} + +// A file in place of the purge directory has no marker and is replaced as before. +func TestUpgradeReplacesFileAtPurgeDirectory(t *testing.T) { + t.Parallel() + + updater, downloader, _ := newRollbackTestUpdater(t, nil) + err := os.RemoveAll(updater.cfg.PurgeDirectory) + if err != nil { + t.Fatal(err) + } + err = os.WriteFile(updater.cfg.PurgeDirectory, []byte("file"), 0o600) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(downloader, true) + if err != nil { + t.Fatalf("upgrade failed: %s", err) + } + checkMarker(t, updater, "after upgrade", false) +} diff --git a/service/updates/upgrade_test.go b/service/updates/upgrade_test.go new file mode 100644 index 000000000..50097ec2b --- /dev/null +++ b/service/updates/upgrade_test.go @@ -0,0 +1,225 @@ +package updates + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestUpgradeCreatesMissingMainDirectory(t *testing.T) { + t.Parallel() + + installedDir := filepath.Join(t.TempDir(), "installed") + updateDir := t.TempDir() + err := GenerateMockFolder(updateDir, rollbackTestName, "1.0.1", time.Now()) + if err != nil { + t.Fatal(err) + } + + updater, err := New(&testInstance{}, rollbackTestName, Config{ + Name: rollbackTestName, + Directory: installedDir, + DownloadDirectory: updateDir, + PurgeDirectory: t.TempDir(), + IndexFile: rollbackTestIndex, + }) + if err != nil { + t.Fatal(err) + } + index, err := LoadIndex(filepath.Join(updateDir, rollbackTestIndex), currentPlatform, nil) + if err != nil { + t.Fatal(err) + } + + // New creates the main directory, but it may be gone by the time of the upgrade. + err = os.RemoveAll(installedDir) + if err != nil { + t.Fatal(err) + } + + err = updater.upgrade(&Downloader{u: updater, index: index}, true) + if err != nil { + t.Fatalf("upgrade into missing main directory failed: %s", err) + } + for _, name := range append([]string{rollbackTestIndex}, artifactNames(index)...) { + _, err := os.Stat(filepath.Join(installedDir, name)) + if err != nil { + t.Errorf("%s not installed: %s", name, err) + } + } +} + +func artifactNames(index *Index) []string { + names := make([]string, 0, len(index.Artifacts)) + for _, artifact := range index.Artifacts { + names = append(names, artifact.Filename) + } + return names +} + +var errSimulatedCrossDevice = errors.New("simulated cross-device link") + +// failRename simulates a rename that is not possible, e.g. across file systems. +func failRename(oldpath, newpath string) error { + return &os.LinkError{Op: "rename", Old: oldpath, New: newpath, Err: errSimulatedCrossDevice} +} + +//nolint:paralleltest // Replaces the package-level renameFile. +func TestUpgradeCopyFallbackRemovesSource(t *testing.T) { + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + + // A file of the old version that the new version does not have. + err := os.WriteFile(filepath.Join(installedDir, "zzz-old-only"), []byte("mock:old-only"), 0o600) + if err != nil { + t.Fatal(err) + } + + renameFile = failRename + defer func() { renameFile = os.Rename }() + + err = updater.upgrade(downloader, true) + if err != nil { + t.Fatalf("upgrade failed: %s", err) + } + + // The main directory must hold exactly the new version. + installed := snapshotDir(t, installedDir) + for _, name := range append([]string{rollbackTestIndex}, artifactNames(downloader.index)...) { + if _, ok := installed[name]; !ok { + t.Errorf("%s not installed", name) + } + delete(installed, name) + } + for name := range installed { + t.Errorf("unexpected file %q in main directory after upgrade", name) + } + + // The old version must be in the purge directory only, the downloads must be gone. + _, err = os.Stat(filepath.Join(updater.cfg.PurgeDirectory, "zzz-old-only")) + if err != nil { + t.Errorf("old file not in purge directory: %s", err) + } + for name := range snapshotDir(t, updater.cfg.DownloadDirectory) { + t.Errorf("unexpected file %q left in download directory", name) + } +} + +//nolint:paralleltest // Replaces the package-level renameFile. +func TestRollbackWithCopyFallback(t *testing.T) { + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + before := snapshotDir(t, installedDir) + + // Make the upgrade fail midway: the last artifact is missing in the download dir. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + err := os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + renameFile = failRename + defer func() { renameFile = os.Rename }() + + err = updater.upgrade(downloader, true) + if err == nil { + t.Fatal("expected upgrade to fail") + } + compareSnapshots(t, before, snapshotDir(t, installedDir)) + for name := range snapshotDir(t, updater.cfg.PurgeDirectory) { + t.Errorf("unexpected file %q left in purge directory after rollback", name) + } +} + +//nolint:paralleltest // Replaces the package-level renameFile. +func TestRollbackReportsAndKeepsUnrestoredFile(t *testing.T) { + updater, downloader, installedDir := newRollbackTestUpdater(t, nil) + + // Give the old file distinct content to tell it apart from the new one. + const name = rollbackTestExecutable + const oldContent = "old:portmaster-core" + err := os.WriteFile(filepath.Join(installedDir, name), []byte(oldContent), 0o600) + if err != nil { + t.Fatal(err) + } + // It is executable, which the restore must keep (only checked on Unix). + err = os.Chmod(filepath.Join(installedDir, name), 0o755) //nolint:gosec // An executable of the installed version. + if err != nil { + t.Fatal(err) + } + before := snapshotDir(t, installedDir) + + // Make the upgrade fail after the new file was installed: the last artifact is missing. + last := downloader.index.Artifacts[len(downloader.index.Artifacts)-1].Filename + if last == name { + t.Fatalf("unexpected test index: %s must not be the last artifact", name) + } + err = os.Remove(filepath.Join(updater.cfg.DownloadDirectory, last)) + if err != nil { + t.Fatal(err) + } + + // Make the restore of the old file fail: the rename fails and a directory + // blocks the temporary file of the copy fallback. + purged := filepath.Join(updater.cfg.PurgeDirectory, name) + blocker := filepath.Join(installedDir, name+".copy") + renameFile = func(oldpath, newpath string) error { + if oldpath == purged { + err := os.MkdirAll(blocker, 0o700) + if err != nil { + return err + } + return failRename(oldpath, newpath) + } + return os.Rename(oldpath, newpath) + } + defer func() { renameFile = os.Rename }() + + err = updater.upgrade(downloader, true) + if err == nil || !strings.Contains(err.Error(), "including recovery") { + t.Errorf("expected upgrade to report a failed recovery, got: %v", err) + } + checkPurgedFile := func(step string) { + t.Helper() + content, err := os.ReadFile(purged) + if err != nil || string(content) != oldContent { + t.Errorf("%s: old file not kept in purge directory: %q, %v", step, content, err) + } + } + checkPurgedFile("after failed recovery") + + // All other files must be restored. + after := snapshotDir(t, installedDir) + for _, ignore := range []string{name, name + ".copy/"} { + delete(before, ignore) + delete(after, ignore) + } + compareSnapshots(t, before, after) + + // The next upgrade must not delete the unrestored file while it cannot be restored. + err = updater.upgrade(downloader, true) + if err == nil { + t.Error("expected upgrade to be refused while an old file cannot be restored") + } + checkPurgedFile("after refused upgrade") + + // Once the cause is gone, the next upgrade restores the file first. + renameFile = os.Rename + err = os.RemoveAll(blocker) + if err != nil { + t.Fatal(err) + } + _ = updater.upgrade(downloader, true) // Fails: the downloads were consumed. + content, err := os.ReadFile(filepath.Join(installedDir, name)) + if err != nil || string(content) != oldContent { + t.Errorf("old file not restored by the next upgrade: %q, %v", content, err) + } + info, err := os.Stat(filepath.Join(installedDir, name)) + if err != nil { + t.Fatal(err) + } + if !onWindows && info.Mode().Perm() != 0o755 { + t.Errorf("old file not restored with its permissions by the next upgrade: %v", info.Mode()) + } +} diff --git a/spn/access/account/auth.go b/spn/access/account/auth.go deleted file mode 100644 index d93e6bf59..000000000 --- a/spn/access/account/auth.go +++ /dev/null @@ -1,65 +0,0 @@ -package account - -import ( - "errors" - "net/http" -) - -// Authentication Headers. -const ( - AuthHeaderDevice = "Device-17" - AuthHeaderToken = "Token-17" - AuthHeaderNextToken = "Next-Token-17" - AuthHeaderNextTokenDeprecated = "Next_token_17" -) - -// Errors. -var ( - ErrMissingDeviceID = errors.New("missing device ID") - ErrMissingToken = errors.New("missing token") -) - -// AuthToken holds an authentication token. -type AuthToken struct { - Device string - Token string -} - -// GetAuthTokenFromRequest extracts an authentication token from a request. -func GetAuthTokenFromRequest(request *http.Request) (*AuthToken, error) { - device := request.Header.Get(AuthHeaderDevice) - if device == "" { - return nil, ErrMissingDeviceID - } - token := request.Header.Get(AuthHeaderToken) - if token == "" { - return nil, ErrMissingToken - } - - return &AuthToken{ - Device: device, - Token: token, - }, nil -} - -// ApplyTo applies the authentication token to a request. -func (at *AuthToken) ApplyTo(request *http.Request) { - request.Header.Set(AuthHeaderDevice, at.Device) - request.Header.Set(AuthHeaderToken, at.Token) -} - -// GetNextTokenFromResponse extracts an authentication token from a response. -func GetNextTokenFromResponse(resp *http.Response) (token string, ok bool) { - token = resp.Header.Get(AuthHeaderNextToken) - if token == "" { - // TODO: Remove when fixed on server. - token = resp.Header.Get(AuthHeaderNextTokenDeprecated) - } - - return token, token != "" -} - -// ApplyNextTokenToResponse applies the next authentication token to a response. -func ApplyNextTokenToResponse(w http.ResponseWriter, token string) { - w.Header().Set(AuthHeaderNextToken, token) -} diff --git a/spn/access/account/client.go b/spn/access/account/client.go deleted file mode 100644 index d6d0f8791..000000000 --- a/spn/access/account/client.go +++ /dev/null @@ -1,14 +0,0 @@ -package account - -// Customer Agent URLs. -const ( - CAAuthenticateURL = "/authenticate" - CAProfileURL = "/user/profile" - CAGetTokensURL = "/tokens" -) - -// Customer Hub URLs. -const ( - CHAuthenticateURL = "/v1/authenticate" - CHUserProfileURL = "/v1/user_profile" -) diff --git a/spn/access/account/types.go b/spn/access/account/types.go deleted file mode 100644 index f92f9f653..000000000 --- a/spn/access/account/types.go +++ /dev/null @@ -1,137 +0,0 @@ -package account - -import ( - "time" - - "golang.org/x/exp/slices" -) - -// User, Subscription and Charge states. -const ( - // UserStateNone is only used within Portmaster for saving information for - // logging into the same device. - UserStateNone = "" - UserStateFresh = "fresh" - UserStateQueued = "queued" - UserStateApproved = "approved" - UserStateSuspended = "suspended" - UserStateLoggedOut = "loggedout" // Portmaster only. - - SubscriptionStateManual = "manual" // Manual renewal. - SubscriptionStateActive = "active" // Automatic renewal. - SubscriptionStateCancelled = "cancelled" // Automatic, but canceled. - - ChargeStatePending = "pending" - ChargeStateCompleted = "completed" - ChargeStateDead = "dead" -) - -// Agent and Hub return statuses. -const ( - // StatusInvalidAuth [401 Unauthorized] is returned when the credentials are - // invalid or the user was logged out. - StatusInvalidAuth = 401 - // StatusNoAccess [403 Forbidden] is returned when the user does not have - // an active subscription or the subscription does not include the required - // feature for the request. - StatusNoAccess = 403 - // StatusInvalidDevice [410 Gone] is returned when the device trying to - // log into does not exist. - StatusInvalidDevice = 410 - // StatusReachedDeviceLimit [409 Conflict] is returned when the device limit is reached. - StatusReachedDeviceLimit = 409 - // StatusDeviceInactive [423 Locked] is returned when the device is locked. - StatusDeviceInactive = 423 - // StatusNotLoggedIn [412 Precondition] is returned by the Portmaster, if an action required to be logged in, but the user is not logged in. - StatusNotLoggedIn = 412 - - // StatusUnknownError is a special status code that signifies an unknown or - // unexpected error by the API. - StatusUnknownError = -1 - // StatusConnectionError is a special status code that signifies a - // connection error. - StatusConnectionError = -2 -) - -// User describes an SPN user account. -type User struct { - Username string `json:"username"` - State string `json:"state"` - Balance int `json:"balance"` - Device *Device `json:"device"` - Subscription *Subscription `json:"subscription"` - CurrentPlan *Plan `json:"current_plan"` - NextPlan *Plan `json:"next_plan"` - View *View `json:"view"` -} - -// MayUseSPN returns whether the user may currently use the SPN. -func (u *User) MayUseSPN() bool { - return u.MayUse(FeatureSPN) -} - -// MayUsePrioritySupport returns whether the user may currently use the priority support. -func (u *User) MayUsePrioritySupport() bool { - return u.MayUse(FeatureSafingSupport) -} - -// MayUse returns whether the user may currently use the feature identified by -// the given feature ID. -// Leave feature ID empty to check without feature. -func (u *User) MayUse(featureID FeatureID) bool { - switch { - case u == nil: - // We need a user, obviously. - case u.State != UserStateApproved: - // Only approved users may use the SPN. - case u.Subscription == nil: - // Need a subscription. - case u.Subscription.EndsAt == nil: - case time.Now().After(*u.Subscription.EndsAt): - // Subscription needs to be active. - case u.CurrentPlan == nil: - // Need a plan / package. - case featureID != "" && - !slices.Contains(u.CurrentPlan.FeatureIDs, featureID): - // Required feature ID must be in plan / package feature IDs. - default: - // All checks passed! - return true - } - return false -} - -// Device describes a device of an SPN user. -type Device struct { - Name string `json:"name"` - ID string `json:"id"` -} - -// Subscription describes an SPN subscription. -type Subscription struct { - EndsAt *time.Time `json:"ends_at"` - State string `json:"state"` - NextBillingDate *time.Time `json:"next_billing_date"` - PaymentProvider string `json:"payment_provider"` -} - -// FeatureID defines a feature that requires a plan/subscription. -type FeatureID string - -// A list of all supported features. -const ( - FeatureSPN = FeatureID("spn") - FeatureSafingSupport = FeatureID("support") - FeatureHistory = FeatureID("history") - FeatureBWVis = FeatureID("bw-vis") - FeatureVPNCompat = FeatureID("vpn-compat") -) - -// Plan describes an SPN subscription plan. -type Plan struct { - Name string `json:"name"` - Amount int `json:"amount"` - Months int `json:"months"` - Renewable bool `json:"renewable"` - FeatureIDs []FeatureID `json:"feature_ids"` -} diff --git a/spn/access/account/view.go b/spn/access/account/view.go deleted file mode 100644 index 818bdfa65..000000000 --- a/spn/access/account/view.go +++ /dev/null @@ -1,123 +0,0 @@ -package account - -import ( - "fmt" - "strings" - "time" -) - -// View holds metadata that assists in displaying account information. -type View struct { - Message string - ShowAccountData bool - ShowAccountButton bool - ShowLoginButton bool - ShowRefreshButton bool - ShowLogoutButton bool -} - -// UpdateView updates the view and handles plan/package fallbacks. -func (u *User) UpdateView(requestStatusCode int) { - v := &View{} - - // Clean up naming and fallbacks when finished. - defer func() { - // Display "Free" package if no plan is set or if it expired. - switch { - case u.CurrentPlan == nil, - u.Subscription == nil, - u.Subscription.EndsAt == nil: - // Reset to free plan. - u.CurrentPlan = &Plan{ - Name: "Free", - } - u.Subscription = nil - - case u.Subscription.NextBillingDate != nil: - // Subscription is on auto-renew. - // Wait for update from server. - - case time.Since(*u.Subscription.EndsAt) > 0: - // Reset to free plan. - u.CurrentPlan = &Plan{ - Name: "Free", - } - u.Subscription = nil - } - - // Prepend "Portmaster " to plan name. - // TODO: Remove when Plan/Package naming has been updated. - if u.CurrentPlan != nil && !strings.HasPrefix(u.CurrentPlan.Name, "Portmaster ") { - u.CurrentPlan.Name = "Portmaster " + u.CurrentPlan.Name - } - - // Apply new view to user. - u.View = v - }() - - // Set view data based on return code. - switch requestStatusCode { - case StatusInvalidAuth, StatusInvalidDevice, StatusDeviceInactive: - // Account deleted or Device inactive or deleted. - // When using token based auth, there is no difference between these cases. - v.Message = "This device may have been deactivated or removed from your account. Please log in again." - v.ShowAccountData = true - v.ShowAccountButton = true - v.ShowLoginButton = true - v.ShowLogoutButton = true - return - - case StatusUnknownError: - v.Message = "There is an unknown error in the communication with the account server. The shown information may not be accurate. " - - case StatusConnectionError: - v.Message = "Portmaster could not connect to the account server. The shown information may not be accurate. " - } - - // Set view data based on profile data. - switch { - case u.State == UserStateLoggedOut: - // User logged out. - v.ShowAccountButton = true - v.ShowLoginButton = true - return - - case u.State == UserStateSuspended: - // Account is suspended. - v.Message += fmt.Sprintf("Your account (%s) was suspended. Please contact support for details.", u.Username) - v.ShowAccountButton = true - v.ShowRefreshButton = true - v.ShowLogoutButton = true - return - - case u.Subscription == nil || u.Subscription.EndsAt == nil: - // Account has never had a subscription. - v.Message += "Get more features. Upgrade today." - - case u.Subscription.NextBillingDate != nil: - switch { - case time.Since(*u.Subscription.NextBillingDate) > 0: - v.Message += "Your auto-renewal seems to be delayed. Please refresh and check the status of your payment. Payment information may be delayed." - case time.Until(*u.Subscription.NextBillingDate) < 24*time.Hour: - v.Message += "Your subscription will auto-renew soon. Please note that payment information may be delayed." - } - - case time.Since(*u.Subscription.EndsAt) > 0: - // Subscription expired. - if u.CurrentPlan != nil { - v.Message += fmt.Sprintf("Your package %s has ended. Extend it on the Account Page.", u.CurrentPlan.Name) - } else { - v.Message += "Your package has ended. Extend it on the Account Page." - } - - case time.Until(*u.Subscription.EndsAt) < 7*24*time.Hour: - // Add generic ending soon message if the package ends in less than 7 days. - v.Message += "Your package ends soon. Extend it on the Account Page." - } - - // Defaults for generally good accounts. - v.ShowAccountData = true - v.ShowAccountButton = true - v.ShowRefreshButton = true - v.ShowLogoutButton = true -} diff --git a/spn/access/api.go b/spn/access/api.go deleted file mode 100644 index a45ac0a72..000000000 --- a/spn/access/api.go +++ /dev/null @@ -1,169 +0,0 @@ -package access - -import ( - "errors" - "fmt" - "net/http" - - "github.com/safing/portmaster/base/api" - "github.com/safing/portmaster/base/database/record" - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/spn/access/account" -) - -func registerAPIEndpoints() error { - if err := api.RegisterEndpoint(api.Endpoint{ - Path: `spn/account/login`, - Write: api.PermitAdmin, - WriteMethod: http.MethodPost, - HandlerFunc: handleLogin, - Name: "SPN Login", - Description: "Log into your SPN account.", - }); err != nil { - return err - } - - if err := api.RegisterEndpoint(api.Endpoint{ - Path: `spn/account/logout`, - Write: api.PermitAdmin, - WriteMethod: http.MethodDelete, - ActionFunc: handleLogout, - Name: "SPN Logout", - Description: "Logout from your SPN account.", - Parameters: []api.Parameter{ - { - Method: http.MethodDelete, - Field: "purge", - Value: "", - Description: "If set, account data is purged. Otherwise, the username and device ID are kept in order to log into the same device when logging in with the same user again.", - }, - }, - }); err != nil { - return err - } - - if err := api.RegisterEndpoint(api.Endpoint{ - Path: `spn/account/user/profile`, - Read: api.PermitUser, - ReadMethod: http.MethodGet, - RecordFunc: handleGetUserProfile, - Name: "SPN User Profile", - Description: "Get the user profile of the logged in SPN account.", - Parameters: []api.Parameter{ - { - Method: http.MethodGet, - Field: "refresh", - Value: "", - Description: "If set, the user profile is freshly fetched from the account server.", - }, - }, - }); err != nil { - return err - } - - if err := api.RegisterEndpoint(api.Endpoint{ - Path: `account/features`, - Read: api.PermitUser, - ReadMethod: http.MethodGet, - StructFunc: func(_ *api.Request) (i interface{}, err error) { - return struct { - Features []Feature - }{ - Features: features, - }, nil - }, - Name: "Get Account Features", - Description: "Returns all account features.", - }); err != nil { - return err - } - - if err := api.RegisterEndpoint(api.Endpoint{ - Path: `account/features/{id:[A-Za-z0-9_-]+}/icon`, - Read: api.PermitUser, - ReadMethod: http.MethodGet, - Name: "Returns the image of the featuare", - MimeType: "image/svg+xml", - DataFunc: func(ar *api.Request) (data []byte, err error) { - featureID, ok := ar.URLVars["id"] - if !ok { - return nil, errors.New("invalid feature id") - } - - for _, feature := range features { - if feature.ID == featureID { - return []byte(feature.icon), nil - } - } - - return nil, errors.New("feature id not found") - }, - }); err != nil { - return err - } - - return nil -} - -func handleLogin(w http.ResponseWriter, r *http.Request) { - // Get username and password. - username, password, ok := r.BasicAuth() - // Request, if omitted. - if !ok || username == "" || password == "" { - w.Header().Set("WWW-Authenticate", "Basic realm=SPN Login") - http.Error(w, "Login with your SPN account.", http.StatusUnauthorized) - return - } - - // Process login. - user, code, err := Login(username, password) - if err != nil { - log.Warningf("spn/access: failed to login: %s", err) - if code == 0 { - http.Error(w, "Internal error: "+err.Error(), http.StatusInternalServerError) - } else { - http.Error(w, err.Error(), code) - } - return - } - - // Return success. - _, _ = w.Write([]byte( - fmt.Sprintf("Now logged in as %s as device %s", user.Username, user.Device.Name), - )) -} - -func handleLogout(ar *api.Request) (msg string, err error) { - purge := ar.URL.Query().Get("purge") != "" - err = Logout(false, purge) - switch { - case err != nil: - log.Warningf("spn/access: failed to logout: %s", err) - return "", err - case purge: - return "Logged out and user data purged.", nil - default: - return "Logged out.", nil - } -} - -func handleGetUserProfile(ar *api.Request) (r record.Record, err error) { - // Check if we are already authenticated. - user, err := GetUser() - if err != nil || user.State == account.UserStateNone { - return nil, api.ErrorWithStatus( - ErrNotLoggedIn, - account.StatusInvalidAuth, - ) - } - - // Should we refresh the user profile? - if ar.URL.Query().Get("refresh") != "" { - user, _, err = UpdateUser() - if err != nil { - return nil, err - } - } - - return user, nil -} diff --git a/spn/access/client.go b/spn/access/client.go deleted file mode 100644 index ca5c8f200..000000000 --- a/spn/access/client.go +++ /dev/null @@ -1,543 +0,0 @@ -package access - -import ( - "context" - "errors" - "fmt" - "net/http" - "sync" - "time" - - "github.com/safing/portmaster/base/database" - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/spn/access/account" - "github.com/safing/portmaster/spn/access/token" - "github.com/safing/structures/dsd" -) - -// Client URLs. -const ( - AccountServer = "https://api.account.safing.io" - LoginPath = "/api/v1/authenticate" - UserProfilePath = "/api/v1/user/profile" - TokenRequestSetupPath = "/api/v1/token/request/setup" //nolint:gosec - TokenRequestIssuePath = "/api/v1/token/request/issue" //nolint:gosec - HealthCheckPath = "/api/v1/health" - - defaultDataFormat = dsd.CBOR - defaultRequestTimeout = 30 * time.Second -) - -var ( - accountClient = &http.Client{} - clientRequestLock sync.Mutex - - // EnableAfterLogin automatically enables the SPN subsystem/module after login. - EnableAfterLogin = true -) - -type clientRequestOptions struct { - method string - url string - send interface{} - recv interface{} - requestTimeout time.Duration - dataFormat uint8 - setAuthToken bool - requireNextAuthToken bool - logoutOnAuthError bool - requestSetupFunc func(*http.Request) error -} - -func makeClientRequest(opts *clientRequestOptions) (resp *http.Response, err error) { - // Get request timeout. - if opts.requestTimeout == 0 { - opts.requestTimeout = defaultRequestTimeout - } - // Get context for request. - var ctx context.Context - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(module.mgr.Ctx(), opts.requestTimeout) - defer cancel() - - // Create new request. - request, err := http.NewRequestWithContext(ctx, opts.method, opts.url, nil) - if err != nil { - return nil, fmt.Errorf("failed to create request structure: %w", err) - } - - // Prepare body and content type. - if opts.dataFormat == dsd.AUTO { - opts.dataFormat = defaultDataFormat - } - if opts.send != nil { - // Add data to body. - err = dsd.DumpToHTTPRequest(request, opts.send, opts.dataFormat) - if err != nil { - return nil, fmt.Errorf("failed to add request body: %w", err) - } - } else { - // Set requested HTTP response format. - _, err = dsd.RequestHTTPResponseFormat(request, opts.dataFormat) - if err != nil { - return nil, fmt.Errorf("failed to set requested response format: %w", err) - } - } - - // Get auth token to apply to request. - var authToken *AuthTokenRecord - if opts.setAuthToken { - authToken, err = GetAuthToken() - if err != nil { - return nil, ErrNotLoggedIn - } - authToken.Token.ApplyTo(request) - } - - // Do any additional custom request setup. - if opts.requestSetupFunc != nil { - err = opts.requestSetupFunc(request) - if err != nil { - return nil, err - } - } - - // Make request. - resp, err = accountClient.Do(request) - if err != nil { - updateUserWithFailedRequest(account.StatusConnectionError, false) - tokenIssuerFailed() - return nil, fmt.Errorf("http request failed: %w", err) - } - log.Debugf("spn/access: request to %s returned %s", request.URL, resp.Status) - defer func() { - _ = resp.Body.Close() - }() - // Handle request error. - switch resp.StatusCode { - case http.StatusOK, http.StatusCreated: - // All good! - - case account.StatusInvalidAuth, account.StatusInvalidDevice: - // Wrong username / password. - updateUserWithFailedRequest(resp.StatusCode, true) - return resp, ErrInvalidCredentials - - case account.StatusReachedDeviceLimit: - // Device limit is reached. - updateUserWithFailedRequest(resp.StatusCode, true) - return resp, ErrDeviceLimitReached - - case account.StatusDeviceInactive: - // Device is locked. - updateUserWithFailedRequest(resp.StatusCode, true) - return resp, ErrDeviceIsLocked - - default: - updateUserWithFailedRequest(account.StatusUnknownError, false) - tokenIssuerFailed() - return resp, fmt.Errorf("unexpected reply: [%d] %s", resp.StatusCode, resp.Status) - } - - // Save next auth token. - if authToken != nil { - err = authToken.Update(resp) - if err != nil { - if errors.Is(err, account.ErrMissingToken) { - if opts.requireNextAuthToken { - return resp, fmt.Errorf("failed to save next auth token: %w", err) - } - } else { - return resp, fmt.Errorf("failed to save next auth token: %w", err) - } - } - } else if opts.requireNextAuthToken { - return resp, fmt.Errorf("failed to save next auth token: %w", account.ErrMissingToken) - } - - // Load response data. - if opts.recv != nil { - _, err = dsd.LoadFromHTTPResponse(resp, opts.recv) - if err != nil { - return resp, fmt.Errorf("failed to parse response: %w", err) - } - } - - tokenIssuerIsFailing.UnSet() - return resp, nil -} - -func updateUserWithFailedRequest(statusCode int, disableSubscription bool) { - // Get user from database. - user, err := GetUser() - if err != nil { - if !errors.Is(err, ErrNotLoggedIn) { - log.Warningf("spn/access: failed to get user to update with failed request: %s", err) - } - return - } - - func() { - user.Lock() - defer user.Unlock() - - // Ignore update if user state is undefined or logged out. - if user.State == "" || user.State == account.UserStateLoggedOut { - return - } - - // Disable the subscription if desired. - if disableSubscription && user.Subscription != nil { - user.Subscription.EndsAt = nil - } - - // Update view with the status code and save user. - user.UpdateView(statusCode) - }() - - err = user.Save() - if err != nil { - log.Warningf("spn/access: failed to save user after update with failed request: %s", err) - } -} - -// Login logs the user into the SPN account with the given username and password. -func Login(username, password string) (user *UserRecord, code int, err error) { - clientRequestLock.Lock() - defer clientRequestLock.Unlock() - - // Trigger account update when done. - defer module.EventAccountUpdate.Submit(struct{}{}) - - // Get previous user. - previousUser, err := GetUser() - if err != nil { - if !errors.Is(err, ErrNotLoggedIn) { - log.Warningf("spn/access: failed to get previous for re-login: %s", err) - } - previousUser = nil - } - - // Create request options. - userAccount := &account.User{} - requestOptions := &clientRequestOptions{ - method: http.MethodPost, - url: AccountServer + LoginPath, - recv: userAccount, - dataFormat: dsd.JSON, - requestSetupFunc: func(request *http.Request) error { - // Add username and password. - request.SetBasicAuth(username, password) - - // Try to reuse the device ID, if the username matches the previous user. - if previousUser != nil && username == previousUser.Username { - request.Header.Set(account.AuthHeaderDevice, previousUser.Device.ID) - } - - return nil - }, - } - - // Make request. - resp, err := makeClientRequest(requestOptions) //nolint:bodyclose // Body is closed in function. - if err != nil { - if resp != nil && resp.StatusCode == account.StatusInvalidDevice { - // Try again without the previous device ID. - previousUser = nil - log.Info("spn/access: retrying log in without re-using previous device ID") - resp, err = makeClientRequest(requestOptions) //nolint:bodyclose // Body is closed in function. - } - if err != nil { - if resp != nil { - return nil, resp.StatusCode, err - } - return nil, 0, err - } - } - - // Save new user. - now := time.Now() - user = &UserRecord{ - User: userAccount, - LoggedInAt: &now, - } - - user.UpdateView(0) - err = user.Save() - if err != nil { - return user, resp.StatusCode, fmt.Errorf("failed to save new user profile: %w", err) - } - - // Save initial auth token. - err = SaveNewAuthToken(user.Device.ID, resp) - if err != nil { - return user, resp.StatusCode, fmt.Errorf("failed to save initial auth token: %w", err) - } - - // Enable the SPN right after login. - if user.MayUseSPN() && EnableAfterLogin { - enableSPN() - } - - log.Infof("spn/access: logged in as %q on device %q", user.Username, user.Device.Name) - return user, resp.StatusCode, nil -} - -// Logout logs the user out of the SPN account. -// Specify "shallow" to keep user data in order to display data in the -// UI - preferably when logged out be the server. -// Specify "purge" in order to fully delete all user account data, even -// the device ID so that logging in again will create a new device. -func Logout(shallow, purge bool) error { - clientRequestLock.Lock() - defer clientRequestLock.Unlock() - - // Trigger account update when done. - defer module.EventAccountUpdate.Submit(struct{}{}) - - // Clear caches. - clearUserCaches() - - // Clear tokens. - clearTokens() - - // Delete auth token. - err := db.Delete(authTokenRecordKey) - if err != nil && !errors.Is(err, database.ErrNotFound) { - return fmt.Errorf("failed to delete auth token: %w", err) - } - - // Delete all user data if purging. - if purge { - err := db.Delete(userRecordKey) - if err != nil && !errors.Is(err, database.ErrNotFound) { - return fmt.Errorf("failed to delete user: %w", err) - } - - // Disable SPN when the user logs out directly. - disableSPN() - - log.Info("spn/access: logged out and purged data") - return nil - } - - // Else, just update the user. - user, err := GetUser() - if err != nil { - if errors.Is(err, ErrNotLoggedIn) { - return nil - } - return fmt.Errorf("failed to load user for logout: %w", err) - } - - func() { - user.Lock() - defer user.Unlock() - - if shallow { - // Shallow logout: User stays logged in the UI to display status when - // logged out from the Portmaster or Customer Hub. - user.User.State = account.UserStateLoggedOut - } else { - // Proper logout: User is logged out from UI. - // Reset all user data, except for username and device ID in order to log - // into the same device again. - user.User = &account.User{ - Username: user.Username, - Device: &account.Device{ - ID: user.Device.ID, - }, - } - user.LoggedInAt = &time.Time{} - } - user.UpdateView(0) - }() - err = user.Save() - if err != nil { - return fmt.Errorf("failed to save user for logout: %w", err) - } - - if shallow { - log.Info("spn/access: logged out shallow") - } else { - log.Info("spn/access: logged out") - - // Disable SPN when the user logs out directly. - disableSPN() - } - - return nil -} - -// UpdateUser fetches the current user information from the server. -func UpdateUser() (user *UserRecord, statusCode int, err error) { - clientRequestLock.Lock() - defer clientRequestLock.Unlock() - - // Trigger account update when done. - defer module.EventAccountUpdate.Submit(struct{}{}) - - // Create request options. - userData := &account.User{} - requestOptions := &clientRequestOptions{ - method: http.MethodGet, - url: AccountServer + UserProfilePath, - recv: userData, - dataFormat: dsd.JSON, - setAuthToken: true, - requireNextAuthToken: true, - logoutOnAuthError: true, - } - - // Make request. - resp, err := makeClientRequest(requestOptions) //nolint:bodyclose // Body is closed in function. - if err != nil { - if resp != nil { - return nil, resp.StatusCode, err - } - return nil, 0, err - } - - // Save to previous user, if exists. - previousUser, err := GetUser() - if err == nil { - func() { - previousUser.Lock() - defer previousUser.Unlock() - previousUser.User = userData - previousUser.UpdateView(resp.StatusCode) - }() - err := previousUser.Save() - if err != nil { - log.Warningf("spn/access: failed to save updated user profile: %s", err) - } - - // Notify user of nearing end of package. - notifyOfPackageEnd(previousUser) - - log.Infof("spn/access: got user profile, updated existing") - return previousUser, resp.StatusCode, nil - } - - // Else, save as new user. - now := time.Now() - newUser := &UserRecord{ - User: userData, - LoggedInAt: &now, - } - newUser.UpdateView(resp.StatusCode) - err = newUser.Save() - if err != nil { - log.Warningf("spn/access: failed to save new user profile: %s", err) - } - - // Notify user of nearing end of package. - notifyOfPackageEnd(newUser) - - log.Infof("spn/access: got user profile, saved as new") - return newUser, resp.StatusCode, nil -} - -// UpdateTokens fetches more tokens for handlers that need it. -func UpdateTokens() error { - clientRequestLock.Lock() - defer clientRequestLock.Unlock() - - // Check if the user may request tokens. - user, err := GetUser() - if err != nil { - return fmt.Errorf("failed to get user: %w", err) - } - if !user.MayUseTheSPN() { - return ErrMayNotUseSPN - } - - // Create setup request, return if not required. - setupRequest, setupRequired := token.CreateSetupRequest() - var setupResponse *token.SetupResponse - if setupRequired { - // Request setup data. - setupResponse = &token.SetupResponse{} - _, err := makeClientRequest(&clientRequestOptions{ //nolint:bodyclose // Body is closed in function. - method: http.MethodPost, - url: AccountServer + TokenRequestSetupPath, - send: setupRequest, - recv: setupResponse, - dataFormat: dsd.MsgPack, - setAuthToken: true, - logoutOnAuthError: true, - }) - if err != nil { - return fmt.Errorf("failed to request setup data: %w", err) - } - } - - // Create request for issuing new tokens. - tokenRequest, requestRequired, err := token.CreateTokenRequest(setupResponse) - if err != nil { - return fmt.Errorf("failed to create token request: %w", err) - } - if !requestRequired { - return nil - } - - // Request issuing new tokens. - issuedTokens := &token.IssuedTokens{} - _, err = makeClientRequest(&clientRequestOptions{ //nolint:bodyclose // Body is closed in function. - method: http.MethodPost, - url: AccountServer + TokenRequestIssuePath, - send: tokenRequest, - recv: issuedTokens, - dataFormat: dsd.MsgPack, - setAuthToken: true, - logoutOnAuthError: true, - }) - if err != nil { - return fmt.Errorf("failed to request tokens: %w", err) - } - - // Save tokens to handlers. - err = token.ProcessIssuedTokens(issuedTokens) - if err != nil { - return fmt.Errorf("failed to process issued tokens: %w", err) - } - - // Log new status. - regular, fallback := GetTokenAmount(ExpandAndConnectZones) - log.Infof( - "spn/access: got new tokens, now at %d regular and %d fallback tokens for expand and connect", - regular, - fallback, - ) - - return nil -} - -var ( - lastHealthCheckExpires time.Time - lastHealthCheckLock sync.Mutex - lastHealthCheckValidityDuration = 30 * time.Second -) - -func healthCheck() (ok bool) { - lastHealthCheckLock.Lock() - defer lastHealthCheckLock.Unlock() - - // Return current value if recently checked. - if time.Now().Before(lastHealthCheckExpires) { - return tokenIssuerIsFailing.IsNotSet() - } - - // Check health. - _, err := makeClientRequest(&clientRequestOptions{ //nolint:bodyclose // Body is closed in function. - method: http.MethodGet, - url: AccountServer + HealthCheckPath, - }) - if err != nil { - log.Warningf("spn/access: token issuer health check failed: %s", err) - } - // Update health check expiry. - lastHealthCheckExpires = time.Now().Add(lastHealthCheckValidityDuration) - - return tokenIssuerIsFailing.IsNotSet() -} diff --git a/spn/access/client_test.go b/spn/access/client_test.go deleted file mode 100644 index acc5bd2b8..000000000 --- a/spn/access/client_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package access - -import ( - "os" - "testing" -) - -var ( - testUsername = os.Getenv("SPN_TEST_USERNAME") - testPassword = os.Getenv("SPN_TEST_PASSWORD") -) - -func TestClient(t *testing.T) { - // Skip test in CI. - if testing.Short() { - t.Skip() - } - t.Parallel() - - if testUsername == "" || testPassword == "" { - t.Fatal("test username or password not configured") - } - - loginAndRefresh(t, true, 5) - clearUserCaches() - loginAndRefresh(t, false, 1) - - err := Logout(false, false) - if err != nil { - t.Fatalf("failed to log out: %s", err) - } - t.Logf("logged out") - - loginAndRefresh(t, true, 1) - - err = Logout(false, true) - if err != nil { - t.Fatalf("failed to log out: %s", err) - } - t.Logf("logged out with purge") - - loginAndRefresh(t, true, 1) -} - -func loginAndRefresh(t *testing.T, doLogin bool, refreshTimes int) { - t.Helper() - - if doLogin { - _, _, err := Login(testUsername, testPassword) - if err != nil { - t.Fatalf("login failed: %s", err) - } - user, err := GetUser() - if err != nil { - t.Fatalf("failed to get user: %s", err) - } - t.Logf("user (from login): %+v", user.User) - t.Logf("device (from login): %+v", user.User.Device) - authToken, err := GetAuthToken() - if err != nil { - t.Fatalf("failed to get auth token: %s", err) - } - t.Logf("auth token: %+v", authToken.Token) - } - - for range refreshTimes { - user, _, err := UpdateUser() - if err != nil { - t.Fatalf("getting profile failed: %s", err) - } - t.Logf("user (from refresh): %+v", user.User) - - authToken, err := GetAuthToken() - if err != nil { - t.Fatalf("failed to get auth token: %s", err) - } - t.Logf("auth token: %+v", authToken.Token) - } -} diff --git a/spn/access/compatibility.go b/spn/access/compatibility.go new file mode 100644 index 000000000..20840a04c --- /dev/null +++ b/spn/access/compatibility.go @@ -0,0 +1,116 @@ +// Copyright (c) 2026 +// SPDX-License-Identifier: GPL-3.0-or-later + +// This file preserves the minimal public surface of the former Safing account +// backend so that the remaining SPN packages still compile. The SPN module is +// never started in portmasterpro. Every symbol here is local, side-effect free +// and performs no network, token, account, persistence or telemetry I/O. + +package access + +import ( + "errors" + "time" + + "github.com/safing/portmaster/base/database/record" + "github.com/safing/portmaster/spn/access/token" + "github.com/safing/portmaster/spn/terminal" +) + +// ErrNotLoggedIn is retained for source compatibility only. No account login +// exists in portmasterpro; callers must not treat it as a recoverable login flow. +var ErrNotLoggedIn = errors.New("account authentication has been removed from portmasterpro") + +// ErrAccessRemoved is returned by every former SPN token or authorization path. +var ErrAccessRemoved = errors.New("SPN access tokens have been removed from portmasterpro") + +// ExpandAndConnectZones is kept as an empty zone list: no access zones exist. +var ExpandAndConnectZones = []string{} + +// UserRecord is a deliberately empty compatibility record. Account data is +// never stored, loaded or transmitted by portmasterpro. All methods are +// nil-safe and report that no account is available. +type UserRecord struct { + record.Base + + // View is always nil; it only exists for source compatibility. + View *UserView + + LastNotifiedOfEnd *time.Time + LoggedInAt *time.Time +} + +// UserView is an empty compatibility type for the removed account view. +type UserView struct { + Message string +} + +// IsLoggedIn always reports false. +func (user *UserRecord) IsLoggedIn() bool { return false } + +// MayUse always reports false: there are no account-gated features left. +func (user *UserRecord) MayUse(_ string) bool { return false } + +// MayUseSPN always reports false. +func (user *UserRecord) MayUseSPN() bool { return false } + +// MayUseTheSPN always reports false. +func (user *UserRecord) MayUseTheSPN() bool { return false } + +// MayUsePrioritySupport always reports false. +func (user *UserRecord) MayUsePrioritySupport() bool { return false } + +// GetUser always reports that accounts are unavailable. +func GetUser() (*UserRecord, error) { return nil, ErrNotLoggedIn } + +// Login never performs authentication or network I/O. +func Login(_, _ string) (user *UserRecord, code int, err error) { + return nil, 0, ErrNotLoggedIn +} + +// Logout is a no-op because nothing is ever logged in. +func Logout(_, _ bool) error { return nil } + +// UpdateUser never contacts an account server. +func UpdateUser() (user *UserRecord, statusCode int, err error) { + return nil, 0, ErrNotLoggedIn +} + +// UpdateTokens never requests or stores tokens. +func UpdateTokens() error { return ErrAccessRemoved } + +// InitializeZones is a no-op because account-associated SPN zones are removed. +func InitializeZones() error { return nil } + +// EnableTestMode is a no-op kept for the SPN test suites. +func EnableTestMode() {} + +// ShouldRequest always reports false: tokens are never requested. +func ShouldRequest(_ []string) bool { return false } + +// GetTokenAmount always reports zero tokens. +func GetTokenAmount(_ []string) (regular, fallback int) { return 0, 0 } + +// GetToken never returns a token. +func GetToken(_ []string) (*token.Token, error) { return nil, ErrAccessRemoved } + +// TokenIssuerIsFailing always reports false; there is no token issuer. +func TokenIssuerIsFailing() bool { return false } + +// AuthorizeOp is kept for type compatibility with the SPN crew and captain +// packages. It is never started. +type AuthorizeOp struct { + terminal.OneOffOperationBase +} + +// OpTypeAccessCodeAuth is the former type ID of the auth operation. The +// operation type is intentionally not registered with the terminal package. +const OpTypeAccessCodeAuth = "auth" + +// Type returns the type ID. +func (op *AuthorizeOp) Type() string { return OpTypeAccessCodeAuth } + +// AuthorizeToTerminal always fails locally: no access token can be presented. +func AuthorizeToTerminal(_ terminal.Terminal) (*AuthorizeOp, *terminal.Error) { + return nil, terminal.ErrPermissionDenied.With("%w", ErrAccessRemoved) +} diff --git a/spn/access/database.go b/spn/access/database.go deleted file mode 100644 index 6dd99b9db..000000000 --- a/spn/access/database.go +++ /dev/null @@ -1,258 +0,0 @@ -package access - -import ( - "errors" - "fmt" - "net/http" - "sync" - "time" - - "github.com/safing/portmaster/base/database" - "github.com/safing/portmaster/base/database/record" - "github.com/safing/portmaster/spn/access/account" -) - -const ( - userRecordKey = "core:spn/account/user" - authTokenRecordKey = "core:spn/account/authtoken" //nolint:gosec // Not a credential. - tokenStorageKeyTemplate = "core:spn/account/tokens/%s" //nolint:gosec // Not a credential. -) - -var db = database.NewInterface(&database.Options{ - Local: true, - Internal: true, -}) - -// UserRecord holds a SPN user account. -type UserRecord struct { - record.Base - sync.Mutex - - *account.User - - LastNotifiedOfEnd *time.Time - LoggedInAt *time.Time -} - -// MayUseSPN returns whether the user may currently use the SPN. -func (user *UserRecord) MayUseSPN() bool { - // Shadow this function in order to allow calls on a nil user. - if user == nil || user.User == nil { - return false - } - return user.User.MayUseSPN() -} - -// MayUsePrioritySupport returns whether the user may currently use the priority support. -func (user *UserRecord) MayUsePrioritySupport() bool { - // Shadow this function in order to allow calls on a nil user. - if user == nil || user.User == nil { - return false - } - return user.User.MayUsePrioritySupport() -} - -// MayUse returns whether the user may currently use the feature identified by -// the given feature ID. -// Leave feature ID empty to check without feature. -func (user *UserRecord) MayUse(featureID account.FeatureID) bool { - // Shadow this function in order to allow calls on a nil user. - if user == nil || user.User == nil { - return false - } - return user.User.MayUse(featureID) -} - -// AuthTokenRecord holds an authentication token. -type AuthTokenRecord struct { - record.Base - sync.Mutex - - Token *account.AuthToken -} - -// GetToken returns the token from the record. -func (authToken *AuthTokenRecord) GetToken() *account.AuthToken { - authToken.Lock() - defer authToken.Unlock() - - return authToken.Token -} - -// SaveNewAuthToken saves a new auth token to the database. -func SaveNewAuthToken(deviceID string, resp *http.Response) error { - token, ok := account.GetNextTokenFromResponse(resp) - if !ok { - return account.ErrMissingToken - } - - newAuthToken := &AuthTokenRecord{ - Token: &account.AuthToken{ - Device: deviceID, - Token: token, - }, - } - return newAuthToken.Save() -} - -// Update updates an existing auth token with the next token from a response. -func (authToken *AuthTokenRecord) Update(resp *http.Response) error { - token, ok := account.GetNextTokenFromResponse(resp) - if !ok { - return account.ErrMissingToken - } - - // Update token with new account.AuthToken. - func() { - authToken.Lock() - defer authToken.Unlock() - - authToken.Token = &account.AuthToken{ - Device: authToken.Token.Device, - Token: token, - } - }() - - return authToken.Save() -} - -var ( - accountCacheLock sync.Mutex - - cachedUser *UserRecord - cachedUserSet bool - - cachedAuthToken *AuthTokenRecord -) - -func clearUserCaches() { - accountCacheLock.Lock() - defer accountCacheLock.Unlock() - - cachedUser = nil - cachedUserSet = false - cachedAuthToken = nil -} - -// GetUser returns the current user account. -// Returns nil when no user is logged in. -func GetUser() (*UserRecord, error) { - // Check cache. - accountCacheLock.Lock() - defer accountCacheLock.Unlock() - if cachedUserSet { - if cachedUser == nil { - return nil, ErrNotLoggedIn - } - return cachedUser, nil - } - - // Load from disk. - r, err := db.Get(userRecordKey) - if err != nil { - if errors.Is(err, database.ErrNotFound) { - cachedUser = nil - cachedUserSet = true - return nil, ErrNotLoggedIn - } - return nil, err - } - - // Unwrap record. - if r.IsWrapped() { - // only allocate a new struct, if we need it - newUser := &UserRecord{} - err = record.Unwrap(r, newUser) - if err != nil { - return nil, err - } - cachedUser = newUser - cachedUserSet = true - return cachedUser, nil - } - - // Or adjust type. - newUser, ok := r.(*UserRecord) - if !ok { - return nil, fmt.Errorf("record not of type *UserRecord, but %T", r) - } - cachedUser = newUser - cachedUserSet = true - return cachedUser, nil -} - -// Save saves the User. -func (user *UserRecord) Save() error { - // Update cache. - accountCacheLock.Lock() - defer accountCacheLock.Unlock() - cachedUser = user - cachedUserSet = true - - // Update view if unset. - if user.View == nil { - user.UpdateView(0) - } - - // Set, check and update metadata. - if !user.KeyIsSet() { - user.SetKey(userRecordKey) - } - user.UpdateMeta() - - return db.Put(user) -} - -// GetAuthToken returns the current auth token. -func GetAuthToken() (*AuthTokenRecord, error) { - // Check cache. - accountCacheLock.Lock() - defer accountCacheLock.Unlock() - if cachedAuthToken != nil { - return cachedAuthToken, nil - } - - // Load from disk. - r, err := db.Get(authTokenRecordKey) - if err != nil { - return nil, err - } - - // Unwrap record. - if r.IsWrapped() { - // only allocate a new struct, if we need it - newAuthRecord := &AuthTokenRecord{} - err = record.Unwrap(r, newAuthRecord) - if err != nil { - return nil, err - } - cachedAuthToken = newAuthRecord - return newAuthRecord, nil - } - - // Or adjust type. - newAuthRecord, ok := r.(*AuthTokenRecord) - if !ok { - return nil, fmt.Errorf("record not of type *AuthTokenRecord, but %T", r) - } - cachedAuthToken = newAuthRecord - return newAuthRecord, nil -} - -// Save saves the auth token to the database. -func (authToken *AuthTokenRecord) Save() error { - // Update cache. - accountCacheLock.Lock() - defer accountCacheLock.Unlock() - cachedAuthToken = authToken - - // Set, check and update metadata. - if !authToken.KeyIsSet() { - authToken.SetKey(authTokenRecordKey) - } - authToken.UpdateMeta() - authToken.Meta().MakeSecret() - authToken.Meta().MakeCrownJewel() - - return db.Put(authToken) -} diff --git a/spn/access/features.go b/spn/access/features.go deleted file mode 100644 index a47e2ebd9..000000000 --- a/spn/access/features.go +++ /dev/null @@ -1,131 +0,0 @@ -package access - -import "github.com/safing/portmaster/spn/access/account" - -// Feature describes a notable part of the program. -type Feature struct { - Name string - ID string - RequiredFeatureID account.FeatureID - ConfigKey string - ConfigScope string - InPackage *Package - Comment string - Beta bool - ComingSoon bool - icon string -} - -// Package combines a set of features. -type Package struct { - Name string - HexColor string - InfoURL string -} - -var ( - infoURL = "https://safing.io/pricing/" - packageFree = &Package{ - Name: "Free", - HexColor: "#ffffff", - InfoURL: infoURL, - } - packagePlus = &Package{ - Name: "Plus", - HexColor: "#2fcfae", - InfoURL: infoURL, - } - packagePro = &Package{ - Name: "Pro", - HexColor: "#029ad0", - InfoURL: infoURL, - } - features = []Feature{ - { - Name: "Secure DNS", - ID: "dns", - ConfigScope: "dns/", - InPackage: packageFree, - icon: ` - - - - `, - }, - { - Name: "Privacy Filter", - ID: "filter", - ConfigScope: "filter/", - InPackage: packageFree, - icon: ` - - - - `, - }, - { - Name: "Network History", - ID: string(account.FeatureHistory), - RequiredFeatureID: account.FeatureHistory, - ConfigKey: "history/enable", - ConfigScope: "history/", - InPackage: packagePlus, - icon: ` - - - - `, - }, - { - Name: "Bandwidth Visibility", - ID: string(account.FeatureBWVis), - RequiredFeatureID: account.FeatureBWVis, - InPackage: packagePlus, - Beta: true, - icon: ` - - - - `, - }, - { - Name: "Split Tunneling", - ID: "splittun", - ConfigKey: "splittun/enable", - ConfigScope: "splittun/", - InPackage: packageFree, - icon: ` - - - - - - - - `, - }, - { - Name: "Safing Privacy Network", - ID: string(account.FeatureSPN), - RequiredFeatureID: account.FeatureSPN, - ConfigKey: "spn/enable", - ConfigScope: "spn/", - InPackage: packagePro, - icon: ` - - - - - - - - - `, - }, - } -) diff --git a/spn/access/module.go b/spn/access/module.go index a805240ac..27af758c7 100644 --- a/spn/access/module.go +++ b/spn/access/module.go @@ -1,259 +1,45 @@ +// Package access has been stubbed out. +// The original access module handled Safing account authentication, +// SPN token management, and feature-flag checks against external servers. +// All of that functionality has been intentionally removed from portmasterpro. package access import ( - "errors" - "fmt" - "sync/atomic" - "time" - - "github.com/tevino/abool" - - "github.com/safing/portmaster/base/config" - "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/mgr" - "github.com/safing/portmaster/spn/access/account" - "github.com/safing/portmaster/spn/access/token" - "github.com/safing/portmaster/spn/conf" ) +// Access is a no-op stub that satisfies the module interface without +// contacting any Safing authentication or account servers. type Access struct { - mgr *mgr.Manager - instance instance - - updateAccountWorkerMgr *mgr.WorkerMgr + m *mgr.Manager +} - EventAccountUpdate *mgr.EventMgr[struct{}] +// New returns a no-op Access stub. +func New(_ any) (*Access, error) { + return &Access{}, nil } +// Manager returns nil — no manager needed for a no-op module. func (a *Access) Manager() *mgr.Manager { - return a.mgr + return a.m } +// Start is a no-op. func (a *Access) Start() error { - return start() -} - -func (a *Access) Stop() error { - return stop() -} - -var ( - module *Access - shimLoaded atomic.Bool - - tokenIssuerIsFailing = abool.New() - tokenIssuerRetryDuration = 10 * time.Minute - - // AccountUpdateEvent is fired when the account has changed in any way. - AccountUpdateEvent = "account update" -) - -// Errors. -var ( - ErrDeviceIsLocked = errors.New("device is locked") - ErrDeviceLimitReached = errors.New("device limit reached") - ErrFallbackNotAvailable = errors.New("fallback tokens not available, token issuer is online") - ErrInvalidCredentials = errors.New("invalid credentials") - ErrMayNotUseSPN = errors.New("may not use SPN") - ErrNotLoggedIn = errors.New("not logged in") -) - -func prep() error { - // Register API handlers. - if conf.Integrated() { - err := registerAPIEndpoints() - if err != nil { - return err - } - } - - return nil -} - -func start() error { - // Initialize zones. - if err := InitializeZones(); err != nil { - return err - } - - if conf.Integrated() { - // Add config listener to enable/disable SPN. - module.instance.Config().EventConfigChange.AddCallback("spn enable check", func(wc *mgr.WorkerCtx, s struct{}) (bool, error) { - // Do not do anything when we are shutting down. - if module.instance.IsShuttingDown() { - return true, nil - } - - enabled := config.GetAsBool("spn/enable", false) - if enabled() { - log.Info("spn: starting SPN") - module.mgr.Go("ensure SPN is started", module.instance.SPNGroup().EnsureStartedWorker) - } else { - log.Info("spn: stopping SPN") - module.mgr.Go("ensure SPN is stopped", module.instance.SPNGroup().EnsureStoppedWorker) - } - return false, nil - }) - - // Load tokens from database. - loadTokens() - - // Check if we need to enable SPN now. - enabled := config.GetAsBool("spn/enable", false) - if enabled() { - module.mgr.Go("ensure SPN is started", module.instance.SPNGroup().EnsureStartedWorker) - } - - // Register new task. - module.updateAccountWorkerMgr.Delay(1 * time.Minute) - } - - return nil -} - -func stop() error { - if conf.Integrated() { - // Make sure SPN is stopped before we proceed. - err := module.mgr.Do("ensure SPN is shut down", module.instance.SPNGroup().EnsureStoppedWorker) - if err != nil { - log.Errorf("access: stop SPN: %s", err) - } - - // Store tokens to database. - storeTokens() - } - - // Reset zones. - token.ResetRegistry() - return nil } -// UpdateAccount updates the user account and fetches new tokens, if needed. -func UpdateAccount(_ *mgr.WorkerCtx) error { - // Schedule next call - this will change if other conditions are met bellow. - module.updateAccountWorkerMgr.Delay(24 * time.Hour) - - // Retry sooner if the token issuer is failing. - defer func() { - if tokenIssuerIsFailing.IsSet() { - module.updateAccountWorkerMgr.Delay(tokenIssuerRetryDuration) - } - }() - - // Get current user. - u, err := GetUser() - if err == nil { - // Do not update if we just updated. - if time.Since(time.Unix(u.Meta().Modified, 0)) < 2*time.Minute { - return nil - } - } - - u, _, err = UpdateUser() - if err != nil { - return fmt.Errorf("failed to update user profile: %w", err) - } - - err = UpdateTokens() - if err != nil { - return fmt.Errorf("failed to get tokens: %w", err) - } - - // Schedule next check. - switch { - case u == nil: // No user. - case u.Subscription == nil: // No subscription. - case u.Subscription.EndsAt == nil: // Subscription not active - - case time.Until(*u.Subscription.EndsAt) < 24*time.Hour && - time.Since(*u.Subscription.EndsAt) < 24*time.Hour: - // Update account every hour for 24h hours before and after the subscription ends. - module.updateAccountWorkerMgr.Delay(1 * time.Hour) - - case u.Subscription.NextBillingDate == nil: // No auto-subscription. - - case time.Until(*u.Subscription.NextBillingDate) < 24*time.Hour && - time.Since(*u.Subscription.NextBillingDate) < 24*time.Hour: - // Update account every hour 24h hours before and after the next billing date. - module.updateAccountWorkerMgr.Delay(1 * time.Hour) - } - +// Stop is a no-op. +func (a *Access) Stop() error { return nil } -func enableSPN() { - err := config.SetConfigOption("spn/enable", true) - if err != nil { - log.Warningf("spn/access: failed to enable the SPN during login: %s", err) - } -} - -func disableSPN() { - err := config.SetConfigOption("spn/enable", false) - if err != nil { - log.Warningf("spn/access: failed to disable the SPN during logout: %s", err) - } -} - -// TokenIssuerIsFailing returns whether token issuing is currently failing. -func TokenIssuerIsFailing() bool { - return tokenIssuerIsFailing.IsSet() -} - -func tokenIssuerFailed() { - if !tokenIssuerIsFailing.SetToIf(false, true) { - return - } - - module.updateAccountWorkerMgr.Delay(tokenIssuerRetryDuration) -} - -// IsLoggedIn returns whether a User is currently logged in. -func (user *UserRecord) IsLoggedIn() bool { - user.Lock() - defer user.Unlock() - - switch user.State { - case account.UserStateNone, account.UserStateLoggedOut: - return false - default: - return true - } -} - -// MayUseTheSPN returns whether the currently logged in User may use the SPN. -func (user *UserRecord) MayUseTheSPN() bool { - user.Lock() - defer user.Unlock() - - return user.User.MayUseSPN() -} - -// New returns a new Access module. -func New(instance instance) (*Access, error) { - if !shimLoaded.CompareAndSwap(false, true) { - return nil, errors.New("only one instance allowed") - } - - m := mgr.New("Access") - module = &Access{ - mgr: m, - instance: instance, - - EventAccountUpdate: mgr.NewEventMgr[struct{}](AccountUpdateEvent, m), - updateAccountWorkerMgr: m.NewWorkerMgr("update account", UpdateAccount, nil), - } - - if err := prep(); err != nil { - return nil, err - } - - return module, nil +// IsLoggedIn always returns false — account login has been removed. +func (a *Access) IsLoggedIn() bool { + return false } -type instance interface { - Config() *config.Config - SPNGroup() *mgr.ExtendedGroup - IsShuttingDown() bool +// HasFeature always returns true — all features are unlocked without an account. +func (a *Access) HasFeature(_ string) bool { + return true } diff --git a/spn/access/module_test.go b/spn/access/module_test.go index b459ecb8e..89e3ec5f8 100644 --- a/spn/access/module_test.go +++ b/spn/access/module_test.go @@ -1,90 +1,63 @@ -package access +package access_test import ( - "fmt" - "os" "testing" - "github.com/safing/portmaster/base/config" - "github.com/safing/portmaster/base/database" - _ "github.com/safing/portmaster/base/database/storage/hashmap" - "github.com/safing/portmaster/service/mgr" - "github.com/safing/portmaster/spn/conf" + "github.com/safing/portmaster/spn/access" ) -type testInstance struct { - config *config.Config -} - -func (stub *testInstance) Config() *config.Config { return stub.config } -func (stub *testInstance) SPNGroup() *mgr.ExtendedGroup { return nil } -func (stub *testInstance) Stopping() bool { return false } -func (stub *testInstance) IsShuttingDown() bool { return false } -func (stub *testInstance) SetCmdLineOperation(f func() error) {} -func (stub *testInstance) DataDir() string { return _dataDir } - -var _dataDir string - -func TestMain(m *testing.M) { - exitCode := 1 - defer func() { - if exitCode != 0 { - os.Exit(exitCode) - } - }() - - var err error - // Create a temporary directory for the data - _dataDir, err = os.MkdirTemp("", "") +// TestAccessStubNoOp verifies the access stub starts and stops cleanly. +func TestAccessStubNoOp(t *testing.T) { + t.Parallel() + a, err := access.New(nil) if err != nil { - fmt.Printf("failed to create temporary data directory: %s", err) - return // Exit with error + t.Fatalf("access.New() returned unexpected error: %v", err) } - defer func() { _ = os.RemoveAll(_dataDir) }() - - // Initialize the database module - err = database.Initialize(_dataDir) + err = a.Start() if err != nil { - fmt.Printf("failed to initialize database module: %s", err) - return // Exit with error + t.Fatalf("Access.Start() returned unexpected error: %v", err) } - _, err = database.Register(&database.Database{ - Name: "core", - Description: "Holds core data, such as settings and profiles", - StorageType: "hashmap", - }) + err = a.Stop() if err != nil { - fmt.Printf("failed to register core database: %s", err) - return // Exit with error + t.Fatalf("Access.Stop() returned unexpected error: %v", err) } +} - // Initialize the instance - instance := &testInstance{} - - instance.config, err = config.New(instance) +// TestAccessStubNotLoggedIn verifies no account session is present. +func TestAccessStubNotLoggedIn(t *testing.T) { + t.Parallel() + a, err := access.New(nil) if err != nil { - fmt.Printf("failed to create config module: %s", err) - return // Exit with error + t.Fatalf("access.New() returned unexpected error: %v", err) } - module, err = New(instance) - if err != nil { - fmt.Printf("failed to create access module: %s", err) - return // Exit with error + if a.IsLoggedIn() { + t.Error("expected IsLoggedIn() to return false — account login has been removed") } +} - err = instance.config.Start() +// TestAccessStubAllFeaturesUnlocked verifies all features are available without a subscription. +func TestAccessStubAllFeaturesUnlocked(t *testing.T) { + t.Parallel() + a, err := access.New(nil) if err != nil { - fmt.Printf("failed to start config module: %s", err) - return // Exit with error + t.Fatalf("access.New() returned unexpected error: %v", err) } - err = module.Start() - if err != nil { - fmt.Printf("failed to start access module: %s", err) - return // Exit with error + features := []string{"bandwidth-visibility", "network-history", "spn", "filter-lists", "custom-lists"} + for _, f := range features { + if !a.HasFeature(f) { + t.Errorf("expected HasFeature(%q) to return true, got false", f) + } } +} - conf.EnableClient(true) - m.Run() - - exitCode = 0 // success +// TestAccessStubManagerIsNil verifies no background workers are spawned. +func TestAccessStubManagerIsNil(t *testing.T) { + t.Parallel() + a, err := access.New(nil) + if err != nil { + t.Fatalf("access.New() returned unexpected error: %v", err) + } + if a.Manager() != nil { + t.Error("expected Manager() to return nil for no-op stub, got non-nil") + } } diff --git a/spn/access/notify.go b/spn/access/notify.go deleted file mode 100644 index 3ed9f6471..000000000 --- a/spn/access/notify.go +++ /dev/null @@ -1,105 +0,0 @@ -package access - -import ( - "fmt" - "strings" - "time" - - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/base/notifications" -) - -const ( - day = 24 * time.Hour - week = 7 * day - - endOfPackageNearNotifID = "access:end-of-package-near" -) - -func notifyOfPackageEnd(u *UserRecord) { - // TODO: Check if subscription auto-renews. - - // Skip if there is not active subscription or if it has ended already. - switch { - case u.Subscription == nil, // No subscription. - u.Subscription.EndsAt == nil, // Subscription not active. - u.Subscription.NextBillingDate != nil, // Subscription is auto-renewing. - time.Now().After(*u.Subscription.EndsAt): // Subscription has ended. - return - } - - // Calculate durations. - sinceLastNotified := 52 * week // Never. - if u.LastNotifiedOfEnd != nil { - sinceLastNotified = time.Since(*u.LastNotifiedOfEnd) - } - untilEnd := time.Until(*u.Subscription.EndsAt) - - // Notify every two days in the week before end. - notifType := notifications.Info - switch { - case untilEnd < week && sinceLastNotified > 2*day: - // Notify 7, 5, 3 and 1 days before end. - if untilEnd < 4*day { - notifType = notifications.Warning - } - fallthrough - - case u.CurrentPlan != nil && u.CurrentPlan.Months >= 6 && - untilEnd < 4*week && sinceLastNotified > week: - // Notify 4, 3 and 2 weeks before end - on long running packages. - - // Get names and messages. - packageNameTitle := "Portmaster Package" - if u.CurrentPlan != nil { - packageNameTitle = u.CurrentPlan.Name - } - packageNameBody := packageNameTitle - if !strings.HasSuffix(packageNameBody, " Package") { - packageNameBody += " Package" - } - - var endsText string - daysUntilEnd := untilEnd / day - switch daysUntilEnd { //nolint:exhaustive - case 0: - endsText = "today" - case 1: - endsText = "tomorrow" - default: - endsText = fmt.Sprintf("in %d days", daysUntilEnd) - } - - // Send notification. - notifications.Notify(¬ifications.Notification{ - EventID: endOfPackageNearNotifID, - Type: notifType, - Title: fmt.Sprintf("%s About to Expire", packageNameTitle), - Message: fmt.Sprintf( - "Your current %s ends %s. Extend it to keep your full privacy protections.", - packageNameBody, - endsText, - ), - ShowOnSystem: notifType == notifications.Warning, - AvailableActions: []*notifications.Action{ - { - Text: "Open Account Page", - Type: notifications.ActionTypeOpenURL, - Payload: "https://account.safing.io", - }, - { - ID: "ack", - Text: "Got it!", - }, - }, - }) - - // Save that we sent a notification. - now := time.Now() - u.LastNotifiedOfEnd = &now - err := u.Save() - if err != nil { - log.Warningf("spn/access: failed to save user after sending subscription ending soon notification: %s", err) - } - } -} diff --git a/spn/access/op_auth.go b/spn/access/op_auth.go deleted file mode 100644 index f31986f78..000000000 --- a/spn/access/op_auth.go +++ /dev/null @@ -1,75 +0,0 @@ -package access - -import ( - "time" - - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/spn/access/token" - "github.com/safing/portmaster/spn/terminal" - "github.com/safing/structures/container" -) - -// OpTypeAccessCodeAuth is the type ID of the auth operation. -const OpTypeAccessCodeAuth = "auth" - -func init() { - terminal.RegisterOpType(terminal.OperationFactory{ - Type: OpTypeAccessCodeAuth, - Start: checkAccessCode, - }) -} - -// AuthorizeOp is used to authorize a session. -type AuthorizeOp struct { - terminal.OneOffOperationBase -} - -// Type returns the type ID. -func (op *AuthorizeOp) Type() string { - return OpTypeAccessCodeAuth -} - -// AuthorizeToTerminal starts an authorization operation. -func AuthorizeToTerminal(t terminal.Terminal) (*AuthorizeOp, *terminal.Error) { - op := &AuthorizeOp{} - op.Init() - - newToken, err := GetToken(ExpandAndConnectZones) - if err != nil { - return nil, terminal.ErrInternalError.With("failed to get access token: %w", err) - } - - tErr := t.StartOperation(op, container.New(newToken.Raw()), 10*time.Second) - if tErr != nil { - return nil, terminal.ErrInternalError.With("failed to init auth op: %w", tErr) - } - - return op, nil -} - -func checkAccessCode(t terminal.Terminal, opID uint32, initData *container.Container) (terminal.Operation, *terminal.Error) { - // Parse provided access token. - receivedToken, err := token.ParseRawToken(initData.CompileData()) - if err != nil { - return nil, terminal.ErrMalformedData.With("failed to parse access token: %w", err) - } - - // Check if token is valid. - granted, err := VerifyToken(receivedToken) - if err != nil { - return nil, terminal.ErrPermissionDenied.With("invalid access token: %w", err) - } - - // Get the authorizing terminal for applying the granted permission. - authTerm, ok := t.(terminal.AuthorizingTerminal) - if !ok { - return nil, terminal.ErrIncorrectUsage.With("terminal does not handle authorization") - } - - // Grant permissions. - authTerm.GrantPermission(granted) - log.Debugf("spn/access: granted %s permissions via %s zone", t.FmtID(), receivedToken.Zone) - - // End successfully. - return nil, terminal.ErrExplicitAck -} diff --git a/spn/access/storage.go b/spn/access/storage.go deleted file mode 100644 index 04f1a5fe1..000000000 --- a/spn/access/storage.go +++ /dev/null @@ -1,131 +0,0 @@ -package access - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/safing/portmaster/base/database" - "github.com/safing/portmaster/base/database/query" - "github.com/safing/portmaster/base/database/record" - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/spn/access/token" - "github.com/safing/structures/dsd" -) - -func loadTokens() { - for _, zone := range persistentZones { - // Get handler of zone. - handler, ok := token.GetHandler(zone) - if !ok { - log.Warningf("spn/access: could not find zone %s for loading tokens", zone) - continue - } - - // Get data from database. - r, err := db.Get(fmt.Sprintf(tokenStorageKeyTemplate, zone)) - if err != nil { - if errors.Is(err, database.ErrNotFound) { - log.Debugf("spn/access: no %s tokens to load", zone) - } else { - log.Warningf("spn/access: failed to load %s tokens: %s", zone, err) - } - continue - } - - // Get wrapper. - wrapper, ok := r.(*record.Wrapper) - if !ok { - log.Warningf("spn/access: failed to parse %s tokens: expected wrapper, got %T", zone, r) - continue - } - - // Load into handler. - err = handler.Load(wrapper.Data) - if err != nil { - log.Warningf("spn/access: failed to load %s tokens: %s", zone, err) - } - log.Infof("spn/access: loaded %d %s tokens", handler.Amount(), zone) - } -} - -func storeTokens() { - for _, zone := range persistentZones { - // Get handler of zone. - handler, ok := token.GetHandler(zone) - if !ok { - log.Warningf("spn/access: could not find zone %s for storing tokens", zone) - continue - } - - // Generate storage key. - storageKey := fmt.Sprintf(tokenStorageKeyTemplate, zone) - - // Check if there is data to save. - amount := handler.Amount() - if amount == 0 { - // Remove possible old entry from database. - err := db.Delete(storageKey) - if err != nil { - log.Warningf("spn/access: failed to delete possible old %s tokens from storage: %s", zone, err) - } - log.Debugf("spn/access: no %s tokens to store", zone) - continue - } - - // Export data. - data, err := handler.Save() - if err != nil { - log.Warningf("spn/access: failed to export %s tokens for storing: %s", zone, err) - continue - } - - // Wrap data into raw record. - r, err := record.NewWrapper(storageKey, nil, dsd.RAW, data) - if err != nil { - log.Warningf("spn/access: failed to prepare %s token export for storing: %s", zone, err) - continue - } - - // Let tokens expire after one month. - // This will regularly happen when we switch zones. - r.UpdateMeta() - r.Meta().MakeSecret() - r.Meta().MakeCrownJewel() - r.Meta().SetRelativateExpiry(30 * 86400) - - // Save to database. - err = db.Put(r) - if err != nil { - log.Warningf("spn/access: failed to store %s tokens: %s", zone, err) - continue - } - - log.Infof("spn/access: stored %d %s tokens", amount, zone) - } -} - -func clearTokens() { - for _, zone := range persistentZones { - // Get handler of zone. - handler, ok := token.GetHandler(zone) - if !ok { - log.Warningf("spn/access: could not find zone %s for clearing tokens", zone) - continue - } - - // Clear tokens. - handler.Clear() - } - - // Purge database storage prefix. - ctx, cancel := context.WithTimeout(module.mgr.Ctx(), 10*time.Second) - defer cancel() - n, err := db.Purge(ctx, query.New(fmt.Sprintf(tokenStorageKeyTemplate, ""))) - if err != nil { - log.Warningf("spn/access: failed to clear token storages: %s", err) - return - } - log.Infof("spn/access: cleared %d token storages", n) -} diff --git a/spn/access/token/pblind.go b/spn/access/token/pblind.go index ef97bb78f..58c5b3003 100644 --- a/spn/access/token/pblind.go +++ b/spn/access/token/pblind.go @@ -13,6 +13,7 @@ import ( "github.com/mr-tron/base58" "github.com/rot256/pblind" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/structures/container" "github.com/safing/structures/dsd" ) @@ -35,7 +36,7 @@ func (pbt *PBlindToken) Pack() ([]byte, error) { func UnpackPBlindToken(token []byte) (*PBlindToken, error) { t := &PBlindToken{} - _, err := dsd.Load(token, t) + _, err := peerdsd.Load(token, t) if err != nil { return nil, err } @@ -461,6 +462,9 @@ func (pbh *PBlindHandler) Verify(token *Token) error { if err != nil { return fmt.Errorf("%w: %w", ErrTokenMalformed, err) } + if t.Signature == nil { + return fmt.Errorf("%w: missing signature", ErrTokenMalformed) + } // Check if serial is valid. switch { diff --git a/spn/access/token/pblind_compressed_test.go b/spn/access/token/pblind_compressed_test.go new file mode 100644 index 000000000..b2367ac6b --- /dev/null +++ b/spn/access/token/pblind_compressed_test.go @@ -0,0 +1,42 @@ +package token + +import ( + "bytes" + "errors" + "testing" + + "github.com/safing/structures/dsd" +) + +// TestUnpackPBlindTokenRejectsCompressed checks that a gzip compressed token +// is rejected before decompression. Tokens are received from any client before +// authentication, and dsd.Load decompresses them into an unbounded buffer, so a +// few KB could make a Hub allocate many MB. +func TestUnpackPBlindTokenRejectsCompressed(t *testing.T) { + t.Parallel() + + pbt := &PBlindToken{Serial: 1, Token: []byte("token")} + + // Packed tokens are accepted. + data, err := pbt.Pack() + if err != nil { + t.Fatal(err) + } + unpacked, err := UnpackPBlindToken(data) + if err != nil { + t.Fatal(err) + } + if unpacked.Serial != 1 || !bytes.Equal(unpacked.Token, pbt.Token) { + t.Fatalf("unexpected token: %+v", unpacked) + } + + // Compressed tokens are rejected. + data, err = dsd.DumpAndCompress(pbt, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, err = UnpackPBlindToken(data) + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("expected ErrIncompatibleFormat, got %v", err) + } +} diff --git a/spn/access/token/pblind_msgpack_test.go b/spn/access/token/pblind_msgpack_test.go new file mode 100644 index 000000000..d60a5c573 --- /dev/null +++ b/spn/access/token/pblind_msgpack_test.go @@ -0,0 +1,24 @@ +package token + +import ( + "errors" + "testing" + + "github.com/safing/portmaster/spn/peerdsd" +) + +// TestUnpackPBlindTokenRejectsOversizedMsgPack checks that a msgpack token +// that declares more data than it holds is rejected before decoding. The +// msgpack decoder allocates the declared length up front, so 12 bytes sent by +// any client before authentication could make a Hub allocate 4GB. +// The length used here is smaller to keep the test cheap without the fix. +func TestUnpackPBlindTokenRejectsOversizedMsgPack(t *testing.T) { + t.Parallel() + + // PBlindToken.Token with a declared length of 64MB. + data := []byte{'M', 0x81, 0xa5, 'T', 'o', 'k', 'e', 'n', 0xc6, 0x04, 0x00, 0x00, 0x00} + _, err := UnpackPBlindToken(data) + if !errors.Is(err, peerdsd.ErrLengthExceedsData) { + t.Errorf("expected ErrLengthExceedsData, got %v", err) + } +} diff --git a/spn/access/token/pblind_verify_test.go b/spn/access/token/pblind_verify_test.go new file mode 100644 index 000000000..718ab8604 --- /dev/null +++ b/spn/access/token/pblind_verify_test.go @@ -0,0 +1,59 @@ +package token + +import ( + "crypto/elliptic" + "errors" + "testing" +) + +func newTestPBlindVerifier(tb testing.TB) *PBlindHandler { + tb.Helper() + + verifier, err := NewPBlindHandler(PBlindOptions{ + Zone: PBlindTestZone, + Curve: elliptic.P256(), + PublicKey: "285oMDh3w5mxyFgpmmURifKfhkcqwwsdnePpPZ6Nqm8cc", + UseSerials: true, + BatchSize: 1000, + }) + if err != nil { + tb.Fatal(err) + } + return verifier +} + +// TestPBlindVerifyWithoutSignature checks that a token without a signature is +// rejected instead of causing a panic. +func TestPBlindVerifyWithoutSignature(t *testing.T) { + t.Parallel() + + verifier := newTestPBlindVerifier(t) + + data, err := (&PBlindToken{Serial: 1, Token: []byte("token")}).Pack() + if err != nil { + t.Fatal(err) + } + err = verifier.Verify(&Token{Zone: PBlindTestZone, Data: data}) + if !errors.Is(err, ErrTokenMalformed) { + t.Fatalf("expected malformed token error, got %v", err) + } +} + +func FuzzPBlindVerify(f *testing.F) { + data, err := (&PBlindToken{Serial: 1, Token: []byte("token")}).Pack() + if err != nil { + f.Fatal(err) + } + f.Add(data) + f.Add([]byte{}) + + verifier := newTestPBlindVerifier(f) + f.Fuzz(func(t *testing.T, data []byte) { + err := verifier.Verify(&Token{Zone: PBlindTestZone, Data: data}) + if err == nil { + t.Fatal("fuzzed token verified") + } + _, _ = ParseRawToken(data) + _, _ = ParseToken(string(data)) + }) +} diff --git a/spn/access/token/request.go b/spn/access/token/request.go index 70e9422a7..70f6f4070 100644 --- a/spn/access/token/request.go +++ b/spn/access/token/request.go @@ -28,7 +28,7 @@ type SetupResponse struct { } // TokenRequest is a token request. -type TokenRequest struct { //nolint:golint // Be explicit. +type TokenRequest struct { SessionID string `json:"ID,omitempty"` PBlind map[string]*PBlindTokenRequest `json:"PB,omitempty"` Scramble map[string]*ScrambleTokenRequest `json:"S,omitempty"` diff --git a/spn/access/zones.go b/spn/access/zones.go deleted file mode 100644 index 165d8f85f..000000000 --- a/spn/access/zones.go +++ /dev/null @@ -1,251 +0,0 @@ -package access - -import ( - "errors" - "fmt" - "os" - "strings" - - "github.com/tevino/abool" - - "github.com/safing/jess/lhash" - "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/spn/access/token" - "github.com/safing/portmaster/spn/conf" - "github.com/safing/portmaster/spn/terminal" -) - -var ( - // ExpandAndConnectZones are the zones that grant access to the expand and - // connect operations. - ExpandAndConnectZones = []string{"pblind1", "alpha2", "fallback1"} - - zonePermissions = map[string]terminal.Permission{ - "pblind1": terminal.AddPermissions(terminal.MayExpand, terminal.MayConnect), - "alpha2": terminal.AddPermissions(terminal.MayExpand, terminal.MayConnect), - "fallback1": terminal.AddPermissions(terminal.MayExpand, terminal.MayConnect), - } - persistentZones = ExpandAndConnectZones - - enableTestMode = abool.New() -) - -// EnableTestMode enables the test mode, leading the access module to only -// register a test zone. -// This should not be used to test the access module itself. -func EnableTestMode() { - enableTestMode.Set() -} - -// InitializeZones initialized the permission zones. -// It initializes the test zones, if EnableTestMode was called before. -// Must only be called once. -func InitializeZones() error { - // Check if we are testing. - if enableTestMode.IsSet() { - return initializeTestZone() - } - - // Special client zone config. - var requestSignalHandler func(token.Handler) - if conf.Integrated() { - requestSignalHandler = shouldRequestTokensHandler - } - - // Register pblind1 as the first primary zone. - ph, err := token.NewPBlindHandler(token.PBlindOptions{ - Zone: "pblind1", - CurveName: "P-256", - PublicKey: "eXoJXzXbM66UEsM2eVi9HwyBPLMfVnNrC7gNrsfMUJDs", - UseSerials: true, - BatchSize: 1000, - RandomizeOrder: true, - SignalShouldRequest: requestSignalHandler, - }) - if err != nil { - return fmt.Errorf("failed to create pblind1 token handler: %w", err) - } - err = token.RegisterPBlindHandler(ph) - if err != nil { - return fmt.Errorf("failed to register pblind1 token handler: %w", err) - } - - // Register fallback1 zone as fallback when the issuer is not available. - sh, err := token.NewScrambleHandler(token.ScrambleOptions{ - Zone: "fallback1", - Algorithm: lhash.BLAKE2b_256, - InitialVerifiers: []string{"ZwkQoaAttVBMURzeLzNXokFBMAMUUwECfM1iHojcVKBmjk"}, - Fallback: true, - }) - if err != nil { - return fmt.Errorf("failed to create fallback1 token handler: %w", err) - } - err = token.RegisterScrambleHandler(sh) - if err != nil { - return fmt.Errorf("failed to register fallback1 token handler: %w", err) - } - - // Register alpha2 zone for transition phase. - sh, err = token.NewScrambleHandler(token.ScrambleOptions{ - Zone: "alpha2", - Algorithm: lhash.BLAKE2b_256, - InitialVerifiers: []string{"ZwojEvXZmAv7SZdNe7m94Xzu7F9J8vULqKf7QYtoTpN2tH"}, - }) - if err != nil { - return fmt.Errorf("failed to create alpha2 token handler: %w", err) - } - err = token.RegisterScrambleHandler(sh) - if err != nil { - return fmt.Errorf("failed to register alpha2 token handler: %w", err) - } - - return nil -} - -func initializeTestZone() error { - // Safeguard checks if we should really enable the test zone. - if !strings.HasSuffix(os.Args[0], ".test") { - return errors.New("tried to enable test mode, but no test binary was detected") - } - if token.RegistrySize() > 0 { - return fmt.Errorf("tried to enable test zone, but %d handlers are already registered", token.RegistrySize()) - } - - // Reset zones. - token.ResetRegistry() - - // Set eligible zones. - ExpandAndConnectZones = []string{"unittest"} - zonePermissions = map[string]terminal.Permission{ - "unittest": terminal.AddPermissions(terminal.MayExpand, terminal.MayConnect), - } - - // Register unittest zone as for testing. - sh, err := token.NewScrambleHandler(token.ScrambleOptions{ - Zone: "unittest", - Algorithm: lhash.BLAKE2b_256, - InitialTokens: []string{"6jFqLA93uSLL52utGKrvctG3ZfopSQ8WFqjsRK1c2Svt"}, - InitialVerifiers: []string{"ZwoEoL59sr81s7WnF2vydGzjeejE3u8CqVafig1NTQzUr7"}, - }) - if err != nil { - return fmt.Errorf("failed to create unittest token handler: %w", err) - } - err = token.RegisterScrambleHandler(sh) - if err != nil { - return fmt.Errorf("failed to register unittest token handler: %w", err) - } - - return nil -} - -func shouldRequestTokensHandler(_ token.Handler) { - // Run the account update task as now. - module.updateAccountWorkerMgr.Go() -} - -// GetTokenAmount returns the amount of tokens for the given zones. -func GetTokenAmount(zones []string) (regular, fallback int) { -handlerLoop: - for _, zone := range zones { - // Get handler and check if it should be used. - handler, ok := token.GetHandler(zone) - if !ok { - log.Warningf("spn/access: use of non-registered zone %q", zone) - continue handlerLoop - } - - if handler.IsFallback() { - fallback += handler.Amount() - } else { - regular += handler.Amount() - } - } - - return -} - -// ShouldRequest returns whether tokens should be requested for the given zones. -func ShouldRequest(zones []string) (shouldRequest bool) { -handlerLoop: - for _, zone := range zones { - // Get handler and check if it should be used. - handler, ok := token.GetHandler(zone) - if !ok { - log.Warningf("spn/access: use of non-registered zone %q", zone) - continue handlerLoop - } - - // Go through all handlers every time as this will be the case anyway most - // of the time and will help us better catch zone misconfiguration. - if handler.ShouldRequest() { - shouldRequest = true - } - } - - return shouldRequest -} - -// GetToken returns a token of one of the given zones. -func GetToken(zones []string) (t *token.Token, err error) { -handlerSelection: - for _, zone := range zones { - // Get handler and check if it should be used. - handler, ok := token.GetHandler(zone) - switch { - case !ok: - log.Warningf("spn/access: use of non-registered zone %q", zone) - continue handlerSelection - case handler.IsFallback() && !TokenIssuerIsFailing(): - // Skip fallback zone if everything works. - continue handlerSelection - } - - // Get token from handler. - t, err = token.GetToken(zone) - if err == nil { - return t, nil - } - } - - // Return existing error, if exists. - if err != nil { - return nil, err - } - return nil, token.ErrEmpty -} - -// VerifyRawToken verifies a raw token. -func VerifyRawToken(data []byte) (granted terminal.Permission, err error) { - t, err := token.ParseRawToken(data) - if err != nil { - return 0, fmt.Errorf("failed to parse token: %w", err) - } - - return VerifyToken(t) -} - -// VerifyToken verifies a token. -func VerifyToken(t *token.Token) (granted terminal.Permission, err error) { - handler, ok := token.GetHandler(t.Zone) - if !ok { - return terminal.NoPermission, token.ErrZoneUnknown - } - - // Check if the token is a fallback token. - if handler.IsFallback() && !healthCheck() { - return terminal.NoPermission, ErrFallbackNotAvailable - } - - // Verify token. - err = handler.Verify(t) - if err != nil { - return 0, fmt.Errorf("failed to verify token: %w", err) - } - - // Return permission of zone. - granted, ok = zonePermissions[t.Zone] - if !ok { - return terminal.NoPermission, nil - } - return granted, nil -} diff --git a/spn/cabin/keys.go b/spn/cabin/keys.go index 3faa36719..dcac7ab0b 100644 --- a/spn/cabin/keys.go +++ b/spn/cabin/keys.go @@ -15,7 +15,7 @@ import ( type providedExchKeyScheme struct { id string - securityLevel int //nolint:structcheck // TODO + securityLevel int tool *tools.Tool } diff --git a/spn/cabin/verification.go b/spn/cabin/verification.go index f60af514b..126752323 100644 --- a/spn/cabin/verification.go +++ b/spn/cabin/verification.go @@ -8,6 +8,7 @@ import ( "github.com/safing/jess" "github.com/safing/portmaster/base/rng" "github.com/safing/portmaster/spn/hub" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/structures/dsd" ) @@ -68,7 +69,7 @@ func CreateVerificationRequest(purpose, clientReference, serverReference string) func (id *Identity) SignVerificationRequest(request []byte, purpose, clientReference, serverReference string) (response []byte, err error) { // Parse request. v := new(Verification) - _, err = dsd.Load(request, v) + _, err = peerdsd.Load(request, v) if err != nil { return nil, fmt.Errorf("failed to parse request: %w", err) } @@ -116,6 +117,11 @@ func (id *Identity) SignVerificationRequest(request []byte, purpose, clientRefer // Verify verifies the verification response and checks if everything is valid. func (v *Verification) Verify(response []byte, h *hub.Hub) error { // Parse response. + // jess.LetterFromDSD uses dsd.Load, which decompresses without limit. + err := peerdsd.CheckFormat(response) + if err != nil { + return fmt.Errorf("failed to parse response: %w", err) + } letter, err := jess.LetterFromDSD(response) if err != nil { return fmt.Errorf("failed to parse response: %w", err) @@ -134,7 +140,7 @@ func (v *Verification) Verify(response []byte, h *hub.Hub) error { // Parse verified response. responseV := new(Verification) - _, err = dsd.Load(responseData, responseV) + _, err = peerdsd.Load(responseData, responseV) if err != nil { return fmt.Errorf("failed to parse verified response: %w", err) } diff --git a/spn/cabin/verification_compressed_test.go b/spn/cabin/verification_compressed_test.go new file mode 100644 index 000000000..a8c087244 --- /dev/null +++ b/spn/cabin/verification_compressed_test.go @@ -0,0 +1,83 @@ +package cabin + +import ( + "errors" + "testing" + + "github.com/safing/jess" + "github.com/safing/structures/dsd" +) + +// TestVerificationRejectsCompressed checks that gzip compressed verification +// requests and responses are rejected before decompression. dsd.Load +// decompresses them into an unbounded buffer, so a few KB sent by any client +// (requests) or any Hub (responses) could make the receiver allocate many MB. +func TestVerificationRejectsCompressed(t *testing.T) { + t.Parallel() + + id, err := CreateIdentity(module.m.Ctx(), "test") + if err != nil { + t.Fatal(err) + } + + // Compressed request. + v, request, err := CreateVerificationRequest("a", "b", "c") + if err != nil { + t.Fatal(err) + } + compressedRequest, err := dsd.DumpAndCompress(v, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, err = id.SignVerificationRequest(compressedRequest, "a", "b", "c") + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("compressed request: expected ErrIncompatibleFormat, got %v", err) + } + + // Compressed response letter. + response, err := id.SignVerificationRequest(request, "a", "b", "c") + if err != nil { + t.Fatal(err) + } + err = v.Verify(response, id.Hub) + if err != nil { + t.Fatalf("valid response: %s", err) + } + letter, err := jess.LetterFromDSD(response) + if err != nil { + t.Fatal(err) + } + compressedResponse, err := dsd.DumpAndCompress(letter, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + err = v.Verify(compressedResponse, id.Hub) + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("compressed response letter: expected ErrIncompatibleFormat, got %v", err) + } + + // Compressed response data in a correctly signed letter. + compressedData, err := dsd.DumpAndCompress(v, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + e := jess.NewUnconfiguredEnvelope() + e.SuiteID = verificationSigningSuite + e.Senders = []*jess.Signet{id.Signet} + jession, err := e.Correspondence(nil) + if err != nil { + t.Fatal(err) + } + letter, err = jession.Close(compressedData) + if err != nil { + t.Fatal(err) + } + signedResponse, err := letter.ToDSD(dsd.JSON) + if err != nil { + t.Fatal(err) + } + err = v.Verify(signedResponse, id.Hub) + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("compressed response data: expected ErrIncompatibleFormat, got %v", err) + } +} diff --git a/spn/cabin/verification_msgpack_test.go b/spn/cabin/verification_msgpack_test.go new file mode 100644 index 000000000..5ca664e3e --- /dev/null +++ b/spn/cabin/verification_msgpack_test.go @@ -0,0 +1,40 @@ +package cabin + +import ( + "errors" + "testing" + + "github.com/safing/portmaster/spn/peerdsd" +) + +// TestVerificationRejectsOversizedMsgPack checks that msgpack verification +// requests that declare more data than they hold are rejected before decoding. +// The msgpack decoder allocates the declared length up front, so 12 bytes sent +// by any client could make a Hub allocate 4GB. +// The length used here is smaller to keep the test cheap without the fix. +func TestVerificationRejectsOversizedMsgPack(t *testing.T) { + t.Parallel() + + id, err := CreateIdentity(module.m.Ctx(), "test") + if err != nil { + t.Fatal(err) + } + + // Verification.Challenge with a declared length of 64MB. + request := []byte{'M', 0x81, 0xa9, 'C', 'h', 'a', 'l', 'l', 'e', 'n', 'g', 'e', 0xc6, 0x04, 0x00, 0x00, 0x00} + _, err = id.SignVerificationRequest(request, "a", "b", "c") + if !errors.Is(err, peerdsd.ErrLengthExceedsData) { + t.Errorf("expected ErrLengthExceedsData, got %v", err) + } + + // Response letter with Letter.Data with a declared length of 64MB. + v, _, err := CreateVerificationRequest("a", "b", "c") + if err != nil { + t.Fatal(err) + } + response := []byte{'M', 0x81, 0xa4, 'D', 'a', 't', 'a', 0xc6, 0x04, 0x00, 0x00, 0x00} + err = v.Verify(response, id.Hub) + if !errors.Is(err, peerdsd.ErrLengthExceedsData) { + t.Errorf("expected ErrLengthExceedsData, got %v", err) + } +} diff --git a/spn/captain/client.go b/spn/captain/client.go index 00c351bfc..208249f54 100644 --- a/spn/captain/client.go +++ b/spn/captain/client.go @@ -75,7 +75,6 @@ func triggerClientHealthCheck() { func clientManager(ctx *mgr.WorkerCtx) error { defer func() { ready.UnSet() - netenv.ConnectedToSPN.UnSet() resetSPNStatus(StatusDisabled, true) module.states.Clear() clientStopHomeHub(ctx) @@ -111,7 +110,6 @@ reconnect: // Reset SPN status. if ready.SetToIf(true, false) { - netenv.ConnectedToSPN.UnSet() log.Info("spn/captain: client not ready") } resetSPNStatus(StatusConnecting, true) @@ -142,7 +140,6 @@ reconnect: log.Info("spn/captain: client is ready") ready.Set() - netenv.ConnectedToSPN.Set() module.EventSPNConnected.Submit(struct{}{}) if conf.Integrated() { diff --git a/spn/captain/config.go b/spn/captain/config.go index bd5b7fc76..764abc7a7 100644 --- a/spn/captain/config.go +++ b/spn/captain/config.go @@ -1,15 +1,38 @@ package captain import ( + "strings" "sync" "github.com/safing/portmaster/base/config" - "github.com/safing/portmaster/service/profile" "github.com/safing/portmaster/service/profile/endpoints" "github.com/safing/portmaster/spn/conf" "github.com/safing/portmaster/spn/navigator" ) +var ( + // spnRulesQuickSettings are generated automatically shortly after start. + spnRulesQuickSettings = []config.QuickSetting{ + {Name: "Loading...", Action: config.QuickMergeTop, Value: []string{""}}, + } + + // spnRulesVerdictNames defines the verdicts names to be used for SPN Rules. + spnRulesVerdictNames = map[string]string{ + "-": "Exclude", // Default. + "+": "Allow", + } + + // spnRulesHelp defines the help text for SPN related Hub selection rules. + spnRulesHelp = strings.ReplaceAll(`Rules are checked from top to bottom, stopping after the first match. They can match the following attributes of SPN Nodes: + +- Country (based on IPs): "US" (two-letter country codes according to ISO 3166-1 alpha-2) +- AS number: "AS123456" +- Address: "192.168.0.1" +- Network: "192.168.0.1/24" +- Anything: "*" +`, `"`, "`") +) + var ( // CfgOptionEnableSPNKey is the configuration key for the SPN module. CfgOptionEnableSPNKey = "spn/enable" @@ -81,7 +104,7 @@ func prepConfig() error { By default, the Portmaster tries to choose the nearest node as your Home Node in order to reduce your exposure to the open Internet. Reconnect to the SPN in order to apply new rules.`, - Help: profile.SPNRulesHelp, + Help: spnRulesHelp, Sensitive: true, OptType: config.OptTypeStringArray, RequiresRestart: true, @@ -91,8 +114,8 @@ Reconnect to the SPN in order to apply new rules.`, config.CategoryAnnotation: "Routing", config.DisplayOrderAnnotation: cfgOptionHomeHubPolicyOrder, config.DisplayHintAnnotation: endpoints.DisplayHintEndpointList, - config.QuickSettingsAnnotation: profile.SPNRulesQuickSettings, - endpoints.EndpointListVerdictNamesAnnotation: profile.SPNRulesVerdictNames, + config.QuickSettingsAnnotation: spnRulesQuickSettings, + endpoints.EndpointListVerdictNamesAnnotation: spnRulesVerdictNames, }, ValidationRegex: endpoints.ListEntryValidationRegex, ValidationFunc: endpoints.ValidateEndpointListConfigOption, @@ -111,7 +134,7 @@ Reconnect to the SPN in order to apply new rules.`, By default, the Portmaster will exit DNS requests directly at your Home Node in order to keep them fast and close to your location. This is important, as DNS resolution often takes your approximate location into account when deciding which optimized DNS records are returned to you. As the Portmaster encrypts your DNS requests by default, you effectively gain a two-hop security level for your DNS requests in order to protect your privacy. This setting mainly exists for when you need to simulate your presence in another location on a lower level too. This might be necessary to defeat more intelligent geo-blocking systems.`, - Help: profile.SPNRulesHelp, + Help: spnRulesHelp, Sensitive: true, OptType: config.OptTypeStringArray, RequiresRestart: true, @@ -121,8 +144,8 @@ This setting mainly exists for when you need to simulate your presence in anothe config.CategoryAnnotation: "Routing", config.DisplayOrderAnnotation: cfgOptionDNSExitHubPolicyOrder, config.DisplayHintAnnotation: endpoints.DisplayHintEndpointList, - config.QuickSettingsAnnotation: profile.SPNRulesQuickSettings, - endpoints.EndpointListVerdictNamesAnnotation: profile.SPNRulesVerdictNames, + config.QuickSettingsAnnotation: spnRulesQuickSettings, + endpoints.EndpointListVerdictNamesAnnotation: spnRulesVerdictNames, }, ValidationRegex: endpoints.ListEntryValidationRegex, ValidationFunc: endpoints.ValidateEndpointListConfigOption, @@ -207,7 +230,7 @@ This setting mainly exists for when you need to simulate your presence in anothe // Config options for use. if conf.Integrated() { - cfgOptionRoutingAlgorithm = config.Concurrent.GetAsString(profile.CfgOptionRoutingAlgorithmKey, navigator.DefaultRoutingProfileID) + cfgOptionRoutingAlgorithm = config.Concurrent.GetAsString(navigator.CfgOptionRoutingAlgorithmKey, navigator.DefaultRoutingProfileID) } else { cfgOptionRoutingAlgorithm = func() string { return navigator.DefaultRoutingProfileID } } diff --git a/spn/captain/op_publish.go b/spn/captain/op_publish.go index 5a16ddc32..a1ad80fd7 100644 --- a/spn/captain/op_publish.go +++ b/spn/captain/op_publish.go @@ -69,6 +69,20 @@ func NewPublishOp(controller *docks.CraneControllerTerminal, identity *cabin.Ide return op, nil } +// parsePublishOpData parses the announcement and status from the publish op +// init data. +func parsePublishOpData(data *container.Container) (announcementData, statusData []byte, tErr *terminal.Error) { + announcementData, err := terminal.GetNextBlock(data) + if err != nil { + return nil, nil, terminal.ErrMalformedData.With("failed to get announcement: %w", err) + } + statusData, err = terminal.GetNextBlock(data) + if err != nil { + return nil, nil, terminal.ErrMalformedData.With("failed to get status: %w", err) + } + return announcementData, statusData, nil +} + func runPublishOp(t terminal.Terminal, opID uint32, data *container.Container) (terminal.Operation, *terminal.Error) { // Check if we are run by a controller. controller, ok := t.(*docks.CraneControllerTerminal) @@ -77,13 +91,9 @@ func runPublishOp(t terminal.Terminal, opID uint32, data *container.Container) ( } // Parse and import Announcement and Status. - announcementData, err := data.GetNextBlock() - if err != nil { - return nil, terminal.ErrMalformedData.With("failed to get announcement: %w", err) - } - statusData, err := data.GetNextBlock() - if err != nil { - return nil, terminal.ErrMalformedData.With("failed to get status: %w", err) + announcementData, statusData, tErr := parsePublishOpData(data) + if tErr != nil { + return nil, tErr } h, forward, tErr := docks.ImportAndVerifyHubInfo(module.mgr.Ctx(), "", announcementData, statusData, conf.MainMapName, conf.MainMapScope) if tErr != nil { diff --git a/spn/captain/op_publish_test.go b/spn/captain/op_publish_test.go new file mode 100644 index 000000000..3d1f0086d --- /dev/null +++ b/spn/captain/op_publish_test.go @@ -0,0 +1,42 @@ +package captain + +import ( + "bytes" + "testing" + + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// TestParsePublishOpDataWithHugeBlockSize checks that publish op init data +// with a crafted block size is rejected without allocating that size. +func TestParsePublishOpDataWithHugeBlockSize(t *testing.T) { + t.Parallel() + + for _, size := range []uint64{1 << 42, 1 << 62, 1<<64 - 1, 4} { + _, _, tErr := parsePublishOpData(container.New(varint.Pack64(size), []byte("abc"))) + if tErr == nil { + t.Fatalf("block size %d accepted", size) + } + } + // Status block with a huge size. + c := container.New() + c.AppendAsBlock([]byte("announcement")) + c.Append(varint.Pack64(1 << 42)) + _, _, tErr := parsePublishOpData(c) + if tErr == nil { + t.Fatal("huge status block size accepted") + } + + // Valid data must still parse. + c = container.New() + c.AppendAsBlock([]byte("announcement")) + c.AppendAsBlock([]byte("status")) + announcementData, statusData, tErr := parsePublishOpData(c) + if tErr != nil { + t.Fatal(tErr) + } + if !bytes.Equal(announcementData, []byte("announcement")) || !bytes.Equal(statusData, []byte("status")) { + t.Fatalf("unexpected parse result: %q %q", announcementData, statusData) + } +} diff --git a/spn/crew/connect.go b/spn/crew/connect.go index 7b1edb4be..730167117 100644 --- a/spn/crew/connect.go +++ b/spn/crew/connect.go @@ -28,7 +28,9 @@ func HandleSluiceRequest(connInfo *network.Connection, conn net.Conn) { if conn == nil { log.Debugf("spn/crew: closing tunnel for %s before starting because of shutdown", connInfo) - // This is called within the connInfo lock. + // The sluice calls this without holding the connInfo lock. + connInfo.Lock() + defer connInfo.Unlock() connInfo.Failed("tunnel entry closed", "") connInfo.SaveWhenFinished() return @@ -118,9 +120,25 @@ func (t *Tunnel) connectWorker(wc *mgr.WorkerCtx) (err error) { return nil } +// errNoTunnelOptions is returned when a connection to be tunneled carries no +// navigator options. +var errNoTunnelOptions = errors.New("no tunnel options set for connection") + +// getTunnelOptions returns the navigator options stored in the connection, or +// nil if the connection has none. +func getTunnelOptions(conn *network.Connection) *navigator.Options { + opts, _ := conn.TunnelOpts.(*navigator.Options) + return opts +} + func (t *Tunnel) establish(ctx context.Context) (err error) { var routes *navigator.Routes + tunnelOpts := getTunnelOptions(t.connInfo) + if tunnelOpts == nil { + return errNoTunnelOptions + } + // Check if the destination sticks to a Hub. sticksTo := getStickiedHub(t.connInfo) switch { @@ -140,7 +158,7 @@ func (t *Tunnel) establish(ctx context.Context) (err error) { } // Append to policies. - t.connInfo.TunnelOpts.Destination.HubPolicies = append(t.connInfo.TunnelOpts.Destination.HubPolicies, avoidPolicy) + tunnelOpts.Destination.HubPolicies = append(tunnelOpts.Destination.HubPolicies, avoidPolicy) default: log.Tracer(ctx).Tracef("spn/crew: using stickied %s", sticksTo.Pin.Hub) @@ -158,7 +176,7 @@ func (t *Tunnel) establish(ctx context.Context) (err error) { // If not, attempt to find a route to the stickied hub. routes, err = navigator.Main.FindRouteToHub( sticksTo.Pin.Hub.ID, - t.connInfo.TunnelOpts, + tunnelOpts, ) if err != nil { log.Tracer(ctx).Tracef("spn/crew: failed to find route to stickied %s: %s", sticksTo.Pin.Hub, err) @@ -173,7 +191,7 @@ func (t *Tunnel) establish(ctx context.Context) (err error) { log.Tracer(ctx).Trace("spn/crew: finding routes...") routes, err = navigator.Main.FindRoutes( t.connInfo.Entity.IP, - t.connInfo.TunnelOpts, + tunnelOpts, ) if err != nil { return fmt.Errorf("failed to find routes to %s: %w", t.connInfo.Entity.IP, err) @@ -215,6 +233,9 @@ type hopCheck struct { expansion *docks.ExpansionTerminal authOp *access.AuthorizeOp pingOp *PingOp + + // expansionInUse is set when the new expansion was taken into use. + expansionInUse bool } func establishRoute(route *navigator.Route) (dstPin *navigator.Pin, dstTerminal terminal.Terminal, err error) { @@ -255,6 +276,19 @@ func establishRoute(route *navigator.Route) (dstPin *navigator.Pin, dstTerminal // Build path and save created paths. hopChecks := make([]*hopCheck, 0, len(route.Path)-1) + // If building the route fails, abandon all new expansions that were not + // taken into use. Nothing else references them, so they would otherwise + // linger until their idle timeout. + defer func() { + if err == nil { + return + } + for _, check := range hopChecks { + if check.authOp != nil && !check.expansionInUse { + check.expansion.Abandon(nil) + } + } + }() for i, hop := range route.Path[1:] { // Check if we already have a connection to the Hub. activeTerminal := hop.Pin().GetActiveTerminal() @@ -317,9 +351,7 @@ func establishRoute(route *navigator.Route) (dstPin *navigator.Pin, dstTerminal default: // Authentication was aborted. - if tErr != nil { - tErr = terminal.ErrUnknownError - } + tErr = abortedAuthError(tErr) log.Warningf("spn/crew: auth to %s aborted with %s", check.pin.Hub, tErr) return nil, nil, tErr.Wrap("authentication to %s aborted: %w", check.pin.Hub, tErr) } @@ -337,6 +369,7 @@ func establishRoute(route *navigator.Route) (dstPin *navigator.Pin, dstTerminal Terminal: check.expansion, Route: check.route, }) + check.expansionInUse = true check.expansion.MarkReachable() log.Infof("spn/crew: added conn to %s via %s", check.pin, check.route) @@ -379,6 +412,18 @@ func establishRoute(route *navigator.Route) (dstPin *navigator.Pin, dstTerminal return previousHop, previousTerminal, nil } +// abortedAuthError returns the error to report for an aborted authentication. +// The result of an operation that was stopped without an error is nil. As a +// nil *terminal.Error stays nil when wrapped and turns into a non-nil error +// interface with a nil pointer when returned as an error, it must be replaced +// with an actual error. +func abortedAuthError(tErr *terminal.Error) *terminal.Error { + if tErr == nil { + return terminal.ErrUnknownError + } + return tErr +} + func expand(fromTerminal terminal.Terminal, from, to *navigator.Pin) (expansion *docks.ExpansionTerminal, authOp *access.AuthorizeOp, tErr *terminal.Error) { expansion, tErr = docks.ExpandTo(fromTerminal, to.Hub.ID, to.Hub) if tErr != nil { diff --git a/spn/crew/connect_route_test.go b/spn/crew/connect_route_test.go new file mode 100644 index 000000000..ae6691d84 --- /dev/null +++ b/spn/crew/connect_route_test.go @@ -0,0 +1,190 @@ +package crew + +import ( + "testing" + "time" + + "github.com/safing/portmaster/spn/cabin" + "github.com/safing/portmaster/spn/conf" + "github.com/safing/portmaster/spn/docks" + "github.com/safing/portmaster/spn/hub" + "github.com/safing/portmaster/spn/navigator" + "github.com/safing/portmaster/spn/ships" + "github.com/safing/portmaster/spn/terminal" +) + +// routeTestSetup holds a route from a home hub via a transit hub to a +// destination hub on the main map. +type routeTestSetup struct { + route *navigator.Route + + home, transit, destination *cabin.Identity + + // homeTerminal is the terminal to the home hub. It belongs to a crane + // that is never started, so everything sent through it is swallowed and + // no replies arrive: expansions via the home hub are started successfully, + // but authentication never completes. + homeTerminal *docks.CraneTerminal + homeCrane *docks.Crane +} + +// setupRouteTest creates three new hubs that are connected in a line, adds +// them to the main map, sets the first one as home hub and returns the route +// to the last one. +func setupRouteTest(t *testing.T) *routeTestSetup { + t.Helper() + + s := &routeTestSetup{} + + // Create hubs with exchange keys. + var err error + for _, id := range []**cabin.Identity{&s.home, &s.transit, &s.destination} { + *id, err = cabin.CreateIdentity(module.mgr.Ctx(), conf.MainMapName) + if err != nil { + t.Fatalf("failed to create identity: %s", err) + } + } + + // Connect them: home <-> transit <-> destination. + lane := func(to *cabin.Identity) *hub.Lane { + return &hub.Lane{ + ID: to.Hub.ID, + Latency: 10 * time.Millisecond, + Capacity: 100_000_000, + } + } + for _, link := range []struct { + id *cabin.Identity + lanes []*hub.Lane + }{ + {s.home, []*hub.Lane{lane(s.transit)}}, + {s.transit, []*hub.Lane{lane(s.home), lane(s.destination)}}, + {s.destination, []*hub.Lane{lane(s.transit)}}, + } { + _, err = link.id.MaintainStatus(link.lanes, nil, nil, true) + if err != nil { + t.Fatalf("failed to set lanes: %s", err) + } + } + for _, id := range []*cabin.Identity{s.home, s.transit, s.destination} { + navigator.Main.UpdateHub(id.Hub) + } + // Add the lanes of the first hub again, as its peer was not yet on the map. + navigator.Main.UpdateHub(s.home.Hub) + + // Create the terminal to the home hub. + s.homeCrane, err = docks.NewCrane(ships.NewTestShip(true, 100), s.home.Hub, nil) + if err != nil { + t.Fatalf("failed to create crane: %s", err) + } + var tErr *terminal.Error + s.homeTerminal, _, tErr = docks.NewLocalCraneTerminal(s.homeCrane, nil, terminal.DefaultHomeHubTerminalOpts()) + if tErr != nil { + t.Fatalf("failed to create crane terminal: %s", tErr) + } + t.Cleanup(func() { + s.homeTerminal.Abandon(nil) + s.homeCrane.Stop(nil) + }) + + // Set home hub and find the route. + if !navigator.Main.SetHome(s.home.Hub.ID, s.homeTerminal) { + t.Fatal("failed to set home hub") + } + routes, err := navigator.Main.FindRouteToHub(s.destination.Hub.ID, navigator.Main.DefaultOptions()) + if err != nil { + for _, id := range []*cabin.Identity{s.home, s.transit, s.destination} { + pin, _ := navigator.Main.GetPin(id.Hub.ID) + t.Logf("%s: states=%s hop distance=%d lanes=%d", pin, pin.State, pin.HopDistance, len(pin.ConnectedTo)) + } + t.Fatalf("failed to find route: %s", err) + } + if len(routes.All) == 0 { + t.Fatal("no route found") + } + s.route = routes.All[0] + if len(s.route.Path) != 3 { + t.Fatalf("unexpected route: %s", s.route) + } + + return s +} + +// waitForNoActiveOps waits until the given terminal has no active operations. +func waitForNoActiveOps(t *testing.T, term *docks.CraneTerminal, within time.Duration) { + t.Helper() + + started := time.Now() + for term.GetActiveOpCount() > 0 { + if time.Since(started) > within { + t.Fatalf( + "%d operations still active on %s after %s: expansions were not abandoned", + term.GetActiveOpCount(), term.FmtID(), time.Since(started), + ) + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestEstablishRouteAbandonsExpansionsOnAuthTimeout checks that establishRoute +// abandons the expansions it created when authenticating to a hop times out. +func TestEstablishRouteAbandonsExpansionsOnAuthTimeout(t *testing.T) { //nolint:paralleltest // Uses the home hub of the main map. + s := setupRouteTest(t) + + // Both expansions can be started, as nothing waits for a reply. But the + // authentication to the transit hub never completes. + _, _, err := establishRoute(s.route) + if err == nil { + t.Fatal("establishing the route should fail") + } + t.Logf("establishing route failed as expected: %s", err) + + // The expansion to the transit hub runs as an operation on the home hub + // terminal. Abandoning the expansion stops this operation. Without cleanup, + // it would only be stopped by the idle timeout of the expansion terminal. + waitForNoActiveOps(t, s.homeTerminal, 5*time.Second) + + // No expansion may have been taken into use. + for _, hop := range s.route.Path[1:] { + if hop.Pin().GetActiveTerminal() != nil { + t.Errorf("%s has an active terminal", hop.Pin()) + } + } +} + +// TestEstablishRouteAbandonsExpansionsOnExpandFailure checks that +// establishRoute abandons the expansions it created when expanding to a later +// hop fails. +func TestEstablishRouteAbandonsExpansionsOnExpandFailure(t *testing.T) { //nolint:paralleltest // Uses the home hub of the main map. + s := setupRouteTest(t) + + // Remove the exchange keys of the destination hub after the route was + // found, so that no encrypted expansion to it can be created. + func() { + s.destination.Hub.Lock() + defer s.destination.Hub.Unlock() + + status := s.destination.Hub.Status.Copy() + status.Keys = nil + s.destination.Hub.Status = status + }() + + // The expansion to the transit hub is started successfully, the one to the + // destination hub fails before any authentication result is awaited. + started := time.Now() + _, _, err := establishRoute(s.route) + if err == nil { + t.Fatal("establishing the route should fail") + } + t.Logf("establishing route failed as expected after %s: %s", time.Since(started), err) + + // The expansion to the transit hub must be abandoned. + waitForNoActiveOps(t, s.homeTerminal, 5*time.Second) + + if s.transit.Hub.ID != s.route.Path[1].HubID { + t.Fatalf("unexpected transit hub in route %s", s.route) + } + if pin := s.route.Path[1].Pin(); pin.GetActiveTerminal() != nil { + t.Errorf("%s has an active terminal", pin) + } +} diff --git a/spn/crew/connect_test.go b/spn/crew/connect_test.go new file mode 100644 index 000000000..39de7c7c0 --- /dev/null +++ b/spn/crew/connect_test.go @@ -0,0 +1,40 @@ +package crew + +import ( + "errors" + "testing" + + "github.com/safing/portmaster/spn/terminal" +) + +// TestAbortedAuthError checks that an aborted authentication always results in +// a usable error, also if the operation was stopped without an error. +func TestAbortedAuthError(t *testing.T) { + t.Parallel() + + // A nil *terminal.Error stays nil when wrapped and does not report an error. + var nilErr *terminal.Error + if nilErr.Wrap("test") != nil || nilErr.IsError() || nilErr.Is(terminal.ErrExplicitAck) { + t.Fatal("unexpected nil receiver behavior") + } + + // The aborted error must always be a real error that is wrapped properly. + for _, tErr := range []*terminal.Error{nil, terminal.ErrStopping} { + wrapped := abortedAuthError(tErr).Wrap("authentication aborted: %w", tErr) + if wrapped == nil { + t.Fatalf("aborted error for %v is nil", tErr) + } + if wrapped.Error() == "" { // Panics on a nil error. + t.Fatalf("aborted error for %v has no message", tErr) + } + } + + // An error reported by the operation must be preserved. + if !abortedAuthError(terminal.ErrStopping).Is(terminal.ErrStopping) { + t.Fatal("error of the aborted operation was replaced") + } + // A missing error must become an unknown error. + if !errors.Is(abortedAuthError(nil), terminal.ErrUnknownError) { + t.Fatal("missing error was not replaced with an unknown error") + } +} diff --git a/spn/crew/module_test.go b/spn/crew/module_test.go index 8426716ee..4e9aa644d 100644 --- a/spn/crew/module_test.go +++ b/spn/crew/module_test.go @@ -10,20 +10,42 @@ import ( "github.com/safing/portmaster/base/metrics" "github.com/safing/portmaster/base/rng" "github.com/safing/portmaster/service/core/base" + "github.com/safing/portmaster/service/intel/geoip" "github.com/safing/portmaster/service/mgr" + "github.com/safing/portmaster/service/netenv" + "github.com/safing/portmaster/service/updates" + "github.com/safing/portmaster/spn/access" "github.com/safing/portmaster/spn/cabin" "github.com/safing/portmaster/spn/conf" + "github.com/safing/portmaster/spn/docks" + "github.com/safing/portmaster/spn/hub" + "github.com/safing/portmaster/spn/navigator" "github.com/safing/portmaster/spn/terminal" ) type testInstance struct { - db *dbmodule.DBModule - config *config.Config - metrics *metrics.Metrics - rng *rng.Rng - base *base.Base - terminal *terminal.TerminalModule - cabin *cabin.Cabin + db *dbmodule.DBModule + config *config.Config + metrics *metrics.Metrics + rng *rng.Rng + base *base.Base + terminal *terminal.TerminalModule + cabin *cabin.Cabin + docks *docks.Docks + geoip *geoip.GeoIP + navigator *navigator.Navigator + + // updates is an updater without any index. It makes geoip lookups fail + // cleanly, as no geoip databases are available in tests. + updates *updates.Updater +} + +func (stub *testInstance) BinaryUpdates() *updates.Updater { + return stub.updates +} + +func (stub *testInstance) IntelUpdates() *updates.Updater { + return stub.updates } func (stub *testInstance) Config() *config.Config { @@ -52,6 +74,11 @@ var _dataDir string func runTest(m *testing.M) error { conf.EnablePublicHub(true) // Make hub config available. + access.EnableTestMode() // Register test zone instead of real ones. + // Do not probe the network (eg. with traceroute) for the device location, + // which the navigator requests when adding hubs to the main map. + netenv.DisableNetworkDerivedLocation(true) + var err error // Create a temporary directory for the data _dataDir, err = os.MkdirTemp("", "") @@ -60,7 +87,9 @@ func runTest(m *testing.M) error { } defer func() { _ = os.RemoveAll(_dataDir) }() - instance := &testInstance{} + instance := &testInstance{ + updates: &updates.Updater{}, + } // Init instance.db, err = dbmodule.New(instance) if err != nil { @@ -90,6 +119,20 @@ func runTest(m *testing.M) error { if err != nil { return fmt.Errorf("failed to create cabin module: %w", err) } + instance.docks, err = docks.New(instance) + if err != nil { + return fmt.Errorf("failed to create docks module: %w", err) + } + // The geoip module is only created, not started, as there are no geoip + // databases. The navigator needs it to look up (missing) locations. + instance.geoip, err = geoip.New(instance) + if err != nil { + return fmt.Errorf("failed to create geoip module: %w", err) + } + instance.navigator, err = navigator.New(instance) + if err != nil { + return fmt.Errorf("failed to create navigator module: %w", err) + } module, err = New(instance) if err != nil { return fmt.Errorf("failed to create crew module: %w", err) @@ -124,10 +167,35 @@ func runTest(m *testing.M) error { if err != nil { return fmt.Errorf("failed to start cabin module: %w", err) } + err = instance.docks.Start() + if err != nil { + return fmt.Errorf("failed to start docks module: %w", err) + } + err = instance.navigator.Start() + if err != nil { + return fmt.Errorf("failed to start navigator module: %w", err) + } + // Hubs are only regarded for routing after the intel data was applied. + // Use empty intel data, so that no intel based states are set. + mapIntel := &hub.Intel{} + err = mapIntel.ParseAdvisories() + if err != nil { + return fmt.Errorf("failed to parse map intel: %w", err) + } + err = navigator.Main.UpdateIntel(mapIntel, nil) + if err != nil { + return fmt.Errorf("failed to set map intel: %w", err) + } err = module.Start() if err != nil { return fmt.Errorf("failed to start crew module: %w", err) } + // Initialize the access zones without the access module, which would also + // manage the account and request tokens. + err = access.InitializeZones() + if err != nil { + return fmt.Errorf("failed to initialize access zones: %w", err) + } conf.EnablePublicHub(true) m.Run() diff --git a/spn/crew/op_compressed_test.go b/spn/crew/op_compressed_test.go new file mode 100644 index 000000000..e7074167b --- /dev/null +++ b/spn/crew/op_compressed_test.go @@ -0,0 +1,55 @@ +package crew + +import ( + "errors" + "testing" + "time" + + "github.com/safing/portmaster/spn/terminal" + "github.com/safing/structures/container" + "github.com/safing/structures/dsd" +) + +// TestCrewOpsRejectCompressed checks that gzip compressed op data is rejected +// before decompression. dsd.Load decompresses it into an unbounded buffer, so +// a 16KB message could make the receiver allocate about 64MB. +func TestCrewOpsRejectCompressed(t *testing.T) { + t.Parallel() + + nonce := []byte{1, 2, 3, 4} + + // Ping request. + data, err := dsd.DumpAndCompress(&PingOpRequest{Nonce: nonce}, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + a, _, err := terminal.NewSimpleTestTerminalPair(0, 0, nil) + if err != nil { + t.Fatal(err) + } + _, tErr := startPingOp(a, 1, container.New(data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("ping request: expected ErrIncompatibleFormat, got %v", tErr) + } + + // Ping response. + data, err = dsd.DumpAndCompress(&PingOpResponse{Nonce: nonce, Time: time.Now()}, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + op := &PingOp{nonce: nonce} + tErr = op.Deliver(terminal.NewMsg(data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("ping response: expected ErrIncompatibleFormat, got %v", tErr) + } + + // Connect request. + data, err = dsd.DumpAndCompress(&ConnectRequest{}, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, tErr = startConnectOp(a, 1, container.New(data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("connect request: expected ErrIncompatibleFormat, got %v", tErr) + } +} diff --git a/spn/crew/op_connect.go b/spn/crew/op_connect.go index 119126ede..5e05b4f2f 100644 --- a/spn/crew/op_connect.go +++ b/spn/crew/op_connect.go @@ -15,6 +15,7 @@ import ( "github.com/safing/portmaster/service/network/netutils" "github.com/safing/portmaster/service/network/packet" "github.com/safing/portmaster/spn/conf" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/portmaster/spn/terminal" "github.com/safing/structures/container" "github.com/safing/structures/dsd" @@ -176,7 +177,7 @@ func startConnectOp(t terminal.Terminal, opID uint32, data *container.Container) // Parse connect request. request := &ConnectRequest{} - _, err := dsd.Load(data.CompileData(), request) + _, err := peerdsd.Load(data.CompileData(), request) if err != nil { connectOpCntError.Inc() // More like a protocol/system error than a bad request. return nil, terminal.ErrMalformedData.With("failed to parse connect request: %w", err) @@ -418,7 +419,7 @@ func (op *ConnectOp) connWriter(_ *mgr.WorkerCtx) error { }() var msg *terminal.Msg - defer msg.Finish() + defer func() { msg.Finish() }() rateLimiter := terminal.NewRateLimiter(rateLimitMaxMbit) diff --git a/spn/crew/op_connect_test.go b/spn/crew/op_connect_test.go index 010bca0f0..5c3c4901c 100644 --- a/spn/crew/op_connect_test.go +++ b/spn/crew/op_connect_test.go @@ -25,8 +25,14 @@ const ( func TestConnectOp(t *testing.T) { t.Parallel() + // This test cannot be made hermetic: the exit side of the connect op only + // connects to IPs in the global scope (see ConnectOp.setup), so a local + // listener on a loopback or LAN address is always denied. Running it + // without network access would require a configurable scope check in + // production code, which does not exist. if testing.Short() { - t.Skip("skipping test in short mode, as it interacts with the network") + t.Skip("skipping test in short mode: it connects to orf.at:80 on the Internet, " + + "because the connect op only allows destinations with a global IP") } // Create test terminal pair. @@ -41,6 +47,10 @@ func TestConnectOp(t *testing.T) { t.Fatalf("failed to create test terminal pair: %s", err) } + // The exit side of the connect op requires a terminal with a session for + // rate limiting. Test terminals have none, so attach one to b. + b.SetTerminalExtension(&sessionTestTerminal{TestTerminal: b}) + // Set up connect op. b.GrantPermission(terminal.MayConnect) conf.EnablePublicHub(true) @@ -112,3 +122,10 @@ func TestConnectOp(t *testing.T) { time.Sleep(500 * time.Millisecond) } } + +// sessionTestTerminal adds session support to a test terminal, as required by +// operations that rate limit per session, such as the connect op. +type sessionTestTerminal struct { + *terminal.TestTerminal + terminal.SessionAddOn +} diff --git a/spn/crew/op_msgpack_test.go b/spn/crew/op_msgpack_test.go new file mode 100644 index 000000000..51e13250c --- /dev/null +++ b/spn/crew/op_msgpack_test.go @@ -0,0 +1,31 @@ +package crew + +import ( + "errors" + "testing" + + "github.com/safing/portmaster/spn/peerdsd" + "github.com/safing/portmaster/spn/terminal" + "github.com/safing/structures/container" +) + +// TestPingOpRejectsOversizedMsgPack checks that a msgpack ping request that +// declares more data than it holds is rejected before decoding. The msgpack +// decoder allocates the declared length up front, so 12 bytes sent by any +// client could make a Hub allocate 4GB. +// The length used here is smaller to keep the test cheap without the fix. +func TestPingOpRejectsOversizedMsgPack(t *testing.T) { + t.Parallel() + + a, _, err := terminal.NewSimpleTestTerminalPair(0, 0, nil) + if err != nil { + t.Fatal(err) + } + + // PingOpRequest.Nonce with a declared length of 64MB. + data := []byte{'M', 0x81, 0xa5, 'N', 'o', 'n', 'c', 'e', 0xc6, 0x04, 0x00, 0x00, 0x00} + _, tErr := startPingOp(a, 1, container.New(data)) + if !errors.Is(tErr, peerdsd.ErrLengthExceedsData) { + t.Errorf("expected ErrLengthExceedsData, got %v", tErr) + } +} diff --git a/spn/crew/op_ping.go b/spn/crew/op_ping.go index 43d433648..50fe83a5a 100644 --- a/spn/crew/op_ping.go +++ b/spn/crew/op_ping.go @@ -5,6 +5,7 @@ import ( "time" "github.com/safing/portmaster/base/rng" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/portmaster/spn/terminal" "github.com/safing/structures/container" "github.com/safing/structures/dsd" @@ -87,7 +88,7 @@ func (op *PingOp) Deliver(msg *terminal.Msg) *terminal.Error { // Parse response. response := &PingOpResponse{} - _, err := dsd.Load(msg.Data.CompileData(), response) + _, err := peerdsd.Load(msg.Data.CompileData(), response) if err != nil { return terminal.ErrMalformedData.With("failed to parse ping response: %w", err) } @@ -103,7 +104,7 @@ func (op *PingOp) Deliver(msg *terminal.Msg) *terminal.Error { func startPingOp(t terminal.Terminal, opID uint32, data *container.Container) (terminal.Operation, *terminal.Error) { // Parse request. request := &PingOpRequest{} - _, err := dsd.Load(data.CompileData(), request) + _, err := peerdsd.Load(data.CompileData(), request) if err != nil { return nil, terminal.ErrMalformedData.With("failed to parse ping request: %w", err) } diff --git a/spn/crew/sticky.go b/spn/crew/sticky.go index baea2979c..fa0b19d1a 100644 --- a/spn/crew/sticky.go +++ b/spn/crew/sticky.go @@ -101,7 +101,11 @@ func getStickiedHub(conn *network.Connection) (sticksTo *stickyHub) { } // Disregard stickied Hub if it is disregard with the current options. - matcher := conn.TunnelOpts.Destination.Matcher(mapIntel) + tunnelOpts := getTunnelOptions(conn) + if tunnelOpts == nil { + return nil + } + matcher := tunnelOpts.Destination.Matcher(mapIntel) if !matcher(sticksTo.Pin) { return nil } diff --git a/spn/docks/crane.go b/spn/docks/crane.go index 9c6d11830..bb1ba3b2d 100644 --- a/spn/docks/crane.go +++ b/spn/docks/crane.go @@ -2,10 +2,12 @@ package docks import ( "context" + "encoding/binary" "errors" "fmt" "io" "net" + "slices" "sync" "time" @@ -414,7 +416,7 @@ func (crane *Crane) decrypt(shipment *container.Container) (decrypted *container crane.jessionLock.Lock() defer crane.jessionLock.Unlock() - letter, err := jess.LetterFromWire(shipment) + letter, err := terminal.LetterFromWire(shipment) if err != nil { return nil, fmt.Errorf("failed to parse letter: %w", err) } @@ -647,8 +649,9 @@ handling: } func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { - shipment := container.New() - var partialShipment *container.Container + // shipment holds the segments waiting to be loaded. It is only used for + // assembling and is reused, as load() copies the data it loads. + shipment := make([]byte, 0, crane.targetLoadSize+maxSegmentLength) var loadingTimer *time.Timer // Unclean shutdown safeguard. @@ -664,8 +667,8 @@ func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { // Make sure any received message is finished var msg, firstMsg *terminal.Msg - defer msg.Finish() - defer firstMsg.Finish() + defer func() { msg.Finish() }() + defer func() { firstMsg.Finish() }() for { // Reset first message in shipment. @@ -673,7 +676,7 @@ func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { firstMsg = nil fillingShipment: - for shipment.Length() < crane.targetLoadSize { + for len(shipment) < crane.targetLoadSize { // Gather segments until shipment is filled. // Prioritize messages from the controller. @@ -701,9 +704,12 @@ func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { // Handle new message. if msg != nil { - // Pack msg and add to segment. - msg.Pack() - newSegment := msg.Data + // Calculate segment size. + // The segment is the msg packed with terminal.MakeMsg: Length, ID+Type, Data. + idType := uint64(msg.FlowID | uint32(msg.Type)) + dataLength := msg.Data.Length() + contentLength := uint64(varint.EncodedSize(idType) + dataLength) //nolint:gosec // Length is never negative. + segmentLength := varint.EncodedSize(contentLength) + int(contentLength) //nolint:gosec // Converted from int. // Check if this is the first message. // This is the only message where we wait for a slot. @@ -715,13 +721,17 @@ func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { } // Check length. - if newSegment.Length() > maxSegmentLength { - log.Warningf("spn/docks: %s ignored oversized segment with length %d", crane, newSegment.Length()) + if segmentLength > maxSegmentLength { + log.Warningf("spn/docks: %s ignored oversized segment with length %d", crane, segmentLength) continue fillingShipment } - // Append to shipment. - shipment.AppendContainer(newSegment) + // Append segment to shipment. + shipment = binary.AppendUvarint(shipment, contentLength) + shipment = binary.AppendUvarint(shipment, idType) + shipment = slices.Grow(shipment, dataLength) + msg.Data.WriteToSlice(shipment[len(shipment) : len(shipment)+dataLength]) + shipment = shipment[:len(shipment)+dataLength] // Set loading max wait timer on first segment. if loadingTimer == nil { @@ -738,17 +748,10 @@ func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { sendingShipment: for { // Check if we are over the target load size and split the shipment. - if shipment.Length() > crane.targetLoadSize { - partialShipment, err = shipment.GetAsContainer(crane.targetLoadSize) - if err != nil { - crane.Stop(terminal.ErrInternalError.With("failed to split segment: %w", err)) - return nil - } - shipment, partialShipment = partialShipment, shipment - } + loadSize := min(len(shipment), crane.targetLoadSize) // Load shipment. - err = crane.load(shipment) + err = crane.load(shipment[:loadSize]) if err != nil { crane.Stop(terminal.ErrShipSunk.With("failed to load shipment: %w", err)) return nil @@ -757,84 +760,26 @@ func (crane *Crane) loader(workerCtx *mgr.WorkerCtx) (err error) { // Reset loading timer. loadingTimer = nil - // Continue loading with partial shipment, or a new one. - if partialShipment != nil { - // Continue loading with a partial previous shipment. - shipment, partialShipment = partialShipment, nil + // Continue loading with the remainder of the shipment, or a new one. + if loadSize < len(shipment) { + // Continue loading with the remainder of the previous shipment. + shipment = shipment[:copy(shipment, shipment[loadSize:])] // If shipment is not big enough to send immediately, wait for more data. - if shipment.Length() < crane.targetLoadSize { + if len(shipment) < crane.targetLoadSize { loadingTimer = time.NewTimer(loadingMaxWaitDuration) break sendingShipment } } else { // Continue loading with new shipment. - shipment = container.New() + shipment = shipment[:0] break sendingShipment } } } } -func (crane *Crane) load(c *container.Container) error { - // Add Padding if needed. - if crane.opts.Padding > 0 { - paddingNeeded := int(crane.opts.Padding) - - ((c.Length() + varint.EncodedSize(uint64(c.Length()))) % int(crane.opts.Padding)) - // As the length changes slightly with the padding, we should avoid loading - // lengths around the varint size hops: - // - 128 - // - 16384 - // - 2097152 - // - 268435456 - - // Pad to target load size at maximum. - maxPadding := crane.targetLoadSize - c.Length() - if paddingNeeded > maxPadding { - paddingNeeded = maxPadding - } - - if paddingNeeded > 0 { - // Add padding indicator. - c.Append([]byte{0}) - paddingNeeded-- - - // Add needed padding data. - if paddingNeeded > 0 { - padding, err := rng.Bytes(paddingNeeded) - if err != nil { - log.Debugf("spn/docks: %s failed to get random padding data, using zeros instead", crane) - padding = make([]byte, paddingNeeded) - } - c.Append(padding) - } - } - } - - // Encrypt shipment. - c, err := crane.encrypt(c) - if err != nil { - return fmt.Errorf("failed to encrypt: %w", err) - } - - // Finalize data. - c.PrependLength() - readyToSend := c.CompileData() - - // Submit metrics. - crane.submitCraneTrafficStats(len(readyToSend)) - crane.NetState.ReportTraffic(uint64(len(readyToSend)), false) - - // Load onto ship. - err = crane.ship.Load(readyToSend) - if err != nil { - return fmt.Errorf("failed to load ship: %w", err) - } - - return nil -} - // Stop stops the crane. func (crane *Crane) Stop(err *terminal.Error) { if !crane.stopped.SetToIf(false, true) { @@ -912,3 +857,84 @@ func (crane *Crane) String() string { func (crane *Crane) Stopped() bool { return crane.stopped.IsSet() } + +// load pads, encrypts, length-prefixes and loads the given shipment onto the +// ship. The given data is copied and not retained. +func (crane *Crane) load(data []byte) error { + // Calculate padding. + var paddingNeeded int + if crane.opts.Padding > 0 { + paddingNeeded = int(crane.opts.Padding) - + ((len(data) + varint.EncodedSize(uint64(len(data)))) % int(crane.opts.Padding)) + // As the length changes slightly with the padding, we should avoid loading + // lengths around the varint size hops: + // - 128 + // - 16384 + // - 2097152 + // - 268435456 + + // Pad to target load size at maximum. + maxPadding := crane.targetLoadSize - len(data) + if paddingNeeded > maxPadding { + paddingNeeded = maxPadding + } + if paddingNeeded < 0 { + paddingNeeded = 0 + } + } + + // Build the final shipment in a new buffer, as the ship may retain it. + // Without encryption, reserve space for the length prefix in front. + // The jess session is set before the loader starts and never changes. + encrypting := crane.jession != nil + shipmentLength := len(data) + paddingNeeded + var prefixLength int + if !encrypting { + prefixLength = varint.EncodedSize(uint64(shipmentLength)) + } + buf := make([]byte, prefixLength+shipmentLength) + shipment := buf[prefixLength:] + copy(shipment, data) + + // Add Padding if needed. + if paddingNeeded > 0 { + // The padding indicator (0) is already in place, as buf is zeroed. + // Add needed padding data. + if paddingNeeded > 1 { + _, err := rng.Read(shipment[len(data)+1:]) + if err != nil { + log.Debugf("spn/docks: %s failed to get random padding data, using zeros instead", crane) + clear(shipment[len(data)+1:]) + } + } + } + + var readyToSend []byte + if !encrypting { + // Finalize data. + binary.PutUvarint(buf, uint64(shipmentLength)) + readyToSend = buf + } else { + // Encrypt shipment. + c, err := crane.encrypt(container.New(shipment)) + if err != nil { + return fmt.Errorf("failed to encrypt: %w", err) + } + + // Finalize data. + c.PrependLength() + readyToSend = c.CompileData() + } + + // Submit metrics. + crane.submitCraneTrafficStats(len(readyToSend)) + crane.NetState.ReportTraffic(uint64(len(readyToSend)), false) + + // Load onto ship. + err := crane.ship.Load(readyToSend) + if err != nil { + return fmt.Errorf("failed to load ship: %w", err) + } + + return nil +} diff --git a/spn/docks/crane_bench_test.go b/spn/docks/crane_bench_test.go new file mode 100644 index 000000000..dc74f02ad --- /dev/null +++ b/spn/docks/crane_bench_test.go @@ -0,0 +1,267 @@ +package docks + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + "github.com/safing/portmaster/spn/cabin" + "github.com/safing/portmaster/spn/hub" + "github.com/safing/portmaster/spn/ships" + "github.com/safing/portmaster/spn/terminal" + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +const benchSinkOpType = "debug/docks-bench-sink" + +func init() { + terminal.RegisterOpType(terminal.OperationFactory{ + Type: benchSinkOpType, + Start: startBenchSinkOp, + }) +} + +// benchSinkOp receives a fixed number of data messages and then signals done. +type benchSinkOp struct { + terminal.OperationBase + + remaining uint64 + done chan struct{} +} + +func (op *benchSinkOp) Type() string { return benchSinkOpType } + +func (op *benchSinkOp) Deliver(msg *terminal.Msg) *terminal.Error { + msg.Finish() + // Deliver is only called by the terminal handler, so no locking is needed. + op.remaining-- + if op.remaining == 0 { + close(op.done) + } + return nil +} + +// benchSinkDone is used to pass the done channel of the remote sink to the +// benchmark. +var benchSinkDone = make(chan chan struct{}, 1) + +func startBenchSinkOp(t terminal.Terminal, opID uint32, data *container.Container) (terminal.Operation, *terminal.Error) { + n, err := data.GetNextN64() + if err != nil { + return nil, terminal.ErrMalformedData.With("failed to get msg count: %w", err) + } + op := &benchSinkOp{ + remaining: n, + done: make(chan struct{}), + } + op.InitOperationBase(t, opID) + benchSinkDone <- op.done + return op, nil +} + +// benchSourceOp sends data messages. +type benchSourceOp struct { + terminal.OperationBase +} + +func (op *benchSourceOp) Type() string { return benchSinkOpType } + +func (op *benchSourceOp) Deliver(msg *terminal.Msg) *terminal.Error { + msg.Finish() + return nil +} + +// benchSinkTerminal is a crane terminal replacement that just counts messages. +type benchSinkTerminal struct { + terminal.BareTerminal + + id uint32 + crane *Crane + remaining int + done chan struct{} +} + +func (t *benchSinkTerminal) ID() uint32 { return t.id } +func (t *benchSinkTerminal) Ctx() context.Context { return module.mgr.Ctx() } +func (t *benchSinkTerminal) FmtID() string { return fmt.Sprintf("bench-%d", t.id) } + +func (t *benchSinkTerminal) Abandon(_ *terminal.Error) { + t.crane.deleteTerminal(t.id) +} + +func (t *benchSinkTerminal) Deliver(msg *terminal.Msg) *terminal.Error { + msg.Finish() + // Deliver is only called by the crane handler, so no locking is needed. + t.remaining-- + if t.remaining == 0 { + close(t.done) + } + return nil +} + +func startBenchCranes(b *testing.B, encrypt bool) (crane1, crane2 *Crane) { + b.Helper() + + var identity *cabin.Identity + var connectedHub *hub.Hub + if encrypt { + if testIdentity == nil { + var err error + testIdentity, err = cabin.CreateIdentity(module.mgr.Ctx(), "test") + if err != nil { + b.Fatalf("failed to create identity: %s", err) + } + } + identity, connectedHub = testIdentity, testIdentity.Hub + } + + // Use realistic load sizes. Tests may modify this global. + optimalMinLoadSize = 3072 + ship := ships.NewTestShip(!encrypt, ships.BaseMTU) + + var wg sync.WaitGroup + wg.Add(2) + errs := make(chan error, 2) + go func() { + defer wg.Done() + var err error + crane1, err = NewCrane(ship, connectedHub, nil) + if err == nil { + err = crane1.Start(module.mgr.Ctx()) + } + if err != nil { + errs <- err + } + }() + go func() { + defer wg.Done() + var err error + crane2, err = NewCrane(ship.Reverse(), nil, identity) + if err == nil { + err = crane2.Start(module.mgr.Ctx()) + } + if err != nil { + errs <- err + } + }() + wg.Wait() + close(errs) + for err := range errs { + b.Fatalf("failed to start cranes: %s", err) + } + + return crane1, crane2 +} + +func stopBenchCranes(crane1, crane2 *Crane) { + crane1.Stop(nil) + crane2.Stop(nil) +} + +// BenchmarkCraneThroughput pumps terminal messages through a crane pair over +// the in-memory test ship. It measures the crane loader (framing, padding, +// encryption), the unloader and the handler (segment parsing, delivery). +func BenchmarkCraneThroughput(b *testing.B) { + for _, encrypt := range []bool{false, true} { + for _, size := range []int{100, 1400} { + b.Run(fmt.Sprintf("encrypt=%v/size=%d", encrypt, size), func(b *testing.B) { + crane1, crane2 := startBenchCranes(b, encrypt) + defer stopBenchCranes(crane1, crane2) + + sink := &benchSinkTerminal{ + id: 8, + crane: crane2, + remaining: b.N, + done: make(chan struct{}), + } + crane2.setTerminal(sink) + + payload := make([]byte, size) + for i := range payload { + payload[i] = byte(i) + } + + b.SetBytes(int64(size)) + b.ReportAllocs() + b.ResetTimer() + + for range b.N { + msg := terminal.NewMsg(payload) + msg.FlowID = sink.id + tErr := crane1.Send(msg, 3*time.Second) + if tErr != nil { + b.Fatal(tErr) + } + } + + select { + case <-sink.done: + case <-time.After(60 * time.Second): + b.Fatal("timed out waiting for sink") + } + b.StopTimer() + }) + } + } +} + +// BenchmarkCraneTerminalThroughput pumps operation messages through a crane +// terminal pair (home hub options, with flow control) on top of a crane pair +// over the in-memory test ship. This is the full per message path of the SPN +// stack below the operations. +func BenchmarkCraneTerminalThroughput(b *testing.B) { + for _, encrypt := range []bool{false, true} { + for _, size := range []int{100, 1400} { + b.Run(fmt.Sprintf("encrypt=%v/size=%d", encrypt, size), func(b *testing.B) { + crane1, crane2 := startBenchCranes(b, encrypt) + defer stopBenchCranes(crane1, crane2) + + // Establish crane terminal pair. + localTerm, initData, tErr := NewLocalCraneTerminal(crane1, nil, terminal.DefaultHomeHubTerminalOpts()) + if tErr != nil { + b.Fatal(tErr) + } + tErr = crane1.EstablishNewTerminal(localTerm, initData) + if tErr != nil { + b.Fatal(tErr) + } + + payload := make([]byte, size) + for i := range payload { + payload[i] = byte(i) + } + + b.SetBytes(int64(size)) + b.ReportAllocs() + b.ResetTimer() + + // Start sink on the other side. + src := &benchSourceOp{} + msgCount := uint64(b.N) //nolint:gosec // b.N is positive. + tErr = localTerm.StartOperation(src, container.New(varint.Pack64(msgCount)), 3*time.Second) + if tErr != nil { + b.Fatal(tErr) + } + done := <-benchSinkDone + + for range b.N { + tErr = src.Send(src.NewMsg(payload), 3*time.Second) + if tErr != nil { + b.Fatal(tErr) + } + } + localTerm.Flush(10 * time.Second) + + select { + case <-done: + case <-time.After(60 * time.Second): + b.Fatal("timed out waiting for sink") + } + b.StopTimer() + }) + } + } +} diff --git a/spn/docks/crane_init.go b/spn/docks/crane_init.go index 3648913c8..de64d31ed 100644 --- a/spn/docks/crane_init.go +++ b/spn/docks/crane_init.go @@ -104,11 +104,11 @@ func (crane *Crane) startLocal(callerCtx context.Context) *terminal.Error { } // Parse and import Announcement and Status. - announcementData, err := reply.GetNextBlock() + announcementData, err := terminal.GetNextBlock(reply) if err != nil { return terminal.ErrMalformedData.With("failed to get announcement: %w", err) } - statusData, err := reply.GetNextBlock() + statusData, err := terminal.GetNextBlock(reply) if err != nil { return terminal.ErrMalformedData.With("failed to get status: %w", err) } @@ -244,7 +244,7 @@ handling: } // Set up encryption. - letter, err := jess.LetterFromWire(container.New(request.CompileData())) + letter, err := terminal.LetterFromWire(container.New(request.CompileData())) if err != nil { return terminal.ErrMalformedData.With("failed to unpack initial packet: %w", err) } diff --git a/spn/docks/crane_letter_test.go b/spn/docks/crane_letter_test.go new file mode 100644 index 000000000..75cd2d00b --- /dev/null +++ b/spn/docks/crane_letter_test.go @@ -0,0 +1,28 @@ +package docks + +import ( + "errors" + "testing" + + "github.com/safing/jess" + "github.com/safing/portmaster/spn/terminal" + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// TestCraneDecryptLetterWithHugeBlockSize checks that a crane does not +// allocate the block size of a received letter, which is parsed before the +// letter is authenticated. With jess.LetterFromWire, this test crashed with +// "fatal error: runtime: out of memory". +func TestCraneDecryptLetterWithHugeBlockSize(t *testing.T) { + t.Parallel() + + // The session is not used, as parsing the letter fails. + crane := &Crane{jession: &jess.Session{}} + // Data message with a nonce of 4TB. + data := append([]byte{1, 0}, varint.Pack64(1<<42)...) + _, err := crane.decrypt(container.New(data)) + if !errors.Is(err, terminal.ErrBlockTooBig) { + t.Errorf("expected ErrBlockTooBig, got %v", err) + } +} diff --git a/spn/docks/crane_load_test.go b/spn/docks/crane_load_test.go new file mode 100644 index 000000000..292191c59 --- /dev/null +++ b/spn/docks/crane_load_test.go @@ -0,0 +1,129 @@ +package docks + +import ( + "bytes" + "testing" + "time" + + "github.com/safing/portmaster/spn/ships" + "github.com/safing/portmaster/spn/terminal" + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// TestCraneLoaderFraming checks that the loader produces the same byte stream +// as packing every message with terminal.MakeMsg and splitting the result +// into shipments of at most the target load size. +func TestCraneLoaderFraming(t *testing.T) { //nolint:paralleltest // Modifies the global optimalMinLoadSize. + optimalMinLoadSize = 3072 + ship := ships.NewTestShip(true, ships.BaseMTU) + crane, err := NewCrane(ship, nil, nil) + if err != nil { + t.Fatal(err) + } + defer unregisterCrane(crane) + reverse := ship.Reverse() + + // Send messages of different sizes, so that shipments are split. + sizes := []int{1, 100, 1400, 127, 128, 5000, 16000, 3, 1400, 1400, 1400, 300} + expected := container.New() + var expectedLen int + for i, size := range sizes { + data := bytes.Repeat([]byte{byte(i + 1)}, size) + + msg := terminal.NewMsg(data) + msg.FlowID = uint32(8 + 4*i) + msg.Type = terminal.MsgTypeData + crane.terminalMsgs <- msg + + c := container.New(data) + terminal.MakeMsg(c, uint32(8+4*i), terminal.MsgTypeData) + expectedLen += c.Length() + expected.AppendContainer(c) + } + expectedData := expected.CompileData() + + // Start loader. + loaderDone := make(chan struct{}) + go func() { + defer close(loaderDone) + _ = crane.loader(nil) + }() + + // Receive shipments until all data is received. + var received []byte + buf := make([]byte, 100000) + for len(received) < expectedLen { + n, err := reverse.UnloadTo(buf) + if err != nil { + t.Fatal(err) + } + shipmentLen, lenSize, err := varint.Unpack64(buf[:n]) + if err != nil { + t.Fatal(err) + } + if shipmentLen != uint64(n-lenSize) { //nolint:gosec // Not negative. + t.Fatalf("shipment length %d does not match received data %d", shipmentLen, n-lenSize) + } + if shipmentLen > uint64(crane.targetLoadSize) { //nolint:gosec // Not negative. + t.Fatalf("shipment length %d exceeds target load size %d", shipmentLen, crane.targetLoadSize) + } + received = append(received, buf[lenSize:n]...) + } + + if !bytes.Equal(received, expectedData) { + t.Fatal("loaded data does not match expected framing") + } + + crane.cancelCtx() + select { + case <-loaderDone: + case <-time.After(5 * time.Second): + t.Fatal("loader did not stop") + } +} + +// TestCraneLoadPadding checks the padding and length prefix of loaded shipments. +func TestCraneLoadPadding(t *testing.T) { //nolint:paralleltest // Modifies the global optimalMinLoadSize. + optimalMinLoadSize = 3072 + ship := ships.NewTestShip(true, ships.BaseMTU) + crane, err := NewCrane(ship, nil, nil) + if err != nil { + t.Fatal(err) + } + defer unregisterCrane(crane) + crane.opts.Padding = 64 + reverse := ship.Reverse() + + buf := make([]byte, 100000) + for _, size := range []int{1, 63, 64, 100, 126, 127, 1000, crane.targetLoadSize - 10, crane.targetLoadSize} { + data := bytes.Repeat([]byte{0xAA}, size) + err := crane.load(data) + if err != nil { + t.Fatal(err) + } + n, err := reverse.UnloadTo(buf) + if err != nil { + t.Fatal(err) + } + + // Calculate expected padding. + paddingNeeded := 64 - ((size + varint.EncodedSize(uint64(size))) % 64) //nolint:gosec // Not negative. + paddingNeeded = min(paddingNeeded, crane.targetLoadSize-size) + + shipmentLen, lenSize, err := varint.Unpack64(buf[:n]) + if err != nil { + t.Fatal(err) + } + if shipmentLen != uint64(size+paddingNeeded) || shipmentLen != uint64(n-lenSize) { //nolint:gosec // Not negative. + t.Fatalf("size %d: unexpected shipment length %d (received %d), expected %d", size, shipmentLen, n-lenSize, size+paddingNeeded) + } + shipment := buf[lenSize:n] + if !bytes.Equal(shipment[:size], data) { + t.Fatalf("size %d: data mismatch", size) + } + if paddingNeeded > 0 && shipment[size] != 0 { + t.Fatalf("size %d: missing padding indicator", size) + } + } +} diff --git a/spn/docks/crane_test.go b/spn/docks/crane_test.go index 90b3a93ee..4de4dd0b6 100644 --- a/spn/docks/crane_test.go +++ b/spn/docks/crane_test.go @@ -17,8 +17,7 @@ import ( "github.com/safing/portmaster/spn/terminal" ) -func TestCraneCommunication(t *testing.T) { - t.Parallel() +func TestCraneCommunication(t *testing.T) { //nolint:paralleltest // Modifies the global optimalMinLoadSize. testCraneWithCounter(t, "plain-counter-load-100", false, 100, 1000) testCraneWithCounter(t, "plain-counter-load-1000", false, 1000, 1000) diff --git a/spn/docks/op_capacity.go b/spn/docks/op_capacity.go index 86f38eb36..a5d2eca8f 100644 --- a/spn/docks/op_capacity.go +++ b/spn/docks/op_capacity.go @@ -9,6 +9,7 @@ import ( "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/mgr" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/portmaster/spn/terminal" "github.com/safing/structures/container" "github.com/safing/structures/dsd" @@ -37,7 +38,7 @@ var ( ) // CapacityTestOp is used for capacity test operations. -type CapacityTestOp struct { //nolint:maligned +type CapacityTestOp struct { terminal.OperationBase opts *CapacityTestOptions @@ -55,6 +56,9 @@ type CapacityTestOp struct { //nolint:maligned testResult int result chan *terminal.Error + + // stopping is closed when the operation is stopped, from any side. + stopping chan struct{} } // CapacityTestOptions holds options for the capacity test. @@ -99,6 +103,7 @@ func NewCapacityTestOp(t terminal.Terminal, opts *CapacityTestOptions) (*Capacit dataSent: new(int64), dataSentWasAckd: abool.New(), result: make(chan *terminal.Error, 1), + stopping: make(chan struct{}), } // Make capacity test request. @@ -129,7 +134,7 @@ func startCapacityTestOp(t terminal.Terminal, opID uint32, data *container.Conta // Parse options. opts := &CapacityTestOptions{} - _, err := dsd.Load(data.CompileData(), opts) + _, err := peerdsd.Load(data.CompileData(), opts) if err != nil { capacityTestRunning.UnSet() return nil, terminal.ErrMalformedData.With("failed to parse options: %w", err) @@ -152,6 +157,7 @@ func startCapacityTestOp(t terminal.Terminal, opID uint32, data *container.Conta dataSent: new(int64), dataSentWasAckd: abool.New(), result: make(chan *terminal.Error, 1), + stopping: make(chan struct{}), } op.InitOperationBase(t, opID) @@ -177,7 +183,7 @@ func (op *CapacityTestOp) handler(ctx *mgr.WorkerCtx) error { // Setup unit handling var msg *terminal.Msg - defer msg.Finish() + defer func() { msg.Finish() }() // Handle receives. for { @@ -188,6 +194,10 @@ func (op *CapacityTestOp) handler(ctx *mgr.WorkerCtx) error { returnErr = terminal.ErrCanceled return nil + case <-op.stopping: + // The operation was stopped, eg. by the remote side. + return nil + case <-opTimeout: returnErr = terminal.ErrTimeout return nil @@ -323,6 +333,9 @@ func (op *CapacityTestOp) Deliver(msg *terminal.Msg) *terminal.Error { // The returned error is the error to send to the other side. // Should never be called directly. Call Stop() instead. func (op *CapacityTestOp) HandleStop(tErr *terminal.Error) (errorToSend *terminal.Error) { + // Signal the handler to end. HandleStop is only called once. + close(op.stopping) + // Return result to waiting routine. select { case op.result <- tErr: diff --git a/spn/docks/op_capacity_test.go b/spn/docks/op_capacity_test.go index 1d7e442fe..7496b40ed 100644 --- a/spn/docks/op_capacity_test.go +++ b/spn/docks/op_capacity_test.go @@ -83,3 +83,64 @@ func testCapacityOp(t *testing.T, opts *CapacityTestOptions) { t.Fatal("measured capacity too low") } } + +// TestCapacityOpRemoteStop checks that the capacity test operations end +// promptly when the remote side stops, instead of running until their own +// timeouts. +func TestCapacityOpRemoteStop(t *testing.T) { //nolint:paralleltest // Uses the global capacity test lock. + // Create test terminal pair. + a, b, err := terminal.NewSimpleTestTerminalPair( + 5*time.Millisecond, + 10, + &terminal.TerminalOpts{ + FlowControl: terminal.FlowControlDFQ, + FlowControlSize: 10, + }, + ) + if err != nil { + t.Fatalf("failed to create test terminal pair: %s", err) + } + defer a.Abandon(nil) + + // Start a test that would run for a long time. + b.GrantPermission(terminal.IsCraneController) + op, tErr := NewCapacityTestOp(a, &CapacityTestOptions{ + TestVolume: maxCapacityTestVolume, + MaxTime: maxCapacityTestMaxTime, + testing: true, + }) + if tErr != nil { + t.Fatalf("failed to start op: %s", tErr) + } + + // Wait for the test to be running on both sides. + time.Sleep(500 * time.Millisecond) + if n := countGoroutinesIn(t, "(*CapacityTestOp).handler"); n != 2 { + t.Fatalf("expected 2 running capacity op handlers, found %d", n) + } + + // Stop the test from the remote side by abandoning the remote terminal. + b.Abandon(nil) + select { + case tErr = <-op.Result(): + t.Logf("op ended with: %s", tErr) + case <-time.After(5 * time.Second): + t.Fatal("op did not end after remote stop") + } + + // All handlers and senders must end promptly. + started := time.Now() + waitUntil := started.Add(5 * time.Second) + for countGoroutinesIn(t, "(*CapacityTestOp).handler")+countGoroutinesIn(t, "(*CapacityTestOp).sender") > 0 { + if time.Now().After(waitUntil) { + t.Fatalf("capacity op workers still running %s after remote stop", time.Since(started)) + } + time.Sleep(10 * time.Millisecond) + } + t.Logf("capacity op workers ended %s after remote stop", time.Since(started)) + + // The global capacity test lock must be released. + if capacityTestRunning.IsSet() { + t.Fatal("capacity test lock still set after all workers ended") + } +} diff --git a/spn/docks/op_compressed_test.go b/spn/docks/op_compressed_test.go new file mode 100644 index 000000000..8fd553625 --- /dev/null +++ b/spn/docks/op_compressed_test.go @@ -0,0 +1,41 @@ +package docks + +import ( + "errors" + "testing" + + "github.com/safing/portmaster/spn/terminal" + "github.com/safing/structures/container" + "github.com/safing/structures/dsd" +) + +// TestWhoAmIRejectsCompressed checks that a gzip compressed whoami response +// is rejected before decompression. dsd.Load decompresses it into an +// unbounded buffer, so a 16KB message could make the receiver allocate about +// 64MB. +func TestWhoAmIRejectsCompressed(t *testing.T) { + t.Parallel() + + data, err := dsd.DumpAndCompress(&WhoAmIResponse{Addr: "1.2.3.4:5"}, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + op := &WhoAmIOp{} + tErr := op.Deliver(terminal.NewMsg(data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("expected ErrIncompatibleFormat, got %v", tErr) + } +} + +// TestCapacityOpRejectsCompressed checks that gzip compressed capacity test +// options are rejected before decompression. +func TestCapacityOpRejectsCompressed(t *testing.T) { //nolint:paralleltest // Uses the global capacity test lock. + data, err := dsd.DumpAndCompress(&CapacityTestOptions{TestVolume: maxCapacityTestVolume + 1}, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, tErr := startCapacityTestOp(nil, 1, container.New(data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("expected ErrIncompatibleFormat, got %v", tErr) + } +} diff --git a/spn/docks/op_expand.go b/spn/docks/op_expand.go index 1c01ad544..3c2502646 100644 --- a/spn/docks/op_expand.go +++ b/spn/docks/op_expand.go @@ -127,7 +127,7 @@ func expand(t terminal.Terminal, opID uint32, data *container.Container) (termin } // Parse destination hub ID. - dstData, err := data.GetNextBlock() + dstData, err := terminal.GetNextBlock(data) if err != nil { return nil, terminal.ErrMalformedData.With("failed to parse destination: %w", err) } diff --git a/spn/docks/op_sync_state.go b/spn/docks/op_sync_state.go index ff1d8e730..4b0cab048 100644 --- a/spn/docks/op_sync_state.go +++ b/spn/docks/op_sync_state.go @@ -6,6 +6,7 @@ import ( "github.com/safing/portmaster/service/mgr" "github.com/safing/portmaster/spn/conf" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/portmaster/spn/terminal" "github.com/safing/structures/container" "github.com/safing/structures/dsd" @@ -115,7 +116,7 @@ func runSyncStateOp(t terminal.Terminal, opID uint32, data *container.Container) // Load message. syncState := &SyncStateMessage{} - _, err := dsd.Load(data.CompileData(), syncState) + _, err := peerdsd.Load(data.CompileData(), syncState) if err != nil { return nil, terminal.ErrMalformedData.With("failed to load sync state message: %w", err) } diff --git a/spn/docks/op_whoami.go b/spn/docks/op_whoami.go index 664f85a55..c0d8fa1c2 100644 --- a/spn/docks/op_whoami.go +++ b/spn/docks/op_whoami.go @@ -3,6 +3,7 @@ package docks import ( "time" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/portmaster/spn/terminal" "github.com/safing/structures/container" "github.com/safing/structures/dsd" @@ -83,7 +84,7 @@ func (op *WhoAmIOp) Deliver(msg *terminal.Msg) *terminal.Error { // Parse response. response := &WhoAmIResponse{} - _, err := dsd.Load(msg.Data.CompileData(), response) + _, err := peerdsd.Load(msg.Data.CompileData(), response) if err != nil { return terminal.ErrMalformedData.With("failed to parse ping response: %w", err) } diff --git a/spn/docks/terminal_expansion.go b/spn/docks/terminal_expansion.go index 31ba0480a..b306ebe32 100644 --- a/spn/docks/terminal_expansion.go +++ b/spn/docks/terminal_expansion.go @@ -67,6 +67,13 @@ func ExpandTo(from terminal.Terminal, routeTo string, encryptFor *hub.Hub) (*Exp base.SetTerminalExtension(expansion) base.SetTimeout(defaultTerminalIdleTimeout) + // Start Workers. + // Do this before starting the relay operation: If starting it fails, the + // relay operation is stopped, which abandons the expansion terminal. The + // abandon procedure needs the workers to flush and finish, otherwise it + // would only end after its flush timeouts (5 minutes each). + base.StartWorkers(module.mgr, "expansion terminal") + // Second, start the actual relay operation. // Create setup message for relay operation. @@ -80,9 +87,6 @@ func ExpandTo(from terminal.Terminal, routeTo string, encryptFor *hub.Hub) (*Exp return nil, tErr.Wrap("failed to start expansion operation") } - // Start Workers. - base.StartWorkers(module.mgr, "expansion terminal") - return expansion, nil } diff --git a/spn/docks/terminal_expansion_fail_test.go b/spn/docks/terminal_expansion_fail_test.go new file mode 100644 index 000000000..4daf3e7f1 --- /dev/null +++ b/spn/docks/terminal_expansion_fail_test.go @@ -0,0 +1,83 @@ +package docks + +import ( + "bytes" + "runtime/pprof" + "strings" + "testing" + "time" + + "github.com/safing/portmaster/spn/terminal" +) + +// countGoroutinesIn returns the number of goroutines that are currently in +// the given function. +func countGoroutinesIn(t *testing.T, function string) int { + t.Helper() + + var buf bytes.Buffer + err := pprof.Lookup("goroutine").WriteTo(&buf, 2) + if err != nil { + t.Fatalf("failed to get goroutine dump: %s", err) + } + return strings.Count(buf.String(), function+"(") +} + +// abandonProceduresRunning returns the number of goroutines currently running +// a terminal abandon procedure. +func abandonProceduresRunning(t *testing.T) int { + t.Helper() + + return countGoroutinesIn(t, "(*TerminalBase).handleAbandonProcedure") +} + +// TestExpandToFailureCleansUpPromptly checks that a failed ExpandTo does not +// leave the half-built expansion terminal lingering in its abandon procedure. +func TestExpandToFailureCleansUpPromptly(t *testing.T) { //nolint:paralleltest // Inspects all goroutines. + // Create a terminal to expand from and shut it down, so that starting the + // expand operation on it fails. + from, _, tErr := terminal.NewLocalTestTerminal( + module.mgr.Ctx(), 1, "expand-fail-test", nil, + terminal.DefaultExpansionTerminalOpts(), + terminal.UpstreamSendFunc(func(msg *terminal.Msg, _ time.Duration) *terminal.Error { + msg.Finish() + return nil + }), + ) + if tErr != nil { + t.Fatalf("failed to create test terminal: %s", tErr) + } + from.Abandon(nil) + select { + case <-from.Ctx().Done(): + case <-time.After(10 * time.Second): + t.Fatal("test terminal did not shut down") + } + // Wait for the abandon procedure of the test terminal to finish. + waitUntil := time.Now().Add(10 * time.Second) + for abandonProceduresRunning(t) > 0 { + if time.Now().After(waitUntil) { + t.Fatal("abandon procedure of test terminal did not finish") + } + time.Sleep(10 * time.Millisecond) + } + + // Expanding must fail. + expansion, tErr := ExpandTo(from, "expand-fail-test-dst", nil) + if tErr == nil { + expansion.Abandon(nil) + t.Fatal("expanding via a stopped terminal should fail") + } + + // The half-built expansion terminal must be cleaned up promptly. + started := time.Now() + waitUntil = started.Add(10 * time.Second) + time.Sleep(10 * time.Millisecond) // Give the abandon procedure time to start. + for abandonProceduresRunning(t) > 0 { + if time.Now().After(waitUntil) { + t.Fatalf("abandon procedure of failed expansion terminal still running after %s", time.Since(started)) + } + time.Sleep(10 * time.Millisecond) + } + t.Logf("failed expansion terminal cleaned up after %s", time.Since(started)) +} diff --git a/spn/docks/terminal_expansion_test.go b/spn/docks/terminal_expansion_test.go index 4d9029de4..db12b5cf2 100644 --- a/spn/docks/terminal_expansion_test.go +++ b/spn/docks/terminal_expansion_test.go @@ -18,8 +18,8 @@ import ( const defaultTestQueueSize = 200 -func TestExpansion(t *testing.T) { - t.Parallel() +func TestExpansion(t *testing.T) { //nolint:paralleltest // Modifies the global optimalMinLoadSize. + t.Skip("SPN access tokens have been removed from portmasterpro; terminal expansion cannot authorize") // Test without and with encryption. for _, encrypt := range []bool{false, true} { diff --git a/spn/hub/database.go b/spn/hub/database.go index c4b114709..73b161231 100644 --- a/spn/hub/database.go +++ b/spn/hub/database.go @@ -146,7 +146,7 @@ func RemoveHubAndMsgs(mapName string, hubID string) (err error) { } // HubMsg stores raw Hub messages. -type HubMsg struct { //nolint:golint +type HubMsg struct { record.Base sync.Mutex diff --git a/spn/hub/hub.go b/spn/hub/hub.go index 6817ce2c0..512743e8b 100644 --- a/spn/hub/hub.go +++ b/spn/hub/hub.go @@ -46,7 +46,7 @@ const ( ) // Hub represents a network node in the SPN. -type Hub struct { //nolint:maligned +type Hub struct { sync.Mutex record.Base @@ -220,8 +220,9 @@ func (h *Hub) getName() string { h.ID[len(h.ID)-4:] // Be more careful, as the Hub name is user input. + // Info is nil for Hubs whose first announcement has not been accepted (yet). switch { - case h.Info.Name == "": + case h.Info == nil || h.Info.Name == "": return shortenedID case len(h.Info.Name) > 16: return h.Info.Name[:16] + " " + shortenedID diff --git a/spn/hub/hubid_test.go b/spn/hub/hubid_test.go new file mode 100644 index 000000000..99abcfba7 --- /dev/null +++ b/spn/hub/hubid_test.go @@ -0,0 +1,102 @@ +package hub + +import ( + "errors" + "strings" + "testing" + + "github.com/mr-tron/base58" + + "github.com/safing/jess" + "github.com/safing/jess/lhash" + "github.com/safing/structures/dsd" + "github.com/safing/structures/varint" +) + +// hugeLengthHubID is a short base58 string that decodes to a labeled hash +// claiming a digest of about 2.9 TB. Found by FuzzParseTransport. +const hugeLengthHubID = "wns3eWStj" + +// TestHubIDWithHugeDigestLength checks that Hub IDs that announce a huge +// digest length are rejected without allocating that length. +func TestHubIDWithHugeDigestLength(t *testing.T) { + t.Parallel() + + // Hub ID check, as done in OpenHubMsg. + if verifyHubID(hugeLengthHubID, "Ed25519", []byte{1}) { + t.Fatal("invalid hub ID verified") + } + maxLength := base58.Encode(append(varint.Pack64(16), varint.Pack64(1<<63)...)) + if verifyHubID(maxLength, "Ed25519", []byte{1}) { + t.Fatal("invalid hub ID verified") + } + + // Bootstrap hub parsing. + _, _, _, err := ParseBootstrapHub("tcp://1.2.3.4:17#" + hugeLengthHubID) //nolint:dogsled + if err == nil { + t.Fatal("invalid bootstrap hub ID accepted") + } + + // Full hub msg with the ID set as signer, as received from the network. + letter := &jess.Letter{ + Version: 1, + SuiteID: jess.SuiteSignV1, + Data: []byte("{}"), + Keys: []*jess.Seal{{Value: []byte{1}}}, + Signatures: []*jess.Seal{{ID: hugeLengthHubID, Scheme: "Ed25519", Value: []byte{1}}}, + } + data, err := letter.ToDSD(dsd.JSON) + if err != nil { + t.Fatal(err) + } + _, _, _, err = OpenHubMsg(nil, data, "test-huge-id", true) //nolint:dogsled + if err == nil { + t.Fatal("hub msg with invalid hub ID accepted") + } + + // Valid IDs must still work. + _, public, err := CreateHubSignet("Ed25519", 0) + if err != nil { + t.Fatal(err) + } + if !verifyHubID(public.ID, public.Scheme, public.Key) { + t.Fatal("valid hub ID not verified") + } + _, id, _, err := ParseBootstrapHub("tcp://1.2.3.4:17#" + public.ID) + if err != nil || id != public.ID { + t.Fatalf("valid bootstrap hub rejected: %s", err) + } +} + +// TestLabeledHashFromBase58LimitsLength checks that overlong IDs are rejected +// before they are decoded, as decoding base58 takes quadratic time. +func TestLabeledHashFromBase58LimitsLength(t *testing.T) { + t.Parallel() + + _, err := labeledHashFromBase58(strings.Repeat("z", maxEncodedLabeledHashLength+1)) + if !errors.Is(err, errLabeledHashTooLong) { + t.Errorf("expected errLabeledHashTooLong, got %v", err) + } + if verifyHubID(strings.Repeat("z", 16000), "Ed25519", []byte{1}) { + t.Error("overlong hub ID verified") + } + + // The biggest digests are within the limit. + for _, alg := range []lhash.Algorithm{lhash.SHA2_512, lhash.SHA3_512, lhash.BLAKE2b_512, lhash.BLAKE2b_256} { + encoded := lhash.Digest(alg, []byte("data")).Base58() + if len(encoded) > 91 { + t.Errorf("unexpected encoded length %d", len(encoded)) + } + _, err := labeledHashFromBase58(encoded) + if err != nil { + t.Errorf("failed to load %s: %s", alg, err) + } + } +} + +func BenchmarkVerifyHubIDOverlong(b *testing.B) { + id := strings.Repeat("z", 16000) + for range b.N { + verifyHubID(id, "Ed25519", make([]byte, 32)) + } +} diff --git a/spn/hub/intel.go b/spn/hub/intel.go index 8bc505ed2..b9fa6d5ed 100644 --- a/spn/hub/intel.go +++ b/spn/hub/intel.go @@ -7,7 +7,6 @@ import ( "github.com/ghodss/yaml" - "github.com/safing/jess/lhash" "github.com/safing/portmaster/service/profile/endpoints" ) @@ -45,7 +44,7 @@ type Intel struct { } // HubIntel holds Hub-related data. -type HubIntel struct { //nolint:golint +type HubIntel struct { // Trusted specifies if the Hub is specially designated for more sensitive tasks, such as handling unencrypted traffic. Trusted bool @@ -172,7 +171,8 @@ func ParseBootstrapHub(bootstrapTransport string) (t *Transport, hubID string, h if t.Option == "" { return nil, "", nil, errors.New("missing hub ID in URL fragment") } - if _, err := lhash.FromBase58(t.Option); err != nil { + _, err = labeledHashFromBase58(t.Option) + if err != nil { return nil, "", nil, fmt.Errorf("hub ID is invalid: %w", err) } diff --git a/spn/hub/msg_fuzz_test.go b/spn/hub/msg_fuzz_test.go new file mode 100644 index 000000000..e044312d0 --- /dev/null +++ b/spn/hub/msg_fuzz_test.go @@ -0,0 +1,102 @@ +package hub + +import ( + "testing" + "time" + + "github.com/safing/structures/dsd" +) + +func FuzzOpenHubMsg(f *testing.F) { + env, hubID := newTestHubEnvelope(f) + a := &Announcement{ + ID: hubID, + Timestamp: time.Now().Unix(), + Name: "fuzz", + Transports: []string{"tcp:717"}, + } + data, err := a.Export(env) + if err != nil { + f.Fatal(err) + } + f.Add(data) + s := &Status{ + Timestamp: time.Now().Unix(), + Version: "1.0.0", + Lanes: []*Lane{{ID: hubID, Capacity: 1, Latency: 1}}, + } + data, err = s.Export(env) + if err != nil { + f.Fatal(err) + } + f.Add(data) + f.Add([]byte(`J{"Signatures":[{"ID":"x"}]}`)) + + f.Fuzz(func(t *testing.T, data []byte) { + _, _, _, _ = OpenHubMsg(nil, data, "fuzz-open", true) //nolint:dogsled + _, _, _, _ = OpenHubMsg(nil, data, "fuzz-open", false) //nolint:dogsled + }) +} + +// FuzzValidateHubMsgs fuzzes the validation of decoded (and already +// signature-verified) announcement and status message payloads. +func FuzzValidateHubMsgs(f *testing.F) { + a := &Announcement{ + ID: "Zwu5LtU3DLjoV1KNg5Vzwns3eWStB1hjUQuCQNP5bWVQmA", + Timestamp: time.Now().Unix(), + Name: "fuzz", + Group: "group", + Hosters: []string{"hoster"}, + IPv4: []byte{1, 1, 1, 1}, + Transports: []string{"tcp://example.com:17", "http://example.com:80/spn"}, + Entry: []string{"+ *"}, + Exit: []string{"- * TCP/25", "- US"}, + Flags: []string{"flag"}, + } + data, err := dsd.Dump(a, dsd.JSON) + if err != nil { + f.Fatal(err) + } + f.Add(data) + s := &Status{ + Timestamp: time.Now().Unix(), + Version: "1.0.0", + Keys: map[string]*Key{"key": {Scheme: "ECDH-X25519", Key: []byte{1, 2, 3}, Expires: 1}}, + Lanes: []*Lane{{ID: "lane", Capacity: 1, Latency: 1}}, + Load: 10, + Flags: []string{FlagNetError}, + } + data, err = dsd.Dump(s, dsd.JSON) + if err != nil { + f.Fatal(err) + } + f.Add(data) + + f.Fuzz(func(t *testing.T, data []byte) { + announcement := &Announcement{} + _, err := dsd.Load(data, announcement) + if err == nil { + h := &Hub{ID: announcement.ID, Info: a} + for _, scope := range []Scope{ScopePublic, ScopeLocal, ScopeTest} { + _ = h.validateAnnouncement(announcement, scope) + } + h.Info = nil + _ = h.validateAnnouncement(announcement, ScopePublic) + _ = h.getName() + } + + status := &Status{} + _, err = dsd.Load(data, status) + if err == nil { + h := &Hub{ID: "Zwu5LtU3DLjoV1KNg5Vzwns3eWStB1hjUQuCQNP5bWVQmA"} + err = h.validateStatus(status) + if err == nil { + h.Status = status + _ = h.SelectSignet() + _ = h.GetLaneTo("lane") + _ = h.HasFlag(FlagOffline) + _ = h.Obsolete() + } + } + }) +} diff --git a/spn/hub/status.go b/spn/hub/status.go index 0d5c48085..a734a4685 100644 --- a/spn/hub/status.go +++ b/spn/hub/status.go @@ -210,6 +210,8 @@ func (l *Lane) Equal(other *Lane) bool { return true } +var errEmptyEntry = errors.New("empty entry") + // validateFormatting check if all values conform to the basic format. func (s *Status) validateFormatting() error { // public keys @@ -220,6 +222,9 @@ func (s *Status) validateFormatting() error { if err := checkStringFormat("Keys#ID", keyID, 255); err != nil { return err } + if key == nil { + return fmt.Errorf("field Keys: %w for %q", errEmptyEntry, keyID) + } if err := checkStringFormat("Keys.Scheme", key.Scheme, 255); err != nil { return err } @@ -233,6 +238,9 @@ func (s *Status) validateFormatting() error { return fmt.Errorf("field Lanes with array/slice length of %d exceeds max length of %d", len(s.Lanes), 255) } for _, lanes := range s.Lanes { + if lanes == nil { + return fmt.Errorf("field Lanes: %w", errEmptyEntry) + } if err := checkStringFormat("Lanes.ID", lanes.ID, 255); err != nil { return err } diff --git a/spn/hub/status_nil_test.go b/spn/hub/status_nil_test.go new file mode 100644 index 000000000..7fda93bc6 --- /dev/null +++ b/spn/hub/status_nil_test.go @@ -0,0 +1,48 @@ +package hub + +import ( + "testing" + "time" +) + +// TestApplyStatusWithNilEntries checks that a status with null entries in its +// keys or lanes is rejected with an error instead of a panic. +func TestApplyStatusWithNilEntries(t *testing.T) { + t.Parallel() + + env, hubID := newTestHubEnvelope(t) + a := &Announcement{ + ID: hubID, + Timestamp: time.Now().Unix(), + Name: "test", + Transports: []string{"tcp:17"}, + } + data, err := a.Export(env) + if err != nil { + t.Fatal(err) + } + h, _, _, err := ApplyAnnouncement(nil, data, "test-nil-entries", ScopeTest, false) + if err != nil { + t.Fatal(err) + } + + for i, s := range []*Status{ + {Timestamp: time.Now().Unix() + 1, Keys: map[string]*Key{"key": nil}}, + {Timestamp: time.Now().Unix() + 2, Lanes: []*Lane{nil}}, + } { + data, err := s.Export(env) + if err != nil { + t.Fatal(err) + } + _, _, _, err = ApplyStatus(h, data, "test-nil-entries", ScopeTest, false) + if err == nil { + t.Fatalf("status %d with nil entry was accepted", i) + } + if !h.InvalidStatus { + t.Fatalf("status %d with nil entry was not marked invalid", i) + } + if h.Status != nil { + t.Fatalf("status %d with nil entry was saved", i) + } + } +} diff --git a/spn/hub/testdata/fuzz/FuzzOpenHubMsg/nil_signature b/spn/hub/testdata/fuzz/FuzzOpenHubMsg/nil_signature new file mode 100644 index 000000000..9f28e6db9 --- /dev/null +++ b/spn/hub/testdata/fuzz/FuzzOpenHubMsg/nil_signature @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("J{\"Signatures\":[null]}") diff --git a/spn/hub/testdata/fuzz/FuzzOpenHubMsg/nil_tofu_key b/spn/hub/testdata/fuzz/FuzzOpenHubMsg/nil_tofu_key new file mode 100644 index 000000000..30ab0cfb7 --- /dev/null +++ b/spn/hub/testdata/fuzz/FuzzOpenHubMsg/nil_tofu_key @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("J{\"Signatures\":[{\"ID\":\"x\"}],\"Keys\":[null]}") diff --git a/spn/hub/testdata/fuzz/FuzzParseTransport/c2d07ff165cf1d4b b/spn/hub/testdata/fuzz/FuzzParseTransport/c2d07ff165cf1d4b new file mode 100644 index 000000000..c9c33e47f --- /dev/null +++ b/spn/hub/testdata/fuzz/FuzzParseTransport/c2d07ff165cf1d4b @@ -0,0 +1,2 @@ +go test fuzz v1 +string("p:7#wns3eWStj") diff --git a/spn/hub/transport_fuzz_test.go b/spn/hub/transport_fuzz_test.go new file mode 100644 index 000000000..ed7bcef16 --- /dev/null +++ b/spn/hub/transport_fuzz_test.go @@ -0,0 +1,39 @@ +package hub + +import ( + "testing" +) + +func FuzzParseTransport(f *testing.F) { + for _, seed := range []string{ + "spn:17", + "smtp:25", + "smtp://:25", + "http:80", + "http://example.com:80/example", + "https:443", + "wss://example.com:443/spn", + "tcp://1.2.3.4:17#Zwu5LtU3DLjoV1KNg5Vzwns3eWStB1hjUQuCQNP5bWVQmA", + "tcp://[2001:db8::1]:17/path?q=1#option", + "spn:17/", + "spn:0", + "spn:65536", + "spn://user:pass@example.com:17", + } { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, definition string) { + _, _, _, _ = ParseBootstrapHub(definition) //nolint:dogsled + ParseTransports([]string{definition, definition}) + + tr, err := ParseTransport(definition) + if err != nil { + return + } + if tr.Port == 0 || tr.Protocol == "" { + t.Fatalf("accepted transport without port or protocol: %+v", tr) + } + _ = tr.String() + }) +} diff --git a/spn/hub/update.go b/spn/hub/update.go index f77dbbfd4..68c9de9a8 100644 --- a/spn/hub/update.go +++ b/spn/hub/update.go @@ -5,13 +5,17 @@ import ( "fmt" "time" + "github.com/mr-tron/base58" + "github.com/safing/jess" "github.com/safing/jess/lhash" "github.com/safing/portmaster/base/database" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/network/netutils" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/structures/container" "github.com/safing/structures/dsd" + "github.com/safing/structures/varint" ) var ( @@ -73,6 +77,11 @@ func SignHubMsg(msg []byte, env *jess.Envelope, enableTofu bool) ([]byte, error) // provided hub or the local database. If TOFU is enabled, the signature is // always accepted, if valid. func OpenHubMsg(hub *Hub, data []byte, mapName string, tofu bool) (msg []byte, sendingHub *Hub, known bool, err error) { + // jess.LetterFromDSD uses dsd.Load, which decompresses without limit. + err = peerdsd.CheckFormat(data) + if err != nil { + return nil, nil, false, fmt.Errorf("malformed letter: %w", err) + } letter, err := jess.LetterFromDSD(data) if err != nil { return nil, nil, false, fmt.Errorf("malformed letter: %w", err) @@ -90,7 +99,7 @@ func OpenHubMsg(hub *Hub, data []byte, mapName string, tofu bool) (msg []byte, s } // check signature signer ID - if seal.ID == "" { + if seal == nil || seal.ID == "" { return nil, nil, false, errors.New("signature is missing signer ID") } @@ -138,7 +147,7 @@ func OpenHubMsg(hub *Hub, data []byte, mapName string, tofu bool) (msg []byte, s } // check ID integrity - if !verifyHubID(seal.ID, seal.Scheme, pubkey.Value) { + if pubkey == nil || !verifyHubID(seal.ID, seal.Scheme, pubkey.Value) { return nil, nil, false, fmt.Errorf("ID integrity of %s violated with new key", seal.ID) } @@ -216,7 +225,7 @@ func ApplyAnnouncement(existingHub *Hub, data []byte, mapName string, scope Scop // parse announcement = &Announcement{} - _, err = dsd.Load(msg, announcement) + _, err = peerdsd.Load(msg, announcement) if err != nil { return //nolint:nakedret } @@ -395,7 +404,7 @@ func ApplyStatus(existingHub *Hub, data []byte, mapName string, scope Scope, sel // parse status := &Status{} - _, err = dsd.Load(msg, status) + _, err = peerdsd.Load(msg, status) if err != nil { return //nolint:nakedret } @@ -507,9 +516,53 @@ func createHubID(scheme string, pubkey []byte) string { return lhash.Digest(lhash.BLAKE2b_256, c.CompileData()).Base58() } +// labeledHashFromBase58 is like lhash.FromBase58, but first checks that the +// encoded digest length matches the available data. lhash allocates the +// encoded length before checking it, so a short attacker-supplied ID could +// otherwise make it allocate terabytes and crash the process. +// +// It also limits the length of the encoded hash, as decoding base58 takes +// quadratic time: decoding a 16000 character ID, which fits into a single +// message, takes about 80ms of CPU time. +func labeledHashFromBase58(encoded string) (*lhash.LabeledHash, error) { + if len(encoded) > maxEncodedLabeledHashLength { + return nil, errLabeledHashTooLong + } + raw, err := base58.Decode(encoded) + if err != nil { + return nil, fmt.Errorf("failed to decode base58: %w", err) + } + + // Skip algorithm ID. + _, algIDSize, err := varint.Unpack64(raw) + if err != nil { + return nil, fmt.Errorf("failed to parse algorithm ID: %w", err) + } + // Check digest length. + digestSize, digestSizeSize, err := varint.Unpack64(raw[algIDSize:]) + if err != nil { + return nil, fmt.Errorf("failed to parse digest length: %w", err) + } + if digestSize != uint64(len(raw[algIDSize+digestSizeSize:])) { + return nil, errInvalidDigestLength + } + + return lhash.Load(raw) +} + +// maxEncodedLabeledHashLength is the maximum length of a base58 encoded +// labeled hash. The biggest supported digest (512 bits) is encoded in 91 +// characters. +const maxEncodedLabeledHashLength = 256 + +var ( + errInvalidDigestLength = errors.New("labeled hash has invalid digest length") + errLabeledHashTooLong = errors.New("encoded labeled hash is too long") +) + func verifyHubID(id string, scheme string, pubkey []byte) (ok bool) { // load labeled hash from ID - labeledHash, err := lhash.FromBase58(id) + labeledHash, err := labeledHashFromBase58(id) if err != nil { return false } diff --git a/spn/hub/update_compressed_test.go b/spn/hub/update_compressed_test.go new file mode 100644 index 000000000..51018d624 --- /dev/null +++ b/spn/hub/update_compressed_test.go @@ -0,0 +1,90 @@ +package hub + +import ( + "errors" + "testing" + "time" + + "github.com/safing/jess" + "github.com/safing/structures/dsd" +) + +// TestHubMsgsRejectCompressed checks that gzip compressed hub messages (and +// compressed payloads in correctly signed hub messages) are rejected before +// decompression. dsd.Load decompresses them into an unbounded buffer, so a few +// KB of gossiped data could make every Hub allocate many MB. +func TestHubMsgsRejectCompressed(t *testing.T) { + t.Parallel() + + env, hubID := newTestHubEnvelope(t) + a := &Announcement{ + ID: hubID, + Timestamp: time.Now().Unix(), + Name: "compressed", + Transports: []string{"tcp:1717"}, + } + s := &Status{ + Timestamp: time.Now().Unix(), + Version: "0.1.0", + } + + // Messages as sent by Hubs are accepted. + announcementData, err := a.Export(env) + if err != nil { + t.Fatal(err) + } + statusData, err := s.Export(env) + if err != nil { + t.Fatal(err) + } + h, _, _, err := ApplyAnnouncement(nil, announcementData, "test-compressed-ok", ScopePublic, false) + if err != nil { + t.Fatalf("valid announcement: %s", err) + } + _, _, _, err = ApplyStatus(h, statusData, "test-compressed-ok", ScopePublic, false) //nolint:dogsled + if err != nil { + t.Fatalf("valid status: %s", err) + } + + // Compressed letter. + letter, err := jess.LetterFromDSD(announcementData) + if err != nil { + t.Fatal(err) + } + compressedLetter, err := dsd.DumpAndCompress(letter, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, _, _, err = OpenHubMsg(nil, compressedLetter, "test-compressed-letter", true) //nolint:dogsled + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("compressed letter: expected ErrIncompatibleFormat, got %v", err) + } + + // Compressed announcement in a correctly signed letter. + compressedMsg, err := dsd.DumpAndCompress(a, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + data, err := SignHubMsg(compressedMsg, env, true) + if err != nil { + t.Fatal(err) + } + _, _, _, err = ApplyAnnouncement(nil, data, "test-compressed-announcement", ScopePublic, false) //nolint:dogsled + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("compressed announcement: expected ErrIncompatibleFormat, got %v", err) + } + + // Compressed status in a correctly signed letter. + compressedMsg, err = dsd.DumpAndCompress(s, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + data, err = SignHubMsg(compressedMsg, env, false) + if err != nil { + t.Fatal(err) + } + _, _, _, err = ApplyStatus(h, data, "test-compressed-ok", ScopePublic, false) //nolint:dogsled + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("compressed status: expected ErrIncompatibleFormat, got %v", err) + } +} diff --git a/spn/hub/update_msgpack_test.go b/spn/hub/update_msgpack_test.go new file mode 100644 index 000000000..d42d3d9ea --- /dev/null +++ b/spn/hub/update_msgpack_test.go @@ -0,0 +1,53 @@ +package hub + +import ( + "errors" + "testing" + "time" + + "github.com/safing/portmaster/spn/peerdsd" +) + +// TestHubMsgsRejectOversizedMsgPack checks that msgpack hub messages that +// declare more data than they hold are rejected before decoding. The msgpack +// decoder allocates the declared length up front, so 12 bytes could make it +// allocate 4GB (byte string) or 32GB (slice of pointers) and crash the process. +// The lengths used here are smaller to keep the test cheap without the fix. +func TestHubMsgsRejectOversizedMsgPack(t *testing.T) { + t.Parallel() + + // Letter.Data with a declared length of 64MB. + data := []byte{'M', 0x81, 0xa4, 'D', 'a', 't', 'a', 0xc6, 0x04, 0x00, 0x00, 0x00} + _, _, _, err := OpenHubMsg(nil, data, "test-msgpack-letter", true) //nolint:dogsled + if !errors.Is(err, peerdsd.ErrLengthExceedsData) { + t.Errorf("letter: expected ErrLengthExceedsData, got %v", err) + } + + // Status.Lanes with a declared length of 1M in a correctly signed letter. + env, hubID := newTestHubEnvelope(t) + a := &Announcement{ + ID: hubID, + Timestamp: time.Now().Unix(), + Name: "msgpack", + Transports: []string{"tcp:1718"}, + } + data, err = a.Export(env) + if err != nil { + t.Fatal(err) + } + h, _, _, err := ApplyAnnouncement(nil, data, "test-msgpack-status", ScopePublic, false) + if err != nil { + t.Fatal(err) + } + data, err = SignHubMsg( + []byte{'M', 0x81, 0xa5, 'L', 'a', 'n', 'e', 's', 0xdd, 0x00, 0x10, 0x00, 0x00}, + env, false, + ) + if err != nil { + t.Fatal(err) + } + _, _, _, err = ApplyStatus(h, data, "test-msgpack-status", ScopePublic, false) //nolint:dogsled + if !errors.Is(err, peerdsd.ErrLengthExceedsData) { + t.Errorf("status: expected ErrLengthExceedsData, got %v", err) + } +} diff --git a/spn/hub/update_panic_test.go b/spn/hub/update_panic_test.go new file mode 100644 index 000000000..195e9f3d0 --- /dev/null +++ b/spn/hub/update_panic_test.go @@ -0,0 +1,54 @@ +package hub + +import ( + "testing" + "time" + + "github.com/safing/jess" +) + +func newTestHubEnvelope(tb testing.TB) (*jess.Envelope, string) { + tb.Helper() + + private, _, err := CreateHubSignet("Ed25519", 0) + if err != nil { + tb.Fatal(err) + } + + env := jess.NewUnconfiguredEnvelope() + env.SuiteID = jess.SuiteSignV1 + env.Senders = []*jess.Signet{private} + return env, private.ID +} + +// TestApplyInvalidAnnouncementOfNewHub checks that an invalid announcement of +// a previously unknown Hub is rejected with an error instead of a panic. +func TestApplyInvalidAnnouncementOfNewHub(t *testing.T) { + t.Parallel() + + env, hubID := newTestHubEnvelope(t) + a := &Announcement{ + ID: hubID, + Timestamp: time.Now().Unix(), + Name: "invalid$name", + Transports: []string{"tcp:17"}, + } + data, err := a.Export(env) + if err != nil { + t.Fatal(err) + } + + h, known, _, err := ApplyAnnouncement(nil, data, "test-invalid-new", ScopePublic, false) + if err == nil { + t.Fatal("invalid announcement was accepted") + } + if known { + t.Fatal("hub should not be known") + } + if h == nil || h.Info != nil { + t.Fatal("expected unknown hub without info") + } + // The name must also be safe to use for such a hub. + _ = h.Name() + _ = h.String() +} diff --git a/spn/navigator/api.go b/spn/navigator/api.go index fe695570c..5ce0537f8 100644 --- a/spn/navigator/api.go +++ b/spn/navigator/api.go @@ -441,7 +441,9 @@ func handleMapGraphRequest(w http.ResponseWriter, hr *http.Request) { _ = graph.AddAttr("", "overlap", "scale") _ = graph.AddAttr("", "center", "true") _ = graph.AddAttr("", "ratio", "fill") - for _, pin := range m.sortedPins(true) { + // Lock the map, as pin states and lanes are guarded by the map lock. + m.RLock() + for _, pin := range m.sortedPins(false) { _ = graph.AddNode("", pin.Hub.ID, map[string]string{ "label": graphNodeLabel(pin), "tooltip": graphNodeTooltip(pin), @@ -467,6 +469,7 @@ func handleMapGraphRequest(w http.ResponseWriter, hr *http.Request) { } } } + m.RUnlock() var mimeType string var responseData []byte diff --git a/spn/navigator/api_route.go b/spn/navigator/api_route.go index 965cb5856..4e8a783ab 100644 --- a/spn/navigator/api_route.go +++ b/spn/navigator/api_route.go @@ -119,7 +119,7 @@ func handleRouteCalculationRequest(ar *api.Request) (msg string, err error) { // } // Require a trusted home node when the routing profile requires less than two hops. - routingProfile := GetRoutingProfile(config.GetAsString(profile.CfgOptionRoutingAlgorithmKey, DefaultRoutingProfileID)()) + routingProfile := GetRoutingProfile(config.GetAsString(CfgOptionRoutingAlgorithmKey, DefaultRoutingProfileID)()) if routingProfile.MinHops < 2 { opts.Home.Regard = opts.Home.Regard.Add(StateTrusted) } diff --git a/spn/navigator/database.go b/spn/navigator/database.go index 62288951b..a10b778b4 100644 --- a/spn/navigator/database.go +++ b/spn/navigator/database.go @@ -140,7 +140,7 @@ func (m *Map) pushPinChangesWorker(ctx *mgr.WorkerCtx) error { for _, pin := range m.all { if pin.pushChanges.SetToIf(true, false) { - mapDBController.PushUpdate(pin.Export()) + mapDBController.PushUpdate(pin.exportLocked()) } } diff --git a/spn/navigator/map_test.go b/spn/navigator/map_test.go index 99e911882..6448949e1 100644 --- a/spn/navigator/map_test.go +++ b/spn/navigator/map_test.go @@ -137,11 +137,14 @@ func createRandomTestMap(seed int64, size int) *Map { m.UpdateHub(h) } + // Lock the map, as pin changes are pushed (and exported) concurrently. + m.Lock() + defer m.Unlock() + // Fake communication error with three Hubs. var i int for _, pin := range m.all { - pin.MarkAsFailingFor(1 * time.Hour) - pin.addStates(StateFailing) + pin.markAsFailingFor(1 * time.Hour) if i++; i >= 3 { break diff --git a/spn/navigator/module.go b/spn/navigator/module.go index b2e4bba8c..7082f7701 100644 --- a/spn/navigator/module.go +++ b/spn/navigator/module.go @@ -13,8 +13,14 @@ import ( ) const ( - // cfgOptionRoutingAlgorithmKey is copied from profile/config.go to avoid import loop. - cfgOptionRoutingAlgorithmKey = "spn/routingAlgorithm" + // CfgOptionRoutingAlgorithmKey is the config key of the SPN routing + // algorithm. The client settings using the SPN keys have been removed from + // service/profile, as portmaster-core no longer includes the SPN. + CfgOptionRoutingAlgorithmKey = "spn/routingAlgorithm" + // CfgOptionTransitHubPolicyKey is the config key of the SPN transit hub policy. + CfgOptionTransitHubPolicyKey = "spn/transitHubPolicy" + // CfgOptionExitHubPolicyKey is the config key of the SPN exit hub policy. + CfgOptionExitHubPolicyKey = "spn/exitHubPolicy" // cfgOptionRoutingAlgorithmKey is copied from captain/config.go to avoid import loop. cfgOptionTrustNodeNodesKey = "spn/trustNodes" @@ -74,7 +80,7 @@ func start() error { cfgOptionTrustNodeNodes = config.Concurrent.GetAsStringArray(cfgOptionTrustNodeNodesKey, []string{}) if conf.Integrated() { - cfgOptionRoutingAlgorithm = config.Concurrent.GetAsString(cfgOptionRoutingAlgorithmKey, DefaultRoutingProfileID) + cfgOptionRoutingAlgorithm = config.Concurrent.GetAsString(CfgOptionRoutingAlgorithmKey, DefaultRoutingProfileID) } else { cfgOptionRoutingAlgorithm = func() string { return DefaultRoutingProfileID } } diff --git a/spn/navigator/optimize.go b/spn/navigator/optimize.go index f396b344e..b3f8e29f9 100644 --- a/spn/navigator/optimize.go +++ b/spn/navigator/optimize.go @@ -26,7 +26,7 @@ const ( ) // AnalysisState holds state for analyzing the network for optimizations. -type AnalysisState struct { //nolint:maligned +type AnalysisState struct { // Suggested signifies that a direct connection to this Hub is suggested by // the optimization algorithm. Suggested bool diff --git a/spn/navigator/optimize_test.go b/spn/navigator/optimize_test.go index 83f778cfe..cfea3a433 100644 --- a/spn/navigator/optimize_test.go +++ b/spn/navigator/optimize_test.go @@ -109,13 +109,13 @@ func (m *Map) optimizeTestMap(t *testing.T) { m.home = originalHome } -func TestOptimize(t *testing.T) { - t.Parallel() - +func TestOptimize(t *testing.T) { //nolint:paralleltest // Modifies the shared test map. m := getOptimizedDefaultTestMap(t) matcher := m.defaultOptions().Destination.Matcher(m.intel) originalHome := m.home + // Lock the map, as pin changes are pushed (and exported) concurrently. + m.Lock() for _, pin := range m.all { // Set Home to this Pin for this iteration. m.home = pin @@ -137,10 +137,11 @@ func TestOptimize(t *testing.T) { } } + m.home = originalHome + m.Unlock() + // Print stats t.Logf("optimized map:\n%s\n", m.Stats()) - - m.home = originalHome } func updateMeasurements(m *Map, mcf *measurementCachedFactory) { diff --git a/spn/navigator/options.go b/spn/navigator/options.go index 708d7f7e4..334921207 100644 --- a/spn/navigator/options.go +++ b/spn/navigator/options.go @@ -25,7 +25,7 @@ const ( var DeriveTunnelOptions func(lp *profile.LayeredProfile, destination *intel.Entity, connEncrypted bool) *Options // Options holds configuration options for operations with the Map. -type Options struct { //nolint:maligned +type Options struct { // Home holds the options for Home Hubs. Home *HomeHubOptions diff --git a/spn/navigator/pin.go b/spn/navigator/pin.go index 54571b6b0..3c23c296a 100644 --- a/spn/navigator/pin.go +++ b/spn/navigator/pin.go @@ -16,7 +16,7 @@ import ( ) // Pin represents a Hub on a Map. -type Pin struct { //nolint:maligned +type Pin struct { // Hub Information Hub *hub.Hub EntityV4 *intel.Entity @@ -25,6 +25,8 @@ type Pin struct { //nolint:maligned LocationV6 *geoip.Location // Hub Status + // State is guarded by the lock of the owning Map, not by the Pin lock. + // Outside of this package, use GetState to access it. State PinState // stateIntelApplied signifies that states from intel file were applied to the pin. @@ -44,6 +46,7 @@ type Pin struct { //nolint:maligned // FailingUntil specifies until when this Hub should be regarded as failing. // This is connected to StateFailing. + // FailingUntil is guarded by the lock of the owning Map, like State. FailingUntil time.Time // Connection holds a information about a connection to the Hub of this Pin. @@ -68,6 +71,10 @@ type Pin struct { //nolint:maligned // region is the region this Pin belongs to. region *Region + + // owner is the Map this Pin belongs to. + // It is used to lock the Map when the Pin is accessed from outside. + owner *Map } // PinConnection represents a connection to a terminal on the Hub. @@ -115,9 +122,10 @@ func (pin *Pin) String() string { } // GetState returns the state of the pin. +// The owning Map is read locked for this, so the Map must not be locked by +// the caller. func (pin *Pin) GetState() PinState { - pin.Lock() - defer pin.Unlock() + defer pin.rLockState()() return pin.State } @@ -228,21 +236,72 @@ func (pin *Pin) NotifyTerminalChange() { } // IsFailing returns whether the pin should be treated as failing. -// The Pin is locked for this. +// The owning Map is read locked for this, so the Map must not be locked by +// the caller. func (pin *Pin) IsFailing() bool { - pin.Lock() - defer pin.Unlock() + defer pin.rLockState()() - return time.Now().Before(pin.FailingUntil) + return pin.isFailing() } // MarkAsFailingFor marks the pin as failing. -// The Pin is locked for this. +// The owning Map is locked for this, so the Map must not be locked by the +// caller. // Changes are pushed. func (pin *Pin) MarkAsFailingFor(duration time.Duration) { + unlock := pin.lockState() + pin.markAsFailingFor(duration) + unlock() + + pin.pushChange() +} + +// ResetFailingState resets the failing state. +// The owning Map is locked for this, so the Map must not be locked by the +// caller. +// Changes are not pushed, but Pins are marked. +func (pin *Pin) ResetFailingState() { + defer pin.lockState()() + + pin.resetFailingState() +} + +// lockState locks the State and FailingUntil fields of the Pin for writing and +// returns the function to unlock them again. +// These fields are guarded by the lock of the owning Map, as all state +// updates within the navigator are done while holding the Map lock. +// No other lock may be acquired while holding the returned lock. +// Pins without an owning Map fall back to the Pin lock. +func (pin *Pin) lockState() (unlock func()) { + if pin.owner != nil { + pin.owner.Lock() + return pin.owner.Unlock + } pin.Lock() - defer pin.Unlock() + return pin.Unlock +} + +// rLockState locks the State and FailingUntil fields of the Pin for reading +// and returns the function to unlock them again. See lockState. +func (pin *Pin) rLockState() (unlock func()) { + if pin.owner != nil { + pin.owner.RLock() + return pin.owner.RUnlock + } + pin.Lock() + return pin.Unlock +} + +// isFailing returns whether the pin should be treated as failing. +// The owning Map must be locked by the caller. +func (pin *Pin) isFailing() bool { + return time.Now().Before(pin.FailingUntil) +} +// markAsFailingFor marks the pin as failing. +// The owning Map must be locked by the caller. +// Changes are not pushed, but the Pin is marked. +func (pin *Pin) markAsFailingFor(duration time.Duration) { until := time.Now().Add(duration) // Only ever increase failing until, never reduce. if until.After(pin.FailingUntil) { @@ -252,16 +311,12 @@ func (pin *Pin) MarkAsFailingFor(duration time.Duration) { pin.addStates(StateFailing) pin.pushChanges.Set() - pin.pushChange() } -// ResetFailingState resets the failing state. -// The Pin is locked for this. +// resetFailingState resets the failing state. +// The owning Map must be locked by the caller. // Changes are not pushed, but Pins are marked. -func (pin *Pin) ResetFailingState() { - pin.Lock() - defer pin.Unlock() - +func (pin *Pin) resetFailingState() { if time.Now().Before(pin.FailingUntil) { pin.FailingUntil = time.Now() pin.pushChanges.Set() diff --git a/spn/navigator/pin_export.go b/spn/navigator/pin_export.go index 7e03e2f7d..eb508cdd9 100644 --- a/spn/navigator/pin_export.go +++ b/spn/navigator/pin_export.go @@ -50,7 +50,20 @@ type LaneExport struct { } // Export puts the Pin's information into an exportable format. +// The owning Map is read locked for this, so the Map must not be locked by +// the caller. Use exportLocked if the Map is already locked. func (pin *Pin) Export() *PinExport { + if pin.owner != nil { + pin.owner.RLock() + defer pin.owner.RUnlock() + } + return pin.exportLocked() +} + +// exportLocked puts the Pin's information into an exportable format. +// The owning Map must be locked by the caller, as the Pin's state and lanes +// are modified under the Map lock. +func (pin *Pin) exportLocked() *PinExport { pin.Lock() defer pin.Unlock() diff --git a/spn/navigator/pin_failing_test.go b/spn/navigator/pin_failing_test.go new file mode 100644 index 000000000..88a73a779 --- /dev/null +++ b/spn/navigator/pin_failing_test.go @@ -0,0 +1,99 @@ +package navigator + +import ( + "runtime" + "sync" + "testing" + "time" + + "github.com/safing/portmaster/spn/hub" +) + +// TestPinFailingStateLocking checks that the failing state of a Pin, which is +// set from outside of the package without holding the Map lock, is +// synchronized with state updates done while holding the Map lock. +func TestPinFailingStateLocking(t *testing.T) { + t.Parallel() + + const rounds = 2000 + + // Create a minimal map with a single Hub without IPs, which keeps the + // test fast, as no geoip lookups are needed. + m := NewMap("Test-Map-Failing-State-Locking", false) + defer m.Close() + m.UpdateHub(&hub.Hub{ + ID: "test-hub", + Map: m.Name, + Info: &hub.Announcement{ID: "test-hub"}, + Status: &hub.Status{}, + FirstSeen: time.Now(), + }) + pin, ok := m.GetPin("test-hub") + if !ok { + t.Fatal("failed to add test hub to map") + } + + var wg sync.WaitGroup + done := make(chan struct{}) + + // Mark and reset the failing state like spn/crew and spn/captain do: + // without holding the map lock. + wg.Go(func() { + defer close(done) + + for range rounds { + pin.ResetFailingState() + pin.MarkAsFailingFor(time.Hour) + _ = pin.GetState() + _ = pin.IsFailing() + } + }) + + // Concurrently run map-locked state updates and readers. + var changedWhileLocked int + wg.Go(func() { + matcher := m.DefaultOptions().Matcher(TransitHub, nil) + for { + select { + case <-done: + return + default: + } + + // Read-modify-write of an unrelated state while holding the map lock. + m.Lock() + pin.addStates(StateConnectivityIssues) + before := pin.State + runtime.Gosched() + if pin.State != before { + changedWhileLocked++ + } + pin.removeStates(StateConnectivityIssues) + m.Unlock() + + // Expire failing states. + _ = m.updateFailingStates(nil) + + // Match pins. + m.RLock() + _ = matcher(pin) + m.RUnlock() + } + }) + + wg.Wait() + + m.RLock() + defer m.RUnlock() + + if changedWhileLocked > 0 { + t.Errorf("pin state changed %d times while the map was locked", changedWhileLocked) + } + // The last operation marked the pin as failing for an hour. + if !pin.State.Has(StateFailing) || !time.Now().Before(pin.FailingUntil) { + t.Errorf("pin lost failing state: states=%s failingUntil=%s", pin.State, pin.FailingUntil) + } + if pin.State.Has(StateConnectivityIssues) { + t.Errorf("pin state update was lost: states=%s", pin.State) + } +} diff --git a/spn/navigator/routing-profiles.go b/spn/navigator/routing-profiles.go index 55508eb86..7ba9287f0 100644 --- a/spn/navigator/routing-profiles.go +++ b/spn/navigator/routing-profiles.go @@ -2,7 +2,6 @@ package navigator import ( "github.com/safing/portmaster/base/log" - "github.com/safing/portmaster/service/profile" ) // RoutingProfile defines a routing algorithm with some options. @@ -43,7 +42,7 @@ const ( // Routing Profiles. var ( - DefaultRoutingProfileID = profile.DefaultRoutingProfileID + DefaultRoutingProfileID = RoutingProfileDoubleHopID RoutingProfileHome = &RoutingProfile{ ID: "home", diff --git a/spn/navigator/state.go b/spn/navigator/state.go index dd2607549..5bbe23d7d 100644 --- a/spn/navigator/state.go +++ b/spn/navigator/state.go @@ -165,11 +165,13 @@ func (pinState PinState) HasNoneOf(states PinState) bool { } // addStates adds the given states on the Pin. +// The owning Map must be locked by the caller. func (pin *Pin) addStates(states PinState) { pin.State = pin.State.Add(states) } // removeStates removes the given states on the Pin. +// The owning Map must be locked by the caller. func (pin *Pin) removeStates(states PinState) { pin.State = pin.State.Remove(states) } diff --git a/spn/navigator/update.go b/spn/navigator/update.go index 17b73ae3e..21affbe88 100644 --- a/spn/navigator/update.go +++ b/spn/navigator/update.go @@ -19,7 +19,6 @@ import ( "github.com/safing/portmaster/service/intel/geoip" "github.com/safing/portmaster/service/mgr" "github.com/safing/portmaster/service/netenv" - "github.com/safing/portmaster/service/profile" "github.com/safing/portmaster/spn/hub" ) @@ -135,7 +134,7 @@ func (m *Map) RemoveHub(id string) { } // Push update to subscriptions. - export := pin.Export() + export := pin.exportLocked() export.Meta().Delete() mapDBController.PushUpdate(export) // Push lane changes. @@ -172,6 +171,7 @@ func (m *Map) updateHub(h *hub.Hub, lockMap, lockHub bool) { ConnectedTo: make(map[string]*Lane), stateIntelApplied: abool.New(), pushChanges: abool.New(), + owner: m, } m.all[h.ID] = pin } @@ -415,7 +415,7 @@ func (m *Map) ResetFailingStates() { defer m.Unlock() for _, pin := range m.all { - pin.ResetFailingState() + pin.resetFailingState() } m.PushPinChanges() @@ -426,7 +426,7 @@ func (m *Map) updateFailingStates(ctx *mgr.WorkerCtx) error { defer m.Unlock() for _, pin := range m.all { - if pin.State.Has(StateFailing) && !pin.IsFailing() { + if pin.State.Has(StateFailing) && !pin.isFailing() { pin.removeStates(StateFailing) } } @@ -574,24 +574,29 @@ func (m *Map) UpdateConfigQuickSettings(wc *mgr.WorkerCtx) error { } // Home Policy. - if err := m.updateQuickSettingExcludeCountryList(ctx, "spn/homePolicy", opts, HomeHub); err != nil { + err := m.updateQuickSettingExcludeCountryList(ctx, "spn/homePolicy", opts, HomeHub) + if err != nil { return err } // Transit Policy. - if err := m.updateQuickSettingExcludeCountryList(ctx, profile.CfgOptionTransitHubPolicyKey, opts, TransitHub); err != nil { + err = m.updateQuickSettingExcludeCountryList(ctx, CfgOptionTransitHubPolicyKey, opts, TransitHub) + if err != nil { return err } // Exit Policy. - if err := m.updateSelectRuleCountryList(ctx, profile.CfgOptionExitHubPolicyKey, opts, DestinationHub); err != nil { + err = m.updateSelectRuleCountryList(ctx, CfgOptionExitHubPolicyKey, opts, DestinationHub) + if err != nil { return err } // DNS Exit Policy. - if err := m.updateSelectRuleCountryList(ctx, "spn/dnsExitPolicy", opts, DestinationHub); err != nil { + err = m.updateSelectRuleCountryList(ctx, "spn/dnsExitPolicy", opts, DestinationHub) + if err != nil { return err } // Trust Nodes. - if err := m.updateQuickSettingVerifiedOwnerList(ctx, "spn/trustNodes"); err != nil { + err = m.updateQuickSettingVerifiedOwnerList(ctx, "spn/trustNodes") + if err != nil { return err } diff --git a/spn/peerdsd/msgpack.go b/spn/peerdsd/msgpack.go new file mode 100644 index 000000000..70496899f --- /dev/null +++ b/spn/peerdsd/msgpack.go @@ -0,0 +1,103 @@ +package peerdsd + +import "errors" + +// ErrLengthExceedsData is returned by CheckFormat and Load if msgpack data +// declares a length that is larger than the remaining data. +var ErrLengthExceedsData = errors.New("peerdsd: msgpack: declared length exceeds data") + +// checkMsgPackLengths checks that none of the lengths declared in the first +// msgpack value of data exceeds the remaining data. +// +// The msgpack decoder allocates the declared length of byte strings and +// slices before it reads them: 12 bytes declaring a 4GB byte string make it +// allocate 4GB, and an array declaring 2^32 pointers makes it allocate 32GB, +// which crashes the process with "fatal error: out of memory". +// Data with such a length is truncated and fails to decode anyway, so +// rejecting it does not change which data is accepted. Everything else (eg. +// invalid codes or other truncated data) is left to the decoder. +func checkMsgPackLengths(data []byte) error { + pending := 1 // Number of values that still need to be read. + for pending > 0 && len(data) > 0 { + code := data[0] + data = data[1:] + pending-- + + var ( + lenSize int // Size of the length field. + length uint64 // Declared length. + isBytes bool // Whether the length is in bytes, not in values. + valueSize uint64 = 1 + fixedSize int // Size of fixed size data. + ) + switch { + case code <= 0x7f, code >= 0xe0, code == 0xc0, code == 0xc2, code == 0xc3: + // fixint, nil, bool + case code <= 0x8f: // fixmap + length, valueSize = uint64(code&0x0f), 2 + case code <= 0x9f: // fixarray + length = uint64(code & 0x0f) + case code <= 0xbf: // fixstr + length, isBytes = uint64(code&0x1f), true + case code == 0xc4, code == 0xd9: // bin8, str8 + lenSize, isBytes = 1, true + case code == 0xc5, code == 0xda: // bin16, str16 + lenSize, isBytes = 2, true + case code == 0xc6, code == 0xdb: // bin32, str32 + lenSize, isBytes = 4, true + case code >= 0xc7 && code <= 0xc9: // ext8, ext16, ext32 + lenSize, isBytes, fixedSize = 1<<(code-0xc7), true, 1 // Ext type. + case code == 0xca: // float32 + fixedSize = 4 + case code == 0xcb: // float64 + fixedSize = 8 + case code >= 0xcc && code <= 0xd3: // uint8-64, int8-64 + fixedSize = 1 << ((code - 0xcc) % 4) + case code >= 0xd4 && code <= 0xd8: // fixext1-16 + fixedSize = 1 + 1<<(code-0xd4) + case code == 0xdc: // array16 + lenSize = 2 + case code == 0xdd: // array32 + lenSize = 4 + case code == 0xde: // map16 + lenSize, valueSize = 2, 2 + case code == 0xdf: // map32 + lenSize, valueSize = 4, 2 + default: // 0xc1 is never used. + return nil + } + + // Read the length field. + if len(data) < lenSize { + return nil + } + for _, b := range data[:lenSize] { + length = length<<8 | uint64(b) + } + data = data[lenSize:] + + // Check the declared length. + switch { + case isBytes: + // The ext type is read together with the data. + length += uint64(fixedSize) + if length > uint64(len(data)) { + return ErrLengthExceedsData + } + data = data[length:] + case fixedSize > 0: + if len(data) < fixedSize { + return nil + } + data = data[fixedSize:] + case length > 0: + // Every value needs at least one byte. + length *= valueSize + if length+uint64(pending) > uint64(len(data)) { + return ErrLengthExceedsData + } + pending += int(length) //nolint:gosec // Bounded by len(data). + } + } + return nil +} diff --git a/spn/peerdsd/msgpack_test.go b/spn/peerdsd/msgpack_test.go new file mode 100644 index 000000000..84787631d --- /dev/null +++ b/spn/peerdsd/msgpack_test.go @@ -0,0 +1,169 @@ +package peerdsd + +import ( + "bytes" + "errors" + "testing" + "time" + + "github.com/safing/structures/dsd" +) + +type msgpackStruct struct { + Data []byte + Items []*testStruct + Names []string + Map map[string]int + Time time.Time + F32 float32 + F64 float64 + I int64 + U uint64 + B bool + P *testStruct +} + +func validMsgPackStructs() []*msgpackStruct { + items := make([]*testStruct, 20) + for i := range items { + items[i] = &testStruct{A: "item", B: i} + } + m := make(map[string]int, 20) + for i := range 20 { + m[string(rune('a'+i))] = i << (i * 3) + } + return []*msgpackStruct{ + {}, + { + Data: []byte("data"), + Items: items[:3], + Names: []string{"a", "bb", ""}, + Map: map[string]int{"a": 1, "b": -1000000}, + Time: time.Unix(1700000000, 123).UTC(), + F32: 1.5, + F64: -2.5, + I: -1 << 40, + U: 1 << 63, + B: true, + P: &testStruct{A: "p", B: 70000}, + }, + { + Data: bytes.Repeat([]byte{1}, 300), + Items: items, + Names: []string{string(bytes.Repeat([]byte{'s'}, 40)), string(bytes.Repeat([]byte{'s'}, 300))}, + Map: m, + }, + {Data: bytes.Repeat([]byte{1}, 70000)}, + } +} + +// TestMsgPackLengthsAcceptsValid checks that msgpack data as produced by +// dsd.Dump is accepted and loaded. +func TestMsgPackLengthsAcceptsValid(t *testing.T) { + t.Parallel() + + for i, s := range validMsgPackStructs() { + data, err := dsd.Dump(s, dsd.MsgPack) + if err != nil { + t.Fatal(err) + } + err = CheckFormat(data) + if err != nil { + t.Errorf("struct %d: CheckFormat failed: %s", i, err) + } + loaded := &msgpackStruct{} + _, err = Load(data, loaded) + if err != nil { + t.Errorf("struct %d: Load failed: %s", i, err) + } + if !bytes.Equal(loaded.Data, s.Data) || len(loaded.Items) != len(s.Items) || + len(loaded.Map) != len(s.Map) || !loaded.Time.Equal(s.Time) || loaded.U != s.U { + t.Errorf("struct %d: unexpected result: %+v", i, loaded) + } + } +} + +// TestMsgPackLengthsOnlyRejectsInvalid checks that data rejected by the +// msgpack length check also fails to load with dsd.Load, using all truncations +// of valid data. +func TestMsgPackLengthsOnlyRejectsInvalid(t *testing.T) { + t.Parallel() + + var rejected int + for i, s := range validMsgPackStructs()[:3] { + data, err := dsd.Dump(s, dsd.MsgPack) + if err != nil { + t.Fatal(err) + } + for n := 2; n <= len(data); n++ { + err := CheckFormat(data[:n]) + switch { + case err == nil: + case errors.Is(err, ErrLengthExceedsData): + rejected++ + _, loadErr := dsd.Load(data[:n], &msgpackStruct{}) + if loadErr == nil { + t.Errorf("struct %d truncated to %d bytes: rejected, but dsd.Load accepts it", i, n) + } + default: + t.Errorf("struct %d truncated to %d bytes: unexpected error %s", i, n, err) + } + } + } + if rejected == 0 { + t.Error("no truncated data was rejected") + } +} + +// TestMsgPackLengthsRejectsOversized checks that msgpack data that declares +// more data than it holds is rejected before decoding. The msgpack decoder +// allocates the declared length up front: 12 bytes declaring a 4GB byte string +// allocate 4GB, and declaring 2^32 pointers in an array allocates 32GB, which +// crashes the process with "fatal error: out of memory". +// The lengths used here are smaller to keep the test cheap without the fix. +func TestMsgPackLengthsRejectsOversized(t *testing.T) { + t.Parallel() + + for name, data := range map[string][]byte{ + "bin32": {'M', 0x81, 0xa4, 'D', 'a', 't', 'a', 0xc6, 0x01, 0x00, 0x00, 0x00}, + "bin16": {'M', 0x81, 0xa4, 'D', 'a', 't', 'a', 0xc5, 0x01, 0x00, 1, 2, 3}, + "bin8": {'M', 0x81, 0xa4, 'D', 'a', 't', 'a', 0xc4, 0x05, 1, 2, 3}, + "str32 key": {'M', 0x81, 0xdb, 0x01, 0x00, 0x00, 0x00, 'a'}, + "fixstr key": {'M', 0x81, 0xa9, 'D', 'a', 't', 'a'}, + "array32": {'M', 0x81, 0xa5, 'I', 't', 'e', 'm', 's', 0xdd, 0x00, 0x10, 0x00, 0x00}, + "array16": {'M', 0x81, 0xa5, 'N', 'a', 'm', 'e', 's', 0xdc, 0xff, 0xff, 0xc0}, + "map32": {'M', 0x81, 0xa3, 'M', 'a', 'p', 0xdf, 0x00, 0x10, 0x00, 0x00}, + "top-level map32": {'M', 0xdf, 0x00, 0x10, 0x00, 0x00}, + "fixmap": {'M', 0x8f, 0xc0, 0xc0}, + "ext32": {'M', 0x81, 0xa4, 'T', 'i', 'm', 'e', 0xc9, 0x00, 0x10, 0x00, 0x00, 0xff}, + "ext32 no type": {'M', 0x91, 0xc9, 0x00, 0x10, 0x00, 0x00}, + "nested": {'M', 0x81, 0xa5, 'I', 't', 'e', 'm', 's', 0x91, 0x81, 0xa1, 'a', 0xdb, 0x00, 0x10, 0x00, 0x00}, + } { + err := CheckFormat(data) + if !errors.Is(err, ErrLengthExceedsData) { + t.Errorf("%s: CheckFormat: expected ErrLengthExceedsData, got %v", name, err) + } + _, err = Load(data, &msgpackStruct{}) + if !errors.Is(err, ErrLengthExceedsData) { + t.Errorf("%s: Load: expected ErrLengthExceedsData, got %v", name, err) + } + } +} + +func FuzzLoad(f *testing.F) { + for _, s := range validMsgPackStructs()[:3] { + for _, format := range []uint8{dsd.JSON, dsd.CBOR, dsd.MsgPack, dsd.YAML} { + data, err := dsd.Dump(s, format) + if err != nil { + f.Fatal(err) + } + f.Add(data) + } + } + f.Add([]byte{'M', 0x81, 0xa4, 'D', 'a', 't', 'a', 0xc6, 0xff, 0xff, 0xff, 0xff}) + f.Add([]byte{'M', 0x81, 0xa5, 'I', 't', 'e', 'm', 's', 0xdd, 0xff, 0xff, 0xff, 0xff}) + + f.Fuzz(func(t *testing.T, data []byte) { + _, _ = Load(data, &msgpackStruct{}) + }) +} diff --git a/spn/peerdsd/peerdsd.go b/spn/peerdsd/peerdsd.go new file mode 100644 index 000000000..6d5666bec --- /dev/null +++ b/spn/peerdsd/peerdsd.go @@ -0,0 +1,54 @@ +// Package peerdsd loads dsd data received from other parties. +// +// dsd.Load transparently decompresses gzip compressed data (dsd format "Z") +// into an unbounded buffer before parsing it. gzip compresses up to about +// 1:1030, so a few KB of data received from the network can make dsd.Load +// allocate many MB (or, combined with the YAML decoder, GB). No SPN component +// sends compressed dsd data, so data received from other parties is checked +// to be in a serialization format before it is handed to dsd.Load. +// +// The msgpack decoder allocates declared lengths before reading the data, so +// msgpack data is checked to not declare more data than it holds. +package peerdsd + +import ( + "io" + + "github.com/safing/structures/dsd" + "github.com/safing/structures/varint" +) + +// CheckFormat checks that the given dsd data is in a serialization format and +// not compressed. It returns the same errors as dsd.Load for malformed data +// and dsd.ErrIncompatibleFormat for compressed data and unknown formats, which +// dsd.Load rejects too. For msgpack data, it returns ErrLengthExceedsData if +// a declared length exceeds the data. +// Use it on data received from other parties before passing it to a function +// that calls dsd.Load internally, such as jess.LetterFromDSD. +func CheckFormat(data []byte) error { + format, read, err := varint.Unpack8(data) + if err != nil { + return err + } + if len(data) <= read { + return io.ErrUnexpectedEOF + } + if _, ok := dsd.ValidateSerializationFormat(format); !ok { + return dsd.ErrIncompatibleFormat + } + if format == dsd.MsgPack { + return checkMsgPackLengths(data[read:]) + } + return nil +} + +// Load is like dsd.Load, but rejects compressed data and msgpack data that +// declares lengths larger than the data. Use it instead of dsd.Load for data +// received from other parties. +func Load(data []byte, t any) (format uint8, err error) { + err = CheckFormat(data) + if err != nil { + return 0, err + } + return dsd.Load(data, t) +} diff --git a/spn/peerdsd/peerdsd_test.go b/spn/peerdsd/peerdsd_test.go new file mode 100644 index 000000000..dd35ecade --- /dev/null +++ b/spn/peerdsd/peerdsd_test.go @@ -0,0 +1,157 @@ +package peerdsd + +import ( + "bytes" + "compress/gzip" + "errors" + "testing" + + "github.com/safing/structures/dsd" +) + +type testStruct struct { + A string `json:"a"` + B int `json:"b"` +} + +// gzipDSD returns the given dsd data compressed with gzip, as produced by +// dsd.DumpAndCompress, with padding spaces inserted after the format. +// The padding is valid JSON whitespace, so the compressed data is a valid +// message that dsd.Load accepts. +func gzipDSD(tb testing.TB, data []byte, padding int) []byte { + tb.Helper() + + buf := bytes.NewBuffer([]byte{dsd.GZIP}) + w, err := gzip.NewWriterLevel(buf, gzip.BestCompression) + if err != nil { + tb.Fatal(err) + } + _, _ = w.Write(data[:1]) + _, _ = w.Write(bytes.Repeat([]byte{' '}, padding)) + _, _ = w.Write(data[1:]) + err = w.Close() + if err != nil { + tb.Fatal(err) + } + return buf.Bytes() +} + +func TestLoadRejectsCompressed(t *testing.T) { + t.Parallel() + + data, err := dsd.DumpAndCompress(&testStruct{A: "a", B: 1}, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + bomb := gzipDSD(t, []byte(`J{"a":"a","b":1}`), 1<<20) + + for _, d := range [][]byte{data, bomb} { + // dsd.Load decompresses it. + s := &testStruct{} + _, err = dsd.Load(d, s) + if err != nil || s.A != "a" { + t.Fatalf("dsd.Load: unexpected result %+v, %v", s, err) + } + + // Load and CheckFormat reject it. + s = &testStruct{} + _, err = Load(d, s) + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("Load: expected ErrIncompatibleFormat, got %v", err) + } + if *s != (testStruct{}) { + t.Errorf("Load: struct was modified: %+v", s) + } + err = CheckFormat(d) + if !errors.Is(err, dsd.ErrIncompatibleFormat) { + t.Errorf("CheckFormat: expected ErrIncompatibleFormat, got %v", err) + } + } +} + +func TestLoadAcceptsSerializationFormats(t *testing.T) { + t.Parallel() + + for _, format := range []uint8{dsd.JSON, dsd.CBOR, dsd.MsgPack, dsd.YAML} { + data, err := dsd.Dump(&testStruct{A: "a", B: 1}, format) + if err != nil { + t.Fatal(err) + } + err = CheckFormat(data) + if err != nil { + t.Errorf("format %c: CheckFormat failed: %s", format, err) + } + s := &testStruct{} + loadedFormat, err := Load(data, s) + if err != nil { + t.Errorf("format %c: Load failed: %s", format, err) + } + if loadedFormat != format || *s != (testStruct{A: "a", B: 1}) { + t.Errorf("format %c: unexpected result %c %+v", format, loadedFormat, s) + } + } +} + +// TestLoadSameAsDSD checks that Load behaves exactly like dsd.Load for every +// format other than compression. +func TestLoadSameAsDSD(t *testing.T) { + t.Parallel() + + payloads := [][]byte{ + nil, + {}, + []byte(`{"a":"a","b":1}`), + {0xa1, 0x61, 0x61, 0x61, 0x61}, // CBOR/MsgPack-ish. + []byte("a: a\nb: 1\n"), + {0x80}, + } + for format := range 256 { + if format == dsd.GZIP { + continue + } + for _, payload := range payloads { + data := append([]byte{byte(format)}, payload...) + s1, s2 := &testStruct{}, &testStruct{} + f1, err1 := dsd.Load(data, s1) + f2, err2 := Load(data, s2) + if f1 != f2 || *s1 != *s2 || (err1 == nil) != (err2 == nil) || + (err1 != nil && err1.Error() != err2.Error()) { + t.Errorf("format %d, payload %q: dsd.Load = (%d, %+v, %v), Load = (%d, %+v, %v)", + format, payload, f1, s1, err1, f2, s2, err2) + } + } + } + // Multi-byte varint format. + data := []byte{0x80, 0x01, '{', '}'} + _, err1 := dsd.Load(data, &testStruct{}) + _, err2 := Load(data, &testStruct{}) + if !errors.Is(err1, dsd.ErrIncompatibleFormat) || !errors.Is(err2, dsd.ErrIncompatibleFormat) { + t.Errorf("multi-byte format: unexpected errors %v, %v", err1, err2) + } +} + +// BenchmarkLoadGzipBomb measures the cost of a 16KB gzip compressed message, +// the maximum size of an SPN segment (spn/docks/crane.go maxSegmentLength). +func BenchmarkLoadGzipBomb(b *testing.B) { + // Find padding that results in a message just below 16KB. + padding := 16 << 20 + bomb := gzipDSD(b, []byte(`J{"a":"a","b":1}`), padding) + for len(bomb) > 16384 { + padding -= 64 << 10 + bomb = gzipDSD(b, []byte(`J{"a":"a","b":1}`), padding) + } + b.Logf("message size: %d bytes, decompressed: %d bytes", len(bomb), padding+16) + + b.Run("dsd.Load", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _, _ = dsd.Load(bomb, &testStruct{}) + } + }) + b.Run("peerdsd.Load", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + _, _ = Load(bomb, &testStruct{}) + } + }) +} diff --git a/spn/ships/connection_test.go b/spn/ships/connection_test.go index d41726459..b44ce74fb 100644 --- a/spn/ships/connection_test.go +++ b/spn/ships/connection_test.go @@ -5,6 +5,7 @@ import ( "fmt" "net" "sync" + "sync/atomic" "testing" "github.com/stretchr/testify/assert" @@ -13,14 +14,17 @@ import ( ) var ( - testPort uint16 = 65000 - testData = []byte("The quick brown fox jumps over the lazy dog") - localhost = net.IPv4(127, 0, 0, 1) + testPort atomic.Uint32 + testData = []byte("The quick brown fox jumps over the lazy dog") + localhost = net.IPv4(127, 0, 0, 1) ) +func init() { + testPort.Store(65000) +} + func getTestPort() uint16 { - testPort++ - return testPort + return uint16(testPort.Add(1)) //nolint:gosec // Test ports stay well below the uint16 limit. } func getTestBuf() []byte { diff --git a/spn/ships/http.go b/spn/ships/http.go index e4f20b2ed..570921090 100644 --- a/spn/ships/http.go +++ b/spn/ships/http.go @@ -2,6 +2,7 @@ package ships import ( "bufio" + "bytes" "context" "fmt" "io" @@ -121,7 +122,8 @@ func launchHTTPShip(ctx context.Context, transport *hub.Transport, ip net.IP) (S } // Receive HTTP response. - response, err := http.ReadResponse(bufio.NewReader(conn), request) + reader := bufio.NewReader(conn) + response, err := http.ReadResponse(reader, request) if err != nil { return nil, fmt.Errorf("failed to read HTTP response: %w", err) } @@ -153,9 +155,10 @@ func launchHTTPShip(ctx context.Context, transport *hub.Transport, ip net.IP) (S } // Create ship. + // The reader may already hold data the peer sent after the response. ship := &HTTPShip{ ShipBase: ShipBase{ - conn: conn, + conn: withBufferedData(conn, reader), transport: transport, mine: true, secure: false, @@ -194,11 +197,15 @@ func (pier *HTTPPier) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusSwitchingProtocols) // Get connection. - conn, _, err = hijacker.Hijack() + var bufrw *bufio.ReadWriter + conn, bufrw, err = hijacker.Hijack() if err != nil { log.Warningf("ships: failed to hijack http connection from %s: %s", r.RemoteAddr, err) return } + // The HTTP server may already have read data the client sent + // right after the request. + conn = withBufferedData(conn, bufrw.Reader) } else { http.Error(w, "", http.StatusInternalServerError) log.Warningf("ships: connection from %s cannot be hijacked", r.RemoteAddr) @@ -267,3 +274,34 @@ func (pier *HTTPPier) Abolish() { // Instead, remove the HTTP handler and the shared server will shutdown itself when needed. _ = removeHTTPHandler(pier.transport.Port, pier.transport.Path) } + +// bufferedConn is a connection whose first bytes were already read into a +// buffer, such as during an HTTP handshake. +type bufferedConn struct { + net.Conn + + reader io.Reader +} + +// Read reads the buffered data first and then from the connection. +func (c *bufferedConn) Read(b []byte) (int, error) { + return c.reader.Read(b) +} + +// withBufferedData returns conn, or a wrapper that first returns the data +// held in reader, if it holds any. reader must read from conn. +func withBufferedData(conn net.Conn, reader *bufio.Reader) net.Conn { + if reader == nil || reader.Buffered() == 0 { + return conn + } + return &bufferedConn{ + Conn: conn, + reader: io.MultiReader(bytes.NewReader(copyBuffered(reader)), conn), + } +} + +// copyBuffered returns a copy of the data buffered in reader. +func copyBuffered(reader *bufio.Reader) []byte { + data, _ := reader.Peek(reader.Buffered()) // Cannot fail for buffered data. + return bytes.Clone(data) +} diff --git a/spn/ships/http_shared.go b/spn/ships/http_shared.go index b174dfc2c..ba423eb9f 100644 --- a/spn/ships/http_shared.go +++ b/spn/ships/http_shared.go @@ -15,7 +15,8 @@ import ( ) type sharedServer struct { - server *http.Server + server *http.Server + listeners []net.Listener handlers map[string]http.HandlerFunc handlersLock sync.RWMutex @@ -23,11 +24,13 @@ type sharedServer struct { // ServeHTTP forwards requests to registered handler or uses defaults. func (shared *sharedServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { - shared.handlersLock.Lock() - defer shared.handlersLock.Unlock() - - // Get and forward to registered handler. + // Get the handler, but do not hold the lock while it runs: handlers may + // take long, and requests must not wait for each other. + shared.handlersLock.RLock() handler, ok := shared.handlers[r.URL.Path] + shared.handlersLock.RUnlock() + + // Forward to registered handler. if ok { handler(w, r) return @@ -110,6 +113,10 @@ func addHTTPHandler(port uint16, path string, handler http.HandlerFunc) error { Port: int(port), }) if err != nil { + // Close the listeners that were already opened. + for _, l := range listeners { + _ = l.Close() + } return fmt.Errorf("failed to listen: %w", err) } @@ -118,6 +125,7 @@ func addHTTPHandler(port uint16, path string, handler http.HandlerFunc) error { } // Add shared http server to list. + shared.listeners = listeners sharedHTTPServers[port] = shared // Start servers in service workers. @@ -126,7 +134,7 @@ func addHTTPHandler(port uint16, path string, handler http.HandlerFunc) error { fmt.Sprintf("shared http server listener on %s", serviceListener.Addr()), func(_ *mgr.WorkerCtx) error { err := shared.server.Serve(serviceListener) - if !errors.Is(http.ErrServerClosed, err) { + if !errors.Is(err, http.ErrServerClosed) { return err } return nil @@ -148,6 +156,30 @@ func removeHTTPHandler(port uint16, path string) error { path = "/" } + shared := detachHTTPHandler(port, path) + if shared == nil { + return nil + } + + // Shut the server down after releasing the locks, as shutting down waits + // for active requests, which need the handlers lock. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err := shared.server.Shutdown(ctx) + + // Shutdown only closes listeners the server already serves on, but the + // listener workers may not have started yet. Close all of them, so that + // the port is released now. + for _, listener := range shared.listeners { + _ = listener.Close() + } + return err +} + +// detachHTTPHandler removes the handler at path from the shared server of +// port. If no more handlers are registered, it also removes the shared server +// and returns it, so that the caller can shut it down. +func detachHTTPHandler(port uint16, path string) *sharedServer { sharedHTTPServersLock.Lock() defer sharedHTTPServersLock.Unlock() @@ -157,31 +189,16 @@ func removeHTTPHandler(port uint16, path string) error { return nil } - // Set path to handler. shared.handlersLock.Lock() defer shared.handlersLock.Unlock() - // Check if path is registered. - _, ok = shared.handlers[path] - if !ok { - return nil - } - - // Remove path from handler. + // Remove path from handlers. delete(shared.handlers, path) - - // Shutdown shared HTTP server if no more handlers are registered. - if len(shared.handlers) == 0 { - ctx, cancel := context.WithTimeout( - context.Background(), - 10*time.Second, - ) - defer cancel() - return shared.server.Shutdown(ctx) + if len(shared.handlers) > 0 { + return nil } - // Remove shared HTTP server from map. + // No more handlers are registered: remove the shared server. delete(sharedHTTPServers, port) - - return nil + return shared } diff --git a/spn/ships/http_shared_test.go b/spn/ships/http_shared_test.go index 190982643..d38ee5328 100644 --- a/spn/ships/http_shared_test.go +++ b/spn/ships/http_shared_test.go @@ -1,39 +1,116 @@ package ships import ( + "io" + "net" + "net/http" + "strconv" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestSharedHTTP(t *testing.T) { //nolint:paralleltest // Test checks global state. - _, err := New(struct{}{}) - if err != nil { - t.Errorf("failed to create module ships: %s", err) +const sharedHTTPTestPort = 65100 + +// requireSharedHTTPModule creates the module the shared HTTP servers run in, +// unless it already exists from a previous run of the tests. +func requireSharedHTTPModule(t *testing.T) { + t.Helper() + + if module != nil { + return } + _, err := New(struct{}{}) + require.NoError(t, err, "failed to create module ships") +} - const testPort = 65100 +func TestSharedHTTP(t *testing.T) { //nolint:paralleltest // Test checks global state. + requireSharedHTTPModule(t) // Register multiple handlers. - err = addHTTPHandler(testPort, "", ServeInfoPage) + err := addHTTPHandler(sharedHTTPTestPort, "", ServeInfoPage) require.NoError(t, err, "should be able to share http listener") - err = addHTTPHandler(testPort, "/test", ServeInfoPage) + err = addHTTPHandler(sharedHTTPTestPort, "/test", ServeInfoPage) require.NoError(t, err, "should be able to share http listener") - err = addHTTPHandler(testPort, "/test2", ServeInfoPage) + err = addHTTPHandler(sharedHTTPTestPort, "/test2", ServeInfoPage) require.NoError(t, err, "should be able to share http listener") - err = addHTTPHandler(testPort, "/", ServeInfoPage) + err = addHTTPHandler(sharedHTTPTestPort, "/", ServeInfoPage) require.Error(t, err, "should fail to register path twice") // Unregister - require.NoError(t, removeHTTPHandler(testPort, "")) - require.NoError(t, removeHTTPHandler(testPort, "/test")) - require.NoError(t, removeHTTPHandler(testPort, "/not-registered")) // removing unregistered handler does not error - require.NoError(t, removeHTTPHandler(testPort, "/test2")) - require.NoError(t, removeHTTPHandler(testPort, "/not-registered")) // removing unregistered handler does not error + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "")) + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "/test")) + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "/not-registered")) // removing unregistered handler does not error + + // The server must keep serving the remaining handler. + sharedHTTPServersLock.Lock() + _, ok := sharedHTTPServers[sharedHTTPTestPort] + sharedHTTPServersLock.Unlock() + assert.True(t, ok, "shared http server should remain while handlers are registered") + + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "/test2")) + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "/not-registered")) // removing unregistered handler does not error // Check if all handlers are gone again. sharedHTTPServersLock.Lock() - defer sharedHTTPServersLock.Unlock() assert.Empty(t, sharedHTTPServers, "shared http handlers should be back to zero") + sharedHTTPServersLock.Unlock() + + // The port must be released after the last handler is removed. + listener, err := net.Listen("tcp", ":"+strconv.Itoa(sharedHTTPTestPort)) + require.NoError(t, err, "port should be released after the last handler is removed") + _ = listener.Close() +} + +// TestSharedHTTPConcurrentRequests checks that a slow handler does not block +// requests to other handlers of the same shared server. +func TestSharedHTTPConcurrentRequests(t *testing.T) { //nolint:paralleltest // Test checks global state. + requireSharedHTTPModule(t) + + release := make(chan struct{}) + slowStarted := make(chan struct{}) + err := addHTTPHandler(sharedHTTPTestPort, "/slow", func(w http.ResponseWriter, _ *http.Request) { + close(slowStarted) + <-release + w.WriteHeader(http.StatusOK) + }) + require.NoError(t, err) + err = addHTTPHandler(sharedHTTPTestPort, "/fast", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) + require.NoError(t, err) + + baseURL := "http://127.0.0.1:" + strconv.Itoa(sharedHTTPTestPort) + client := &http.Client{Timeout: 5 * time.Second} + + // Start the slow request and wait until its handler runs. + slowDone := make(chan error, 1) + go func() { + resp, err := client.Get(baseURL + "/slow") //nolint:noctx // Client has a timeout. + if err == nil { + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + } + slowDone <- err + }() + select { + case <-slowStarted: + case <-time.After(5 * time.Second): + t.Fatal("slow handler did not start") + } + + // The fast request must complete while the slow one is still running. + fastClient := &http.Client{Timeout: 2 * time.Second} + resp, err := fastClient.Get(baseURL + "/fast") //nolint:noctx // Client has a timeout. + if err == nil { + _ = resp.Body.Close() + } + close(release) + require.NoError(t, err, "request to another handler should not wait for the slow handler") + require.NoError(t, <-slowDone) + + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "/slow")) + require.NoError(t, removeHTTPHandler(sharedHTTPTestPort, "/fast")) } diff --git a/spn/ships/http_test.go b/spn/ships/http_test.go index 5bcf51640..4dc102ff2 100644 --- a/spn/ships/http_test.go +++ b/spn/ships/http_test.go @@ -1,14 +1,20 @@ package ships import ( + "bufio" "context" + "io" "net" + "net/http" + "net/http/httptest" "testing" "time" "github.com/safing/portmaster/spn/hub" ) +const httpProtocol = "http" + // TestHTTPShipUnresponsivePeer checks that launching an HTTP ship does not // hang when the peer accepts the connection but never answers the upgrade. func TestHTTPShipUnresponsivePeer(t *testing.T) { @@ -39,7 +45,7 @@ func TestHTTPShipUnresponsivePeer(t *testing.T) { t.Fatalf("unexpected listener address type %T", listener.Addr()) } transport := &hub.Transport{ - Protocol: "http", + Protocol: httpProtocol, Port: uint16(listenAddr.Port), //nolint:gosec // Port is always in range. } @@ -89,3 +95,99 @@ func TestHTTPShipUnresponsivePeer(t *testing.T) { }) } } + +// TestHTTPPierKeepsDataSentWithRequest checks that the pier does not lose data +// the client sends in the same packet as the upgrade request. +func TestHTTPPierKeepsDataSentWithRequest(t *testing.T) { + t.Parallel() + + dockingRequests := make(chan Ship, 1) + pier := &HTTPPier{ + PierBase: PierBase{ + transport: &hub.Transport{Protocol: "http"}, + dockingRequests: dockingRequests, + }, + } + server := httptest.NewServer(pier) + t.Cleanup(server.Close) + + conn, err := net.Dial("tcp", server.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + + payload := "SPN payload sent right after the request" + _, err = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: test\r\nConnection: Upgrade\r\nUpgrade: SPN\r\n\r\n"+payload) + if err != nil { + t.Fatal(err) + } + + var ship Ship + select { + case ship = <-dockingRequests: + case <-time.After(5 * time.Second): + t.Fatal("no docking request") + } + t.Cleanup(ship.Sink) + + readPayload(t, ship.(*HTTPShip).conn, payload) //nolint:forcetypeassert +} + +// TestHTTPShipKeepsDataSentWithResponse checks that the ship does not lose data +// the server sends in the same packet as the upgrade response. +func TestHTTPShipKeepsDataSentWithResponse(t *testing.T) { + t.Parallel() + + payload := "SPN payload sent right after the response" + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + conn, err := listener.Accept() + if err != nil { + return + } + t.Cleanup(func() { _ = conn.Close() }) + // Read the request, then reply and send the payload in one write. + _, err = http.ReadRequest(bufio.NewReader(conn)) + if err != nil { + return + } + _, _ = io.WriteString(conn, "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: SPN\r\n\r\n"+payload) + }() + + listenAddr, ok := listener.Addr().(*net.TCPAddr) + if !ok { + t.Fatalf("unexpected listener address type %T", listener.Addr()) + } + transport := &hub.Transport{ + Protocol: httpProtocol, + Port: uint16(listenAddr.Port), //nolint:gosec // Port is always in range. + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ship, err := launchHTTPShip(ctx, transport, localhost) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ship.Sink) + + readPayload(t, ship.(*HTTPShip).conn, payload) //nolint:forcetypeassert +} + +func readPayload(t *testing.T, conn net.Conn, want string) { + t.Helper() + + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + got := make([]byte, len(want)) + _, err := io.ReadFull(conn, got) + if err != nil { + t.Fatalf("failed to read payload: %s (got %q)", err, got) + } + if string(got) != want { + t.Fatalf("got payload %q, want %q", got, want) + } +} diff --git a/spn/ships/testship.go b/spn/ships/testship.go index 6ec74b6e7..479bfc971 100644 --- a/spn/ships/testship.go +++ b/spn/ships/testship.go @@ -145,10 +145,10 @@ func (ship *TestShip) Sink() { // Dummy methods to conform to interface for testing. -func (ship *TestShip) LocalAddr() net.Addr { return nil } //nolint:golint -func (ship *TestShip) RemoteAddr() net.Addr { return nil } //nolint:golint -func (ship *TestShip) Public() bool { return true } //nolint:golint -func (ship *TestShip) MarkPublic() {} //nolint:golint -func (ship *TestShip) MaskAddress(addr net.Addr) string { return addr.String() } //nolint:golint -func (ship *TestShip) MaskIP(ip net.IP) string { return ip.String() } //nolint:golint -func (ship *TestShip) Mask(value []byte) string { return base58.Encode(value) } //nolint:golint +func (ship *TestShip) LocalAddr() net.Addr { return nil } +func (ship *TestShip) RemoteAddr() net.Addr { return nil } +func (ship *TestShip) Public() bool { return true } +func (ship *TestShip) MarkPublic() {} +func (ship *TestShip) MaskAddress(addr net.Addr) string { return addr.String() } +func (ship *TestShip) MaskIP(ip net.IP) string { return ip.String() } +func (ship *TestShip) Mask(value []byte) string { return base58.Encode(value) } diff --git a/spn/sluice/abandon_test.go b/spn/sluice/abandon_test.go new file mode 100644 index 000000000..0e6cfb4e3 --- /dev/null +++ b/spn/sluice/abandon_test.go @@ -0,0 +1,103 @@ +package sluice + +import ( + "net" + "sync" + "testing" + "time" + + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/packet" + "github.com/safing/portmaster/spn/crew" +) + +func newTestSluice() *Sluice { + // The network name is not registered, so abandoning does not touch the registry. + return &Sluice{network: "test", pendingRequests: make(map[string]*Request)} +} + +func newTestPendingConn(port uint16) *network.Connection { + return &network.Connection{ + ID: "test-conn", + IPVersion: packet.IPv4, + IPProtocol: packet.TCP, + LocalIP: net.IPv4(127, 0, 0, 1), + LocalPort: port, + Verdict: network.VerdictRerouteToTunnel, + } +} + +// TestAbandonCallbackHoldsConnLock checks that abandoning a sluice fails the +// pending connections with the connection lock held, so that concurrent +// readers (packet handler, API) do not race with it. Run with -race. +func TestAbandonCallbackHoldsConnLock(t *testing.T) { + t.Parallel() + + s := newTestSluice() + conn := newTestPendingConn(50001) + err := s.AwaitRequest(&Request{ConnInfo: conn, CallbackFn: crew.HandleSluiceRequest}) + if err != nil { + t.Fatal(err) + } + + // Concurrent reader, as e.g. the packet handler of the next packet. + var wg sync.WaitGroup + wg.Go(func() { + conn.Lock() + defer conn.Unlock() + _ = conn.Verdict + _ = conn.Reason.Msg + }) + + s.abandon() + wg.Wait() + + conn.Lock() + defer conn.Unlock() + if conn.Verdict != network.VerdictFailed { + t.Fatalf("expected verdict failed, got %s", conn.Verdict) + } +} + +// TestAbandonDoesNotDeadlockWithAwaitRequest reproduces the lock order of the +// firewall: AwaitRequest is called with the connection lock held. Abandon must +// therefore not hold the sluice lock while the callback takes a connection lock. +func TestAbandonDoesNotDeadlockWithAwaitRequest(t *testing.T) { + t.Parallel() + + s := newTestSluice() + pending := newTestPendingConn(50002) + err := s.AwaitRequest(&Request{ConnInfo: pending, CallbackFn: crew.HandleSluiceRequest}) + if err != nil { + t.Fatal(err) + } + + // Firewall: holds the pending connection's lock (e.g. handling its next + // packet) and waits for the sluice lock to register a request. + pending.Lock() + abandonDone := make(chan struct{}) + go func() { + defer close(abandonDone) + s.abandon() + }() + // Give abandon time to take the sluice lock and block in the callback. + time.Sleep(50 * time.Millisecond) + + awaitDone := make(chan struct{}) + go func() { + defer close(awaitDone) + _ = s.AwaitRequest(&Request{ConnInfo: newTestPendingConn(50003), CallbackFn: crew.HandleSluiceRequest}) + pending.Unlock() + }() + + select { + case <-awaitDone: + case <-time.After(5 * time.Second): + t.Fatal("deadlock: AwaitRequest blocked on sluice lock held by abandon") + } + select { + case <-abandonDone: + case <-time.After(5 * time.Second): + t.Fatal("abandon did not finish") + } +} diff --git a/spn/sluice/lifecycle_test.go b/spn/sluice/lifecycle_test.go new file mode 100644 index 000000000..a649c2a36 --- /dev/null +++ b/spn/sluice/lifecycle_test.go @@ -0,0 +1,233 @@ +package sluice + +import ( + "bytes" + "errors" + "io" + "net" + "testing" + "time" + + "github.com/tevino/abool" + + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/packet" +) + +// startTestSluice starts a sluice on loopback and returns it once it listens. +func startTestSluice(t *testing.T, networkName string) (*Sluice, net.Addr) { + t.Helper() + + setTestModule(t) + + StartSluice(networkName, "127.0.0.1:0") + var s *Sluice + waitFor(t, func() bool { + var ok bool + s, ok = getSluice(networkName) + return ok + }) + s.lock.Lock() + defer s.lock.Unlock() + return s, s.listener.Addr() +} + +func setDeadline(t *testing.T, conn net.Conn) { + t.Helper() + + err := conn.SetDeadline(time.Now().Add(5 * time.Second)) + if err != nil { + t.Fatal(err) + } +} + +func TestUDPSluiceLifecycle(t *testing.T) { //nolint:paralleltest // Uses global module state. + _, sluiceAddr := startTestSluice(t, "udp4") + + // Prepare app socket. + app, err := net.DialUDP("udp4", nil, sluiceAddr.(*net.UDPAddr)) //nolint:forcetypeassert + if err != nil { + t.Fatal(err) + } + defer func() { _ = app.Close() }() + setDeadline(t, app) + appAddr := app.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + + // Register request for the app socket. + accepted := make(chan net.Conn, 1) + err = AwaitRequest( + testConnInfo(packet.UDP, appAddr.IP, uint16(appAddr.Port)), //nolint:gosec // Port is always in range. + func(_ *network.Connection, conn net.Conn) { accepted <- conn }, + ) + if err != nil { + t.Fatal(err) + } + + // Send first packet and get connection. + _, err = app.Write([]byte("ping")) + if err != nil { + t.Fatal(err) + } + var conn net.Conn + select { + case conn = <-accepted: + case <-time.After(5 * time.Second): + t.Fatal("request callback not called") + } + if conn == nil { + t.Fatal("got nil conn") + } + + // Read first packet. + buf := make([]byte, 100) + n, err := conn.Read(buf) + if err != nil || string(buf[:n]) != "ping" { + t.Fatalf("unexpected read: %q, %v", buf[:n], err) + } + + // Reply. + _, err = conn.Write([]byte("pong")) + if err != nil { + t.Fatal(err) + } + n, err = app.Read(buf) + if err != nil || string(buf[:n]) != "pong" { + t.Fatalf("unexpected app read: %q, %v", buf[:n], err) + } + + // Read a packet in parts. + _, err = app.Write([]byte("abcdef")) + if err != nil { + t.Fatal(err) + } + small := make([]byte, 4) + n, err = conn.Read(small) + if err != nil || string(small[:n]) != "abcd" { + t.Fatalf("unexpected partial read: %q, %v", small[:n], err) + } + n, err = conn.Read(small) + if err != nil || string(small[:n]) != "ef" { + t.Fatalf("unexpected rest read: %q, %v", small[:n], err) + } + + // Close connection. + err = conn.Close() + if err != nil { + t.Fatal(err) + } + _, err = conn.Read(buf) + if !errors.Is(err, io.EOF) { + t.Fatalf("expected EOF after close, got %v", err) + } + _, err = conn.Write([]byte("x")) + if err == nil { + t.Fatal("expected error when writing to closed conn") + } +} + +func TestUDPSluiceWithoutRequest(t *testing.T) { //nolint:paralleltest // Uses global module state. + _, sluiceAddr := startTestSluice(t, "udp4") + + app, err := net.DialUDP("udp4", nil, sluiceAddr.(*net.UDPAddr)) //nolint:forcetypeassert + if err != nil { + t.Fatal(err) + } + defer func() { _ = app.Close() }() + setDeadline(t, app) + + _, err = app.Write([]byte("hello")) + if err != nil { + t.Fatal(err) + } + buf := make([]byte, 1024) + n, err := app.Read(buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(buf[:n], entrypointInfoMsg) { + t.Fatalf("unexpected reply: %q", buf[:n]) + } +} + +func TestTCPSluiceWithoutRequest(t *testing.T) { //nolint:paralleltest // Uses global module state. + _, sluiceAddr := startTestSluice(t, "tcp4") + + app, err := net.Dial("tcp4", sluiceAddr.String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = app.Close() }() + setDeadline(t, app) + + reply, err := io.ReadAll(app) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(reply, entrypointInfoMsg) { + t.Fatalf("unexpected reply: %q", reply) + } +} + +func TestSluiceAbandonNotifiesPendingRequests(t *testing.T) { //nolint:paralleltest // Uses global module state. + s, _ := startTestSluice(t, "tcp4") + + notified := make(chan net.Conn, 1) + err := AwaitRequest( + testConnInfo(packet.TCP, net.IPv4(127, 0, 0, 1), 1), + func(_ *network.Connection, conn net.Conn) { notified <- conn }, + ) + if err != nil { + t.Fatal(err) + } + + s.abandon() + select { + case conn := <-notified: + if conn != nil { + t.Fatal("expected nil conn on abandon") + } + default: + t.Fatal("pending request was not notified") + } + _, ok := getSluice("tcp4") + if ok { + t.Fatal("abandoned sluice is still registered") + } +} + +func TestUDPListenerCleanInactiveConns(t *testing.T) { + t.Parallel() + + ln := &UDPListener{ + closed: abool.New(), + closing: make(chan struct{}), + newConns: make(chan *UDPConn), + conns: make(map[string]*UDPConn), + } + conn := &UDPConn{ + ln: ln, + addr: &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1}, + closed: abool.New(), + closing: make(chan struct{}), + in: make(chan []byte, 1), + inactivityCnt: new(uint32), + } + ln.setConn(conn) + + for range 10 { + ln.cleanInactiveConns(10) + } + if conn.closed.IsSet() { + t.Fatal("conn closed too early") + } + ln.cleanInactiveConns(10) + if !conn.closed.IsSet() { + t.Fatal("inactive conn not closed") + } + for range 10 { + ln.cleanInactiveConns(10) + } + if _, ok := ln.getConn(conn.addr.String()); ok { + t.Fatal("inactive conn not removed") + } +} diff --git a/spn/sluice/listener_test.go b/spn/sluice/listener_test.go new file mode 100644 index 000000000..ac57cc9a1 --- /dev/null +++ b/spn/sluice/listener_test.go @@ -0,0 +1,119 @@ +package sluice + +import ( + "net" + "testing" + "time" + + "github.com/tevino/abool" +) + +// runCatchingPanic runs fn and returns the recovered panic value, if any. +func runCatchingPanic(fn func()) (recovered any) { + defer func() { + recovered = recover() + }() + fn() + return nil +} + +// waitFor polls cond until it returns true or the timeout is reached. +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for condition") + } + time.Sleep(time.Millisecond) + } +} + +// testableListener abstracts the UDP and the packet listener for tests. +type testableListener interface { + net.Listener + hasConn(remoteAddr string) bool + runReader() +} + +func (ln *UDPListener) hasConn(remoteAddr string) bool { + _, ok := ln.getConn(remoteAddr) + return ok +} +func (ln *UDPListener) runReader() { _ = ln.reader(nil) } + +func (ln *PacketListener) hasConn(remoteAddr string) bool { + _, ok := ln.getConn(remoteAddr) + return ok +} +func (ln *PacketListener) runReader() { _ = ln.reader(nil) } + +// testCloseDuringHandover closes the listener while the reader is handing a +// new connection to Accept, which must not panic. +func testCloseDuringHandover(t *testing.T, ln testableListener) { + t.Helper() + + readerPanic := make(chan any, 1) + go func() { + readerPanic <- runCatchingPanic(ln.runReader) + }() + + // Send a packet from a new peer, but do not accept it. + peer, err := net.DialUDP("udp4", nil, ln.Addr().(*net.UDPAddr)) //nolint:forcetypeassert + if err != nil { + t.Fatal(err) + } + defer func() { _ = peer.Close() }() + _, err = peer.Write([]byte("hello")) + if err != nil { + t.Fatal(err) + } + waitFor(t, func() bool { return ln.hasConn(peer.LocalAddr().String()) }) + + // Close the listener while the reader is (about to be) blocked handing over. + err = ln.Close() + if err != nil { + t.Fatal(err) + } + if p := <-readerPanic; p != nil { + t.Fatalf("reader panicked: %v", p) + } + _, err = ln.Accept() + if err == nil { + t.Fatal("expected error from Accept on closed listener") + } +} + +func TestUDPListenerCloseDuringHandover(t *testing.T) { + t.Parallel() + + sock, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + testCloseDuringHandover(t, &UDPListener{ + sock: sock, + closed: abool.New(), + closing: make(chan struct{}), + newConns: make(chan *UDPConn), + oobSize: 32, + conns: make(map[string]*UDPConn), + }) +} + +func TestPacketListenerCloseDuringHandover(t *testing.T) { + t.Parallel() + + sock, err := net.ListenPacket("udp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + testCloseDuringHandover(t, &PacketListener{ + sock: sock, + closed: abool.New(), + closing: make(chan struct{}), + newConns: make(chan *PacketConn), + conns: make(map[string]*PacketConn), + }) +} diff --git a/spn/sluice/packet_listener.go b/spn/sluice/packet_listener.go index a20fcefff..27e5208f5 100644 --- a/spn/sluice/packet_listener.go +++ b/spn/sluice/packet_listener.go @@ -16,6 +16,7 @@ import ( type PacketListener struct { sock net.PacketConn closed *abool.AtomicBool + closing chan struct{} newConns chan *PacketConn lock sync.Mutex @@ -35,6 +36,7 @@ func ListenPacket(network, address string) (net.Listener, error) { ln := &PacketListener{ sock: sock, closed: abool.New(), + closing: make(chan struct{}), newConns: make(chan *PacketConn), conns: make(map[string]*PacketConn), } @@ -46,9 +48,10 @@ func ListenPacket(network, address string) (net.Listener, error) { // Accept waits for and returns the next connection to the listener. func (ln *PacketListener) Accept() (net.Conn, error) { - conn := <-ln.newConns - if conn != nil { + select { + case conn := <-ln.newConns: return conn, nil + case <-ln.closing: } // Check if there is a socket error. @@ -68,8 +71,9 @@ func (ln *PacketListener) Close() error { return nil } - // Close all channels. - close(ln.newConns) + // Signal closing and close all connection channels. + // newConns is never closed, as the reader might be sending on it. + close(ln.closing) ln.lock.Lock() defer ln.lock.Unlock() for _, conn := range ln.conns { @@ -116,23 +120,13 @@ func (ln *PacketListener) reader(_ *mgr.WorkerCtx) error { } buf = buf[:n] - // Get connection and supply data. - conn, ok := ln.getConn(addr.String()) - if ok { - // Ignore if conn is closed. - if conn.closed.IsSet() { - continue - } - - select { - case conn.in <- buf: - default: - } + // Supply data to existing connection. + if ln.supplyData(addr.String(), buf) { continue } // Or create a new connection. - conn = &PacketConn{ + conn := &PacketConn{ ln: ln, addr: addr, closed: abool.New(), @@ -142,8 +136,36 @@ func (ln *PacketListener) reader(_ *mgr.WorkerCtx) error { inactivityCnt: new(uint32), } ln.setConn(conn) - ln.newConns <- conn + select { + case ln.newConns <- conn: + case <-ln.closing: + } + } +} + +// supplyData supplies the given data to an existing connection and reports +// whether a connection exists for the given remote address. +// The send happens under the lock so that it cannot race with Close closing +// the connection's channel. +func (ln *PacketListener) supplyData(remoteAddr string, data []byte) (connExists bool) { + ln.lock.Lock() + defer ln.lock.Unlock() + + conn, ok := ln.conns[remoteAddr] + if !ok { + return false + } + + // Ignore if conn or listener is closed. + if conn.closed.IsSet() || ln.closed.IsSet() { + return true + } + + select { + case conn.in <- data: + default: } + return true } func (ln *PacketListener) cleaner(ctx *mgr.WorkerCtx) error { diff --git a/spn/sluice/sluice.go b/spn/sluice/sluice.go index 8c993c3ac..a8f76e577 100644 --- a/spn/sluice/sluice.go +++ b/spn/sluice/sluice.go @@ -1,6 +1,7 @@ package sluice import ( + "context" "fmt" "net" "strconv" @@ -63,9 +64,11 @@ func (s *Sluice) AwaitRequest(r *Request) error { defer s.lock.Unlock() // Check if a pending request already exists for this local address. + // Expired requests are only cleaned up when a connection is accepted, so + // replace them here instead of blocking new requests for the address. key := net.JoinHostPort(r.ConnInfo.LocalIP.String(), strconv.Itoa(int(r.ConnInfo.LocalPort))) - _, exists := s.pendingRequests[key] - if exists { + existing, exists := s.pendingRequests[key] + if exists && !time.Now().After(existing.Expires) { return fmt.Errorf("a pending request for %s already exists", key) } @@ -79,10 +82,16 @@ func (s *Sluice) getRequest(address string) (r *Request, ok bool) { defer s.lock.Unlock() r, ok = s.pendingRequests[address] - if ok { - delete(s.pendingRequests, address) + if !ok { + return nil, false + } + delete(s.pendingRequests, address) + + // Do not hand connections to expired requests. + if time.Now().After(r.Expires) { + return nil, false } - return + return r, true } func (s *Sluice) init() error { @@ -105,10 +114,21 @@ func (s *Sluice) init() error { } func (s *Sluice) abandon() { + pending := s.abandonLocked() + + // Notify pending requests outside of the sluice lock, as the callback + // locks the connection and AwaitRequest is called with the connection + // lock held. + for _, r := range pending { + r.CallbackFn(r.ConnInfo, nil) + } +} + +func (s *Sluice) abandonLocked() []*Request { s.lock.Lock() defer s.lock.Unlock() if s.abandoned { - return + return nil } s.abandoned = true @@ -120,11 +140,13 @@ func (s *Sluice) abandon() { _ = s.listener.Close() } - // Notify pending requests. + // Take pending requests. + pending := make([]*Request, 0, len(s.pendingRequests)) for i, r := range s.pendingRequests { - r.CallbackFn(r.ConnInfo, nil) + pending = append(pending, r) delete(s.pendingRequests, i) } + return pending } func (s *Sluice) handleConnection(conn net.Conn) { @@ -188,13 +210,19 @@ func (s *Sluice) handleConnection(conn net.Conn) { success = true } -func (s *Sluice) listenHandler(_ *mgr.WorkerCtx) error { +func (s *Sluice) listenHandler(wc *mgr.WorkerCtx) error { defer s.abandon() err := s.init() if err != nil { return err } + // Also abandon (and thus close the listener) when the worker is canceled. + // The module's stop function only abandons registered sluices, so a sluice + // that registers after stop ran would otherwise block in Accept forever. + stopAbandonOnCancel := context.AfterFunc(wc.Ctx(), s.abandon) + defer stopAbandonOnCancel() + // Handle new connections. log.Infof("spn/sluice: started listening for %s requests on %s", s.network, s.listener.Addr()) for { diff --git a/spn/sluice/sluice_test.go b/spn/sluice/sluice_test.go new file mode 100644 index 000000000..6c280fed9 --- /dev/null +++ b/spn/sluice/sluice_test.go @@ -0,0 +1,127 @@ +package sluice + +import ( + "net" + "testing" + "time" + + "github.com/safing/portmaster/service/intel" + "github.com/safing/portmaster/service/mgr" + "github.com/safing/portmaster/service/network" + "github.com/safing/portmaster/service/network/packet" +) + +// setTestModule installs a fresh module manager for tests. +func setTestModule(t *testing.T) *mgr.Manager { + t.Helper() + + m := mgr.New("sluice-test") + module = &SluiceModule{mgr: m} + t.Cleanup(func() { + stopAllSluices() + m.Cancel() + if !m.WaitForWorkers(5 * time.Second) { + t.Error("sluice workers did not stop") + } + }) + return m +} + +// TestSluiceStopBeforeListen simulates the module being stopped (Stop and +// Cancel) before the listener worker got to create its listener. The worker +// must still finish and release the listener. +func TestSluiceStopBeforeListen(t *testing.T) { //nolint:paralleltest // Uses global module state. + m := setTestModule(t) + + s := &Sluice{ + network: "tcp4", + address: "127.0.0.1:0", + createListener: net.Listen, + pendingRequests: make(map[string]*Request), + } + + // Module stop: Stop() (nothing registered yet), then Cancel(). + stopAllSluices() + m.Cancel() + + // Worker only starts now. + m.Go("test sluice listener", s.listenHandler) + // Wait until the worker has created its listener (and thus is registered + // as a running worker). + waitFor(t, func() bool { + s.lock.Lock() + defer s.lock.Unlock() + return s.listener != nil + }) + done := m.WaitForWorkers(2 * time.Second) + if !done { + s.abandon() // Release the leaked worker. + t.Fatal("sluice listener worker did not stop after module stop") + } +} + +func testConnInfo(proto packet.IPProtocol, localIP net.IP, localPort uint16) *network.Connection { + return &network.Connection{ + IPVersion: packet.IPv4, + IPProtocol: proto, + LocalIP: localIP, + LocalPort: localPort, + Entity: &intel.Entity{}, + } +} + +// TestExpiredRequestIsNotUsed checks that an expired pending request neither +// blocks a new request for the same local address nor is handed a new +// connection. +func TestExpiredRequestIsNotUsed(t *testing.T) { + t.Parallel() + + s := &Sluice{ + network: "udp4", + pendingRequests: make(map[string]*Request), + } + localIP := net.IPv4(127, 0, 0, 1) + const key = "127.0.0.1:40000" + noop := func(*network.Connection, net.Conn) {} + + stale := &Request{ + ConnInfo: testConnInfo(packet.UDP, localIP, 40000), + CallbackFn: noop, + Expires: time.Now().Add(-time.Second), + } + err := s.AwaitRequest(stale) + if err != nil { + t.Fatal(err) + } + + // Expired request must not be returned. + r, ok := s.getRequest(key) + if ok { + t.Fatalf("got expired request %p", r) + } + + // Re-add the stale one and check that a new request replaces it. + s.pendingRequests[key] = stale + fresh := &Request{ + ConnInfo: testConnInfo(packet.UDP, localIP, 40000), + CallbackFn: noop, + } + err = s.AwaitRequest(fresh) + if err != nil { + t.Fatalf("new request blocked by expired one: %s", err) + } + r, ok = s.getRequest(key) + if !ok || r != fresh { + t.Fatal("expected fresh request to be returned") + } + + // A non-expired request must still block duplicates. + err = s.AwaitRequest(fresh) + if err != nil { + t.Fatal(err) + } + err = s.AwaitRequest(&Request{ConnInfo: fresh.ConnInfo, CallbackFn: noop}) + if err == nil { + t.Fatal("expected duplicate request to be rejected") + } +} diff --git a/spn/sluice/udp_listener.go b/spn/sluice/udp_listener.go index 2f0ab03f2..8ad58b301 100644 --- a/spn/sluice/udp_listener.go +++ b/spn/sluice/udp_listener.go @@ -21,6 +21,7 @@ const onWindows = runtime.GOOS == "windows" type UDPListener struct { sock *net.UDPConn closed *abool.AtomicBool + closing chan struct{} newConns chan *UDPConn oobSize int @@ -53,6 +54,7 @@ func ListenUDP(network, address string) (net.Listener, error) { ln := &UDPListener{ sock: sock, closed: abool.New(), + closing: make(chan struct{}), newConns: make(chan *UDPConn), oobSize: oobSize, conns: make(map[string]*UDPConn), @@ -73,9 +75,10 @@ func ListenUDP(network, address string) (net.Listener, error) { // Accept waits for and returns the next connection to the listener. func (ln *UDPListener) Accept() (net.Conn, error) { - conn := <-ln.newConns - if conn != nil { + select { + case conn := <-ln.newConns: return conn, nil + case <-ln.closing: } // Check if there is a socket error. @@ -95,8 +98,9 @@ func (ln *UDPListener) Close() error { return nil } - // Close all channels. - close(ln.newConns) + // Signal closing and close all connection channels. + // newConns is never closed, as the reader might be sending on it. + close(ln.closing) ln.lock.Lock() defer ln.lock.Unlock() for _, conn := range ln.conns { @@ -150,23 +154,13 @@ func (ln *UDPListener) reader(_ *mgr.WorkerCtx) error { buf = buf[:n] oob = oob[:oobn] - // Get connection and supply data. - conn, ok := ln.getConn(addr.String()) - if ok { - // Ignore if conn is closed. - if conn.closed.IsSet() { - continue - } - - select { - case conn.in <- buf: - default: - } + // Supply data to existing connection. + if ln.supplyData(addr.String(), buf) { continue } // Or create a new connection. - conn = &UDPConn{ + conn := &UDPConn{ ln: ln, addr: addr, oob: oob, @@ -177,8 +171,36 @@ func (ln *UDPListener) reader(_ *mgr.WorkerCtx) error { inactivityCnt: new(uint32), } ln.setConn(conn) - ln.newConns <- conn + select { + case ln.newConns <- conn: + case <-ln.closing: + } + } +} + +// supplyData supplies the given data to an existing connection and reports +// whether a connection exists for the given remote address. +// The send happens under the lock so that it cannot race with Close closing +// the connection's channel. +func (ln *UDPListener) supplyData(remoteAddr string, data []byte) (connExists bool) { + ln.lock.Lock() + defer ln.lock.Unlock() + + conn, ok := ln.conns[remoteAddr] + if !ok { + return false + } + + // Ignore if conn or listener is closed. + if conn.closed.IsSet() || ln.closed.IsSet() { + return true + } + + select { + case conn.in <- data: + default: } + return true } func (ln *UDPListener) cleaner(ctx *mgr.WorkerCtx) error { diff --git a/spn/terminal/block.go b/spn/terminal/block.go new file mode 100644 index 000000000..dca9b75e6 --- /dev/null +++ b/spn/terminal/block.go @@ -0,0 +1,35 @@ +package terminal + +import ( + "encoding/binary" + "errors" + + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// ErrBlockTooBig is returned by GetNextBlock if the block size exceeds the +// data that is available. +var ErrBlockTooBig = errors.New("block size exceeds available data") + +// GetNextBlock is like container.GetNextBlock, but checks the block size +// before reading the block. +// +// container.GetNextBlock allocates the received block size before checking +// that the data is there, so a crafted size (eg. 1<<42) in data received from +// the network makes it allocate terabytes, which crashes the process with an +// unrecoverable "out of memory" fatal error. Always use this function for +// data received from other parties. +func GetNextBlock(c *container.Container) ([]byte, error) { + if c.Length() == 0 { + return nil, varint.ErrBufTooSmall + } + blockSize, n, err := varint.Unpack64(c.Peek(binary.MaxVarintLen64)) + if err != nil { + return nil, err + } + if available := c.Length() - n; available < 0 || blockSize > uint64(available) { + return nil, ErrBlockTooBig + } + return c.GetNextBlock() +} diff --git a/spn/terminal/block_test.go b/spn/terminal/block_test.go new file mode 100644 index 000000000..81047b8c4 --- /dev/null +++ b/spn/terminal/block_test.go @@ -0,0 +1,74 @@ +package terminal + +import ( + "bytes" + "errors" + "testing" + + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// TestGetNextBlockChecksSize checks that a block with a crafted size is +// rejected without allocating that size. container.GetNextBlock crashes the +// process with "fatal error: runtime: out of memory" on the large sizes. +func TestGetNextBlockChecksSize(t *testing.T) { + t.Parallel() + + for _, size := range []uint64{1 << 42, 1 << 62, 1<<64 - 1, 4} { + _, err := GetNextBlock(container.New(varint.Pack64(size), []byte("abc"))) + if !errors.Is(err, ErrBlockTooBig) { + t.Errorf("block size %d: expected ErrBlockTooBig, got %v", size, err) + } + } + + // Empty and exhausted containers must fail without panicking. + _, err := GetNextBlock(container.New()) + if err == nil { + t.Error("empty container: expected error") + } + c := container.New([]byte{1, 'a'}) + _, err = GetNextBlock(c) + if err != nil { + t.Fatal(err) + } + _, err = GetNextBlock(c) + if err == nil { + t.Error("exhausted container: expected error") + } + + // Valid blocks parse as before, also across compartments. + c = container.New() + c.AppendAsBlock([]byte("first")) + c.Append(varint.Pack64(6)) + c.Append([]byte("sec")) + c.Append([]byte("ond")) + c.AppendAsBlock(nil) + for _, expected := range []string{"first", "second", ""} { + data, err := GetNextBlock(c) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(data, []byte(expected)) { + t.Errorf("expected block %q, got %q", expected, data) + } + } +} + +// TestOperationStartWithHugeOpTypeSize checks that an operation start with a +// crafted op type block size stops the operation instead of crashing. +func TestOperationStartWithHugeOpTypeSize(t *testing.T) { + t.Parallel() + + a, _, err := NewSimpleTestTerminalPair(0, 10, nil) + if err != nil { + t.Fatal(err) + } + defer a.Abandon(nil) + + // Before the size check, this crashed the whole process. + a.handleOperationStart(8, container.New(varint.Pack64(1<<42), []byte("abc"))) + if _, ok := a.GetActiveOp(8); ok { + t.Fatal("operation with malformed init data was started") + } +} diff --git a/spn/terminal/control_flow.go b/spn/terminal/control_flow.go index 8da522ee7..452369876 100644 --- a/spn/terminal/control_flow.go +++ b/spn/terminal/control_flow.go @@ -3,6 +3,7 @@ package terminal import ( "context" "fmt" + "math" "sync" "sync/atomic" "time" @@ -180,6 +181,20 @@ func (dfq *DuplexFlowQueue) reportableRecvSpace() int32 { return 0 } + // The receiver parses reported space as a 16 bit number, so never report + // more than that in one message. The remainder is not added to the reported + // space and is thus reported with the next report. + if toReport > math.MaxUint16 { + toReport = math.MaxUint16 + + // Make sure the remainder is reported soon, even if no more data is + // received. + select { + case dfq.forceSpaceReport <- struct{}{}: + default: + } + } + // Add space to report to dfq.reportedSpace and return it. atomic.AddInt32(dfq.reportedSpace, toReport) return toReport diff --git a/spn/terminal/control_flow_test.go b/spn/terminal/control_flow_test.go new file mode 100644 index 000000000..fd0b26864 --- /dev/null +++ b/spn/terminal/control_flow_test.go @@ -0,0 +1,55 @@ +package terminal + +import ( + "context" + "math" + "sync/atomic" + "testing" + "time" + + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// TestFlowQueueSpaceReportLimit checks that a space report always fits the 16 +// bit number the receiving side parses, without losing any space. +func TestFlowQueueSpaceReportLimit(t *testing.T) { + t.Parallel() + + const queueSize = 200_000 // Allowed up to MaxQueueSize. + + dfq := NewDuplexFlowQueue(context.Background(), queueSize, func(*Msg, time.Duration) {}) + // Pretend all of the initially reported space was used up by the other end. + atomic.StoreInt32(dfq.reportedSpace, 0) + + var total int64 + for range 10 { + report := dfq.reportableRecvSpace() + if report == 0 { + break + } + if report > math.MaxUint16 { + t.Fatalf("reported space %d does not fit into 16 bits", report) + } + + // The receiving side must be able to parse the report. + c := container.New(varint.Pack64(uint64(report))) //nolint:gosec // Checked to be positive above. + parsed, err := c.GetNextN16() + if err != nil { + t.Fatalf("failed to parse report of %d: %s", report, err) + } + if int32(parsed) != report { + t.Fatalf("parsed %d, reported %d", parsed, report) + } + + total += int64(report) + } + + // No space must be lost. + if total != queueSize { + t.Fatalf("reported %d in total, expected %d", total, queueSize) + } + if got := atomic.LoadInt32(dfq.reportedSpace); got != queueSize { + t.Fatalf("reportedSpace is %d, expected %d", got, queueSize) + } +} diff --git a/spn/terminal/init.go b/spn/terminal/init.go index ee8633e28..6d1788889 100644 --- a/spn/terminal/init.go +++ b/spn/terminal/init.go @@ -6,6 +6,7 @@ import ( "github.com/safing/jess" "github.com/safing/portmaster/spn/cabin" "github.com/safing/portmaster/spn/hub" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/structures/container" "github.com/safing/structures/dsd" "github.com/safing/structures/varint" @@ -27,7 +28,7 @@ const ( ) // TerminalOpts holds configuration for the terminal. -type TerminalOpts struct { //nolint:golint,maligned // TODO: Rename. +type TerminalOpts struct { Version uint8 `json:"-"` Encrypt bool `json:"e,omitempty"` Padding uint16 `json:"p,omitempty"` @@ -52,7 +53,7 @@ func ParseTerminalOpts(c *container.Container) (*TerminalOpts, *Error) { // Parse init message. initMsg := &TerminalOpts{} - _, err = dsd.Load(c.CompileData(), initMsg) + _, err = peerdsd.Load(c.CompileData(), initMsg) if err != nil { return nil, ErrMalformedData.With("failed to parse init message: %w", err) } diff --git a/spn/terminal/init_compressed_test.go b/spn/terminal/init_compressed_test.go new file mode 100644 index 000000000..2d8ff1937 --- /dev/null +++ b/spn/terminal/init_compressed_test.go @@ -0,0 +1,87 @@ +package terminal + +import ( + "errors" + "testing" + + "github.com/safing/structures/container" + "github.com/safing/structures/dsd" + "github.com/safing/structures/varint" +) + +// TestParseTerminalOptsRejectsCompressed checks that gzip compressed terminal +// options are rejected before decompression. They are received from any +// client before authentication, and dsd.Load decompresses them into an +// unbounded buffer, so 16KB could make a Hub allocate about 64MB. +func TestParseTerminalOptsRejectsCompressed(t *testing.T) { + t.Parallel() + + opts := &TerminalOpts{Version: 1, Encrypt: true, Padding: 8, FlowControl: FlowControlDFQ, FlowControlSize: 100} + + // Packed options are accepted, as well as all serialization formats. + packed, tErr := opts.Pack() + if tErr != nil { + t.Fatal(tErr) + } + parsed, tErr := ParseTerminalOpts(packed) + if tErr != nil { + t.Fatal(tErr) + } + if *parsed != *opts { + t.Fatalf("unexpected options: %+v", parsed) + } + for _, format := range []uint8{dsd.JSON, dsd.CBOR, dsd.MsgPack, dsd.YAML} { + data, err := dsd.Dump(opts, format) + if err != nil { + t.Fatal(err) + } + parsed, tErr := ParseTerminalOpts(container.New(varint.Pack8(1), data)) + if tErr != nil { + t.Fatalf("format %c: %s", format, tErr) + } + if *parsed != *opts { + t.Fatalf("format %c: unexpected options: %+v", format, parsed) + } + } + + // Compressed options are rejected. + data, err := dsd.DumpAndCompress(opts, dsd.CBOR, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, tErr = ParseTerminalOpts(container.New(varint.Pack8(1), data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("expected ErrIncompatibleFormat, got %v", tErr) + } +} + +// TestCounterOpRejectsCompressed checks that gzip compressed counter op +// options are rejected before decompression. +func TestCounterOpRejectsCompressed(t *testing.T) { + t.Parallel() + + data, err := dsd.DumpAndCompress(&CounterOpts{}, dsd.JSON, dsd.GZIP) + if err != nil { + t.Fatal(err) + } + _, tErr := startCounterOp(nil, 1, container.New(data)) + if !errors.Is(tErr, dsd.ErrIncompatibleFormat) { + t.Errorf("expected ErrIncompatibleFormat, got %v", tErr) + } +} + +func FuzzParseTerminalOpts(f *testing.F) { + opts := &TerminalOpts{Version: 1, Encrypt: true, Padding: 8, FlowControl: FlowControlDFQ, FlowControlSize: 100} + for _, format := range []uint8{dsd.JSON, dsd.CBOR, dsd.MsgPack, dsd.YAML} { + data, err := dsd.Dump(opts, format) + if err != nil { + f.Fatal(err) + } + f.Add(append(varint.Pack8(1), data...)) + } + f.Add([]byte{1, 'Y', '[', '0', ']'}) + + f.Fuzz(func(t *testing.T, data []byte) { + _, _ = ParseTerminalOpts(container.New(data)) + }) +} diff --git a/spn/terminal/letter.go b/spn/terminal/letter.go new file mode 100644 index 000000000..50a5c0958 --- /dev/null +++ b/spn/terminal/letter.go @@ -0,0 +1,109 @@ +package terminal + +import ( + "github.com/safing/jess" + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +// LetterFromWire parses a letter received over a network connection. +// +// It parses the same wire format (version 1) and returns the same result as +// jess.LetterFromWire, but checks the size of every block against the data +// that is available before reading the block. jess.LetterFromWire reads +// blocks with container.GetNextBlock, which allocates the received block size +// before checking that the data is there. As letters are parsed before they +// are authenticated, anyone who can send a few bytes to a crane or terminal +// could otherwise make it allocate terabytes, which crashes the process with +// an unrecoverable "out of memory" fatal error (see GetNextBlock). +// Always use this function instead of jess.LetterFromWire for data received +// from other parties. +func LetterFromWire(c *container.Container) (*jess.Letter, error) { + // Reading from a container without data panics. + if c.Length() == 0 { + return nil, varint.ErrBufTooSmall + } + + letter := &jess.Letter{} + + // Wire Format Version: varint + wireFormatVersion, err := c.GetNextN8() + if err != nil { + return nil, err + } + if wireFormatVersion != 1 { + return nil, jess.ErrIncompatibleWireFormatVersion + } + + // Flags: varint + // - 1: Setup Msg (includes Version and Tools) + // - 2: Sending Keys + // - 4: Apply Keys + flags, err := c.GetNextN64() + if err != nil { + return nil, err + } + setupMsg := flags&1 > 0 + sendingKeys := flags&2 > 0 + letter.ApplyKeys = flags&4 > 0 + + if setupMsg { + // Version: varint (if Setup Msg) + letter.Version, err = c.GetNextN8() + if err != nil { + return nil, err + } + + // SuiteID: byte block (if Setup Msg) + suiteID, err := GetNextBlock(c) + if err != nil { + return nil, err + } + letter.SuiteID = string(suiteID) + } + + if sendingKeys { + // Keys: + // - Amount: varint + // - IDs/Values: byte blocks + n, err := c.GetNextN8() + if err != nil { + return nil, err + } + letter.Keys = make([]*jess.Seal, n) + for i := range letter.Keys { + signetID, err := GetNextBlock(c) + if err != nil { + return nil, err + } + sealValue, err := GetNextBlock(c) + if err != nil { + return nil, err + } + letter.Keys[i] = &jess.Seal{ + ID: string(signetID), + Value: sealValue, + } + } + } + + // Nonce: byte block + letter.Nonce, err = GetNextBlock(c) + if err != nil { + return nil, err + } + + // Data: byte block + letter.Data, err = GetNextBlock(c) + if err != nil { + return nil, err + } + + // MAC: byte block + letter.Mac, err = GetNextBlock(c) + if err != nil { + return nil, err + } + + return letter, nil +} diff --git a/spn/terminal/letter_test.go b/spn/terminal/letter_test.go new file mode 100644 index 000000000..36f8b9f24 --- /dev/null +++ b/spn/terminal/letter_test.go @@ -0,0 +1,163 @@ +package terminal + +import ( + "bytes" + "errors" + "reflect" + "testing" + + "github.com/safing/jess" + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +func testWireLetters() []*jess.Letter { + return []*jess.Letter{ + { // Data message. + Nonce: []byte{1, 2, 3, 4}, + Data: []byte("encrypted data"), + Mac: []byte("mac"), + }, + { // Setup message with keys. + Version: 1, + SuiteID: jess.SuiteWireV1, + Keys: []*jess.Seal{ + {ID: "key-id", Value: bytes.Repeat([]byte{7}, 32)}, + {Value: bytes.Repeat([]byte{8}, 32)}, + }, + Nonce: []byte{1, 2, 3, 4}, + Data: bytes.Repeat([]byte("data"), 1000), + }, + { // Rekeying message. + ApplyKeys: true, + Keys: []*jess.Seal{{Value: bytes.Repeat([]byte{9}, 32)}}, + Data: []byte{}, + }, + } +} + +// TestLetterFromWireMatchesJess checks that LetterFromWire parses valid +// letters exactly like jess.LetterFromWire. +func TestLetterFromWireMatchesJess(t *testing.T) { + t.Parallel() + + for i, letter := range testWireLetters() { + wire, err := letter.ToWire() + if err != nil { + t.Fatal(err) + } + data := wire.CompileData() + + expected, err := jess.LetterFromWire(container.New(data)) + if err != nil { + t.Fatal(err) + } + // Also parse data that is split over multiple compartments. + for _, c := range []*container.Container{ + container.New(data), + container.New(data[:3], data[3:7], data[7:]), + } { + got, err := LetterFromWire(c) + if err != nil { + t.Fatalf("letter %d: %s", i, err) + } + if !reflect.DeepEqual(got, expected) { + t.Errorf("letter %d: got %+v, expected %+v", i, got, expected) + } + if c.Length() != 0 { + t.Errorf("letter %d: %d bytes left", i, c.Length()) + } + } + } +} + +// TestLetterFromWireChecksBlockSizes checks that letters with a block size +// that exceeds the available data are rejected before the block is read. +// jess.LetterFromWire allocates the block size first, which crashes the +// process with "fatal error: runtime: out of memory" for these letters. +func TestLetterFromWireChecksBlockSizes(t *testing.T) { + t.Parallel() + + hugeSizes := []uint64{1 << 42, 1 << 62, 1<<64 - 1} + // Letter prefixes up to the block that gets the huge size. + prefixes := map[string][]byte{ + "suite ID": {1, 1, 1}, // Setup message: version, then suite ID. + "signet ID": {1, 2, 1}, // One key: signet ID. + "seal": {1, 2, 1, 0}, // One key with empty signet ID: seal value. + "nonce": {1, 0}, // Data message: nonce. + "data": {1, 0, 1, 0xFF}, // Data message with nonce: data. + "mac": {1, 0, 1, 0xFF, 1, 0xFF}, // Data message with nonce and data: mac. + } + + for name, prefix := range prefixes { + for _, size := range hugeSizes { + data := append(bytes.Clone(prefix), varint.Pack64(size)...) + data = append(data, "some data"...) + _, err := LetterFromWire(container.New(data)) + if !errors.Is(err, ErrBlockTooBig) { + t.Errorf("%s with size %d: expected ErrBlockTooBig, got %v", name, size, err) + } + } + } + + // Empty containers and truncated letters fail without panic. + for _, c := range []*container.Container{ + container.New(), + container.New(nil), + container.New([]byte{1}), + container.New([]byte{1, 0}), + container.New([]byte{1, 3, 1}), + container.New([]byte{1, 2, 255}), + container.New([]byte{2, 0}), + } { + _, err := LetterFromWire(c) + if err == nil { + t.Errorf("expected error for %v", c.CompileData()) + } + } +} + +// TestDecryptLetterWithHugeBlockSize checks that a terminal does not allocate +// the block size of a received letter, which is parsed before the letter is +// authenticated. Before LetterFromWire was used, this test crashed with +// "fatal error: runtime: out of memory". +func TestDecryptLetterWithHugeBlockSize(t *testing.T) { + t.Parallel() + + term := &TerminalBase{opts: &TerminalOpts{Encrypt: true}} + // Data message with a nonce of 4TB. + data := append([]byte{1, 0}, varint.Pack64(1<<42)...) + _, tErr := term.decrypt(container.New(data)) + if tErr == nil || !tErr.Is(ErrMalformedData) || !errors.Is(tErr, ErrBlockTooBig) { + t.Errorf("expected malformed data error with ErrBlockTooBig, got %v", tErr) + } +} + +// FuzzLetterFromWire checks that LetterFromWire never panics and agrees with +// jess.LetterFromWire on everything it accepts. +func FuzzLetterFromWire(f *testing.F) { + for _, letter := range testWireLetters() { + wire, err := letter.ToWire() + if err != nil { + f.Fatal(err) + } + f.Add(wire.CompileData()) + } + f.Add([]byte{1, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F}) + f.Add([]byte{}) + + f.Fuzz(func(t *testing.T, data []byte) { + got, err := LetterFromWire(container.New(bytes.Clone(data))) + if err != nil { + // jess.LetterFromWire cannot be called here, as it may run out of memory. + return + } + expected, err := jess.LetterFromWire(container.New(bytes.Clone(data))) + if err != nil { + t.Fatalf("jess.LetterFromWire failed on accepted letter: %s", err) + } + if !reflect.DeepEqual(got, expected) { + t.Fatalf("got %+v, expected %+v", got, expected) + } + }) +} diff --git a/spn/terminal/metrics.go b/spn/terminal/metrics.go index 099bde6c1..1d6f5f6e8 100644 --- a/spn/terminal/metrics.go +++ b/spn/terminal/metrics.go @@ -26,7 +26,7 @@ func registerMetrics() (err error) { _, err = metrics.NewGauge( "spn/scheduling/unit/slotpace/max", nil, - metricFromInt(scheduler.GetMaxSlotPace, scaleSlotToSecondsFactor), + metricFromInt(func() int64 { return getScheduler().GetMaxSlotPace() }, scaleSlotToSecondsFactor), &metrics.Options{ Name: "SPN Scheduling Max Slot Pace (scaled to per second)", Permission: api.PermitUser, @@ -39,7 +39,7 @@ func registerMetrics() (err error) { _, err = metrics.NewGauge( "spn/scheduling/unit/slotpace/leveled/max", nil, - metricFromInt(scheduler.GetMaxLeveledSlotPace, scaleSlotToSecondsFactor), + metricFromInt(func() int64 { return getScheduler().GetMaxLeveledSlotPace() }, scaleSlotToSecondsFactor), &metrics.Options{ Name: "SPN Scheduling Max Leveled Slot Pace (scaled to per second)", Permission: api.PermitUser, @@ -52,7 +52,7 @@ func registerMetrics() (err error) { _, err = metrics.NewGauge( "spn/scheduling/unit/slotpace/avg", nil, - metricFromInt(scheduler.GetAvgSlotPace, scaleSlotToSecondsFactor), + metricFromInt(func() int64 { return getScheduler().GetAvgSlotPace() }, scaleSlotToSecondsFactor), &metrics.Options{ Name: "SPN Scheduling Avg Slot Pace (scaled to per second)", Permission: api.PermitUser, @@ -65,7 +65,7 @@ func registerMetrics() (err error) { _, err = metrics.NewGauge( "spn/scheduling/unit/life/avg/seconds", nil, - metricFromNanoseconds(scheduler.GetAvgUnitLife), + metricFromNanoseconds(func() int64 { return getScheduler().GetAvgUnitLife() }), &metrics.Options{ Name: "SPN Scheduling Avg Unit Life", Permission: api.PermitUser, @@ -78,7 +78,7 @@ func registerMetrics() (err error) { _, err = metrics.NewGauge( "spn/scheduling/unit/workslot/avg/seconds", nil, - metricFromNanoseconds(scheduler.GetAvgWorkSlotDuration), + metricFromNanoseconds(func() int64 { return getScheduler().GetAvgWorkSlotDuration() }), &metrics.Options{ Name: "SPN Scheduling Avg Work Slot Duration", Permission: api.PermitUser, @@ -91,7 +91,7 @@ func registerMetrics() (err error) { _, err = metrics.NewGauge( "spn/scheduling/unit/catchupslot/avg/seconds", nil, - metricFromNanoseconds(scheduler.GetAvgCatchUpSlotDuration), + metricFromNanoseconds(func() int64 { return getScheduler().GetAvgCatchUpSlotDuration() }), &metrics.Options{ Name: "SPN Scheduling Avg Catch-Up Slot Duration", Permission: api.PermitUser, diff --git a/spn/terminal/module.go b/spn/terminal/module.go index a0867f996..b4a5bf661 100644 --- a/spn/terminal/module.go +++ b/spn/terminal/module.go @@ -3,6 +3,7 @@ package terminal import ( "errors" "flag" + "sync" "sync/atomic" "time" @@ -13,7 +14,7 @@ import ( ) // TerminalModule is the command multiplexing module. -type TerminalModule struct { //nolint:golint +type TerminalModule struct { mgr *mgr.Manager instance instance } @@ -34,9 +35,15 @@ func (s *TerminalModule) Stop() error { } var ( - rngFeeder *rng.Feeder = nil + // rngFeeder holds the current entropy feeder. It is replaced on every + // module start, while it may be used concurrently, so always use + // getRngFeeder() to access it. + rngFeeder atomic.Pointer[rng.Feeder] - scheduler *unit.Scheduler + // scheduler holds the current unit scheduler. It is replaced on every + // module start, while it may be used concurrently, so always use + // getScheduler() to access it. + scheduler atomic.Pointer[unit.Scheduler] debugUnitScheduling bool ) @@ -46,14 +53,15 @@ func init() { } func start() error { - rngFeeder = rng.NewFeeder() + rngFeeder.Store(rng.NewFeeder()) - scheduler = unit.NewScheduler(getSchedulerConfig()) + newScheduler := unit.NewScheduler(getSchedulerConfig()) if debugUnitScheduling { // Debug unit leaks. - scheduler.StartDebugLog() + newScheduler.StartDebugLog() } - module.mgr.Go("msg unit scheduler", scheduler.SlotScheduler) + scheduler.Store(newScheduler) + module.mgr.Go("msg unit scheduler", newScheduler.SlotScheduler) lockOpRegistry() @@ -70,13 +78,48 @@ func TimedOut(timeout time.Duration) <-chan time.Time { return time.After(timeout) } +// timerPool holds stopped timers for reuse. +var timerPool = sync.Pool{ + New: func() any { + timer := time.NewTimer(time.Hour) + timer.Stop() + return timer + }, +} + +// getPooledTimer returns a running timer with the given duration from the pool. +// It must be returned with putPooledTimer when it is not used anymore. +func getPooledTimer(d time.Duration) *time.Timer { + timer := timerPool.Get().(*time.Timer) //nolint:forcetypeassert // Pool only holds timers. + timer.Reset(d) + return timer +} + +// putPooledTimer stops the given timer and returns it to the pool. +// Since Go 1.23, a stopped timer never delivers a stale value on its channel, +// so it can be safely reused. +func putPooledTimer(timer *time.Timer) { + timer.Stop() + timerPool.Put(timer) +} + // StopScheduler stops the unit scheduler. func StopScheduler() { - if scheduler != nil { - scheduler.Stop() + if s := getScheduler(); s != nil { + s.Stop() } } +// getRngFeeder returns the current entropy feeder. +func getRngFeeder() *rng.Feeder { + return rngFeeder.Load() +} + +// getScheduler returns the current unit scheduler. +func getScheduler() *unit.Scheduler { + return scheduler.Load() +} + func getSchedulerConfig() *unit.SchedulerConfig { // Client Scheduler Config. if conf.Client() { diff --git a/spn/terminal/msg.go b/spn/terminal/msg.go index 1a2754996..a845e3854 100644 --- a/spn/terminal/msg.go +++ b/spn/terminal/msg.go @@ -28,7 +28,7 @@ func NewMsg(data []byte) *Msg { msg := &Msg{ Type: MsgTypeData, Data: container.New(data), - Unit: scheduler.NewUnit(), + Unit: getScheduler().NewUnit(), } // Debug unit leaks. @@ -44,7 +44,7 @@ func NewMsg(data []byte) *Msg { func NewEmptyMsg() *Msg { msg := &Msg{ Type: MsgTypeData, - Unit: scheduler.NewUnit(), + Unit: getScheduler().NewUnit(), } // Debug unit leaks. @@ -101,6 +101,6 @@ func (msg *Msg) debugWithCaller(skip int) { //nolint:unparam } _, file, line, ok := runtime.Caller(skip) if ok { - scheduler.DebugUnit(msg.Unit, fmt.Sprintf("%s:%d", file, line)) + getScheduler().DebugUnit(msg.Unit, fmt.Sprintf("%s:%d", file, line)) } } diff --git a/spn/terminal/msgtypes.go b/spn/terminal/msgtypes.go index c158e93bd..8c56fe8ca 100644 --- a/spn/terminal/msgtypes.go +++ b/spn/terminal/msgtypes.go @@ -1,6 +1,8 @@ package terminal import ( + "encoding/binary" + "github.com/safing/structures/container" "github.com/safing/structures/varint" ) @@ -50,8 +52,14 @@ func AddIDType(c *container.Container, id uint32, msgType MsgType) { // MakeMsg prepends the message header (Length and ID+Type) to the data. func MakeMsg(c *container.Container, id uint32, msgType MsgType) { - AddIDType(c, id, msgType) - c.PrependLength() + // Build the complete header in one buffer. + // This is equivalent to AddIDType followed by c.PrependLength(). + idType := uint64(id | uint32(msgType)) + length := uint64(varint.EncodedSize(idType) + c.Length()) //nolint:gosec // Length is never negative. + header := make([]byte, 0, varint.EncodedSize(length)+varint.EncodedSize(idType)) + header = binary.AppendUvarint(header, length) + header = binary.AppendUvarint(header, idType) + c.Prepend(header) } // ParseIDType parses the combined message ID and type. diff --git a/spn/terminal/msgtypes_test.go b/spn/terminal/msgtypes_test.go new file mode 100644 index 000000000..ad9a0528b --- /dev/null +++ b/spn/terminal/msgtypes_test.go @@ -0,0 +1,32 @@ +package terminal + +import ( + "bytes" + "testing" + + "github.com/safing/structures/container" +) + +func TestMakeMsg(t *testing.T) { + t.Parallel() + + for _, id := range []uint32{0, 4, 8, 124, 128, 1 << 14, 1<<28 + 4} { + for _, msgType := range []MsgType{MsgTypeInit, MsgTypeData, MsgTypePriorityData, MsgTypeStop} { + for _, size := range []int{0, 1, 124, 125, 126, 127, 128, 1400, 16380, 16384} { + data := bytes.Repeat([]byte{0xAB}, size) + + // Build expected msg the original way. + expected := container.New(data) + AddIDType(expected, id, msgType) + expected.PrependLength() + + // Build with MakeMsg and compare. + c := container.New(data) + MakeMsg(c, id, msgType) + if !bytes.Equal(c.CompileData(), expected.CompileData()) { + t.Fatalf("id=%d type=%d size=%d: MakeMsg output differs", id, msgType, size) + } + } + } + } +} diff --git a/spn/terminal/operation.go b/spn/terminal/operation.go index 7e014e0ec..afd160858 100644 --- a/spn/terminal/operation.go +++ b/spn/terminal/operation.go @@ -119,7 +119,7 @@ func (t *TerminalBase) handleOperationStart(opID uint32, initData *container.Con } // Extract the requested operation name. - opType, err := initData.GetNextBlock() + opType, err := GetNextBlock(initData) if err != nil { t.StopOperation(newUnknownOp(opID, ""), ErrMalformedData.With("failed to get init data: %w", err)) return @@ -197,6 +197,12 @@ func (t *TerminalBase) StartOperation(op Operation, initData *container.Containe err := op.Send(msg, timeout) if err != nil { msg.Finish() + + // The init msg was not sent, so the operation was never started. Remove + // it from the active operations immediately, as no reply will ever end + // it, and stop it so that it can clean up. + t.DeleteActiveOp(op.ID()) + t.StopOperation(op, err) } return err } @@ -215,10 +221,17 @@ func (t *TerminalBase) Send(msg *Msg, timeout time.Duration) *Error { } // Submit message to buffer, if space is available. + // This is a hot path, so use a pooled timer instead of allocating a new one. + var timedOut <-chan time.Time + if timeout != 0 { + timer := getPooledTimer(timeout) + defer putPooledTimer(timer) + timedOut = timer.C + } select { case t.sendQueue <- msg: return nil - case <-TimedOut(timeout): + case <-timedOut: msg.Finish() return ErrTimeout.With("sending via terminal") case <-t.Ctx().Done(): diff --git a/spn/terminal/operation_counter.go b/spn/terminal/operation_counter.go index 5ac2dacd3..d28bd3a7f 100644 --- a/spn/terminal/operation_counter.go +++ b/spn/terminal/operation_counter.go @@ -1,12 +1,14 @@ package terminal import ( + "errors" "fmt" "sync" "time" "github.com/safing/portmaster/base/log" "github.com/safing/portmaster/service/mgr" + "github.com/safing/portmaster/spn/peerdsd" "github.com/safing/structures/container" "github.com/safing/structures/dsd" "github.com/safing/structures/varint" @@ -15,8 +17,10 @@ import ( // CounterOpType is the type ID for the Counter Operation. const CounterOpType string = "debug/count" +var errCounterNotFinished = errors.New("did not finish counting") + // CounterOp sends increasing numbers on both sides. -type CounterOp struct { //nolint:maligned +type CounterOp struct { OperationBase wg sync.WaitGroup @@ -83,7 +87,7 @@ func startCounterOp(t Terminal, opID uint32, data *container.Container) (Operati // Parse arguments. opts := &CounterOpts{} - _, err := dsd.Load(data.CompileData(), opts) + _, err := peerdsd.Load(data.CompileData(), opts) if err != nil { return nil, ErrInternalError.With("failed to unpack options: %w", err) } @@ -178,15 +182,32 @@ func (op *CounterOp) Deliver(msg *Msg) *Error { // HandleStop handles stopping the operation. func (op *CounterOp) HandleStop(err *Error) (errorToSend *Error) { // Check if counting finished. - if !op.isDone() { - err := fmt.Errorf( - "counter op %d: did not finish counting (%d<-%d %d->%d)", - op.id, - op.opts.ClientCountTo, op.ClientCounter, - op.ServerCounter, op.opts.ServerCountTo, - ) - op.Error = err - } + // The counters may still be changed concurrently by Deliver, so read them + // while holding the lock. + func() { + op.counterLock.Lock() + defer op.counterLock.Unlock() + + if op.ClientCounter < op.opts.ClientCountTo || + op.ServerCounter < op.opts.ServerCountTo { + notFinished := fmt.Errorf( + "counter op %d: %w (%d<-%d %d->%d)", + op.id, errCounterNotFinished, + op.opts.ClientCountTo, op.ClientCounter, + op.ServerCounter, op.opts.ServerCountTo, + ) + // Keep the reason the operation stopped early, such as a failed + // send, instead of only reporting that counting did not finish. + switch { + case op.Error != nil: + op.Error = fmt.Errorf("%w: %w", notFinished, op.Error) + case err != nil && !err.IsOK(): + op.Error = fmt.Errorf("%w: stopped with: %w", notFinished, err) + default: + op.Error = notFinished + } + } + }() op.wg.Done() return err @@ -232,7 +253,9 @@ func (op *CounterOp) CounterWorker(ctx *mgr.WorkerCtx) error { default: // Something went wrong. err := fmt.Errorf("counter op %d: failed to send counter: %w", op.id, err) + op.counterLock.Lock() op.Error = err + op.counterLock.Unlock() op.Stop(op, ErrInternalError.With(err.Error())) return nil } diff --git a/spn/terminal/operation_counter_test.go b/spn/terminal/operation_counter_test.go new file mode 100644 index 000000000..d37179078 --- /dev/null +++ b/spn/terminal/operation_counter_test.go @@ -0,0 +1,46 @@ +package terminal + +import ( + "sync" + "testing" + + "github.com/safing/structures/varint" +) + +// TestCounterOpStopWhileDelivering checks that stopping a counter operation +// while it is still receiving counters does not race on the counters. +// Run with -race. +func TestCounterOpStopWhileDelivering(t *testing.T) { + t.Parallel() + + op := &CounterOp{ + opts: &CounterOpts{ + ClientCountTo: 1_000_000, + ServerCountTo: 1_000_000, + }, + } + op.wg.Add(1) + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for i := uint64(1); i <= 1000; i++ { + tErr := op.Deliver(NewMsg(varint.Pack64(i))) + if tErr != nil { + t.Errorf("failed to deliver counter %d: %s", i, tErr) + return + } + } + }() + go func() { + defer wg.Done() + _ = op.HandleStop(nil) + }() + wg.Wait() + op.Wait() + + if op.Error == nil { + t.Error("expected unfinished counting error") + } +} diff --git a/spn/terminal/operation_test.go b/spn/terminal/operation_test.go new file mode 100644 index 000000000..11e0945d3 --- /dev/null +++ b/spn/terminal/operation_test.go @@ -0,0 +1,74 @@ +package terminal + +import ( + "context" + "testing" + "time" +) + +type startFailTestOp struct { + OperationBase + + stopped chan *Error +} + +func (op *startFailTestOp) Type() string { + return "test/startfail" +} + +func (op *startFailTestOp) HandleStop(err *Error) (errorToSend *Error) { + select { + case op.stopped <- err: + default: + } + return err +} + +// TestStartOperationFailureCleansUp checks that an operation whose init msg +// could not be sent does not stay registered (leaked) in the terminal and is +// given the chance to clean up. +func TestStartOperationFailureCleansUp(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(module.mgr.Ctx()) + defer cancel() + + // Create a terminal without starting its workers. This simulates a + // terminal whose sender is busy, eg. waiting for flow control space, so + // that sending the init msg times out. + term, _, tErr := NewLocalBaseTerminal( + ctx, 127, "t", nil, + &TerminalOpts{ + FlowControl: FlowControlDFQ, + FlowControlSize: defaultTestQueueSize, + }, + UpstreamSendFunc(func(msg *Msg, _ time.Duration) *Error { + msg.Finish() + return nil + }), + ) + if tErr != nil { + t.Fatalf("failed to create terminal: %s", tErr) + } + + op := &startFailTestOp{stopped: make(chan *Error, 1)} + tErr = term.StartOperation(op, nil, 10*time.Millisecond) + if tErr == nil { + t.Fatal("expected starting the operation to fail") + } + + // The failed operation must not be registered anymore. + if cnt := term.GetActiveOpCount(); cnt != 0 { + t.Fatalf("failed operation is still registered: %d active operations", cnt) + } + + // The operation must be stopped, so it can clean up. + select { + case <-op.stopped: + case <-time.After(5 * time.Second): + t.Fatal("failed operation was not stopped") + } + if !op.Stopped() { + t.Fatal("failed operation is not marked as stopped") + } +} diff --git a/spn/terminal/rng_feeder_restart_test.go b/spn/terminal/rng_feeder_restart_test.go new file mode 100644 index 000000000..19aae4867 --- /dev/null +++ b/spn/terminal/rng_feeder_restart_test.go @@ -0,0 +1,44 @@ +package terminal + +import ( + "sync" + "testing" + "time" + + "github.com/safing/structures/container" +) + +// TestRngFeederRestart checks that the entropy feeder can be replaced on a +// module restart while padding messages are being handled concurrently. +// Run with -race. +func TestRngFeederRestart(t *testing.T) { //nolint:paralleltest // Restarts the global feeder. + term := &TerminalBase{} + stop := make(chan struct{}) + running := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + close(running) + for { + select { + case <-stop: + return + default: + } + term.handlePaddingMsg(container.New([]byte("padding"))) + } + }) + + // Restart the module like a module stop and start does. + <-running + for range 3 { + time.Sleep(10 * time.Millisecond) + StopScheduler() + err := start() + if err != nil { + t.Fatalf("failed to restart: %s", err) + } + } + + close(stop) + wg.Wait() +} diff --git a/spn/terminal/scheduler_restart_test.go b/spn/terminal/scheduler_restart_test.go new file mode 100644 index 000000000..6c17caa51 --- /dev/null +++ b/spn/terminal/scheduler_restart_test.go @@ -0,0 +1,47 @@ +package terminal + +import ( + "sync" + "testing" + "time" +) + +// TestSchedulerRestart checks that the unit scheduler can be replaced on a +// module restart while messages are being created concurrently. +// Run with -race. +func TestSchedulerRestart(t *testing.T) { //nolint:paralleltest // Restarts the global scheduler. + stop := make(chan struct{}) + running := make(chan struct{}) + var wg sync.WaitGroup + wg.Go(func() { + close(running) + for { + select { + case <-stop: + return + default: + } + NewMsg([]byte("test")).Finish() + NewEmptyMsg().Finish() + } + }) + + // Restart the scheduler like a module stop and start does. + <-running + for range 3 { + time.Sleep(10 * time.Millisecond) + StopScheduler() + err := start() + if err != nil { + t.Fatalf("failed to restart: %s", err) + } + } + + close(stop) + wg.Wait() + + // Messages must still get through the new scheduler. + msg := NewMsg([]byte("test")) + msg.Unit.WaitForSlot() + msg.Finish() +} diff --git a/spn/terminal/terminal.go b/spn/terminal/terminal.go index 1288303b3..ebece4fea 100644 --- a/spn/terminal/terminal.go +++ b/spn/terminal/terminal.go @@ -25,7 +25,7 @@ const ( ) // Terminal represents a terminal. -type Terminal interface { //nolint:golint // Being explicit is helpful here. +type Terminal interface { // ID returns the terminal ID. ID() uint32 // Ctx returns the terminal context. @@ -69,7 +69,7 @@ type Terminal interface { //nolint:golint // Being explicit is helpful here. } // TerminalBase contains the basic functions of a terminal. -type TerminalBase struct { //nolint:golint,maligned // Being explicit is helpful here. +type TerminalBase struct { // TODO: Fix maligned. Terminal // Interface check. @@ -254,7 +254,7 @@ func (t *TerminalBase) Handler(_ *mgr.WorkerCtx) error { defer t.Abandon(ErrInternalError.With("handler died")) var msg *Msg - defer msg.Finish() + defer func() { msg.Finish() }() for { select { @@ -348,7 +348,7 @@ func (t *TerminalBase) Sender(_ *mgr.WorkerCtx) error { var flushFinished func() // Finish any current unit when returning. - defer msgBufferMsg.Finish() + defer func() { msgBufferMsg.Finish() }() // Only receive message when not sending the current msg buffer. sendQueueOpMsgs := func() <-chan *Msg { @@ -574,7 +574,7 @@ func (t *TerminalBase) decrypt(c *container.Container) (*container.Container, *E t.jessionLock.Lock() defer t.jessionLock.Unlock() - letter, err := jess.LetterFromWire(c) + letter, err := LetterFromWire(c) if err != nil { return nil, ErrMalformedData.With("failed to parse letter: %w", err) } @@ -739,7 +739,7 @@ func (t *TerminalBase) handleOpMsg(data *container.Container) *Error { func (t *TerminalBase) handlePaddingMsg(c *container.Container) { padding := c.GetAll() if len(padding) > 0 { - rngFeeder.SupplyEntropyIfNeeded(padding, len(padding)) + getRngFeeder().SupplyEntropyIfNeeded(padding, len(padding)) } } diff --git a/spn/terminal/terminal_bench_test.go b/spn/terminal/terminal_bench_test.go new file mode 100644 index 000000000..61933c210 --- /dev/null +++ b/spn/terminal/terminal_bench_test.go @@ -0,0 +1,176 @@ +package terminal + +import ( + "fmt" + "testing" + "time" + + "github.com/safing/portmaster/spn/cabin" + "github.com/safing/structures/container" + "github.com/safing/structures/varint" +) + +const benchSinkOpType = "debug/bench-sink" + +func init() { + RegisterOpType(OperationFactory{ + Type: benchSinkOpType, + Start: startBenchSinkOp, + }) +} + +// benchSinkOp receives a fixed number of data messages and then signals done. +type benchSinkOp struct { + OperationBase + + remaining uint64 + done chan struct{} +} + +func (op *benchSinkOp) Type() string { + return benchSinkOpType +} + +func (op *benchSinkOp) Deliver(msg *Msg) *Error { + msg.Finish() + // Deliver is only called by the terminal handler, so no locking is needed. + op.remaining-- + if op.remaining == 0 { + close(op.done) + } + return nil +} + +// benchSinkDone is used to pass the done channel of the remote sink to the +// benchmark. +var benchSinkDone = make(chan chan struct{}, 1) + +func startBenchSinkOp(t Terminal, opID uint32, data *container.Container) (Operation, *Error) { + n, err := data.GetNextN64() + if err != nil { + return nil, ErrMalformedData.With("failed to get msg count: %w", err) + } + op := &benchSinkOp{ + remaining: n, + done: make(chan struct{}), + } + op.InitOperationBase(t, opID) + benchSinkDone <- op.done + return op, nil +} + +// benchSourceOp sends data messages. +type benchSourceOp struct { + OperationBase +} + +func (op *benchSourceOp) Type() string { + return benchSinkOpType +} + +func (op *benchSourceOp) Deliver(msg *Msg) *Error { + msg.Finish() + return nil +} + +// BenchmarkTerminalThroughput pumps data messages through a connected +// terminal pair (in-memory, no crane) and measures the per message cost of +// framing, flow control, unit scheduling and optionally encryption. +func BenchmarkTerminalThroughput(b *testing.B) { + for _, encrypt := range []bool{false, true} { + for _, size := range []int{100, 1400} { + b.Run(fmt.Sprintf("encrypt=%v/size=%d", encrypt, size), func(b *testing.B) { + benchmarkTerminalThroughput(b, encrypt, size) + }) + } + } +} + +func benchmarkTerminalThroughput(b *testing.B, encrypt bool, size int) { + b.Helper() + + opts := DefaultExpansionTerminalOpts() + opts.Encrypt = encrypt + opts.FlowControlSize = opts.FlowControl.DefaultSize() + + var a, z *TestTerminal + var initData *container.Container + var tErr *Error + if encrypt { + identity := getBenchIdentity(b) + a, initData, tErr = NewLocalTestTerminal( + module.mgr.Ctx(), 127, "a", identity.Hub, opts, UpstreamSendFunc(func(msg *Msg, _ time.Duration) *Error { + return z.Deliver(msg) + }), + ) + if tErr != nil { + b.Fatal(tErr) + } + z, _, tErr = NewRemoteTestTerminal( + module.mgr.Ctx(), 127, "z", identity, initData, UpstreamSendFunc(func(msg *Msg, _ time.Duration) *Error { + return a.Deliver(msg) + }), + ) + if tErr != nil { + b.Fatal(tErr) + } + } else { + var err error + a, z, err = NewSimpleTestTerminalPair(0, 0, opts) + if err != nil { + b.Fatal(err) + } + } + defer func() { + a.Abandon(nil) + z.Abandon(nil) + }() + + payload := make([]byte, size) + for i := range payload { + payload[i] = byte(i) + } + + b.SetBytes(int64(size)) + b.ReportAllocs() + b.ResetTimer() + + // Start sink on the other side. + src := &benchSourceOp{} + msgCount := uint64(b.N) //nolint:gosec // b.N is positive. + tErr = a.StartOperation(src, container.New(varint.Pack64(msgCount)), 3*time.Second) + if tErr != nil { + b.Fatal(tErr) + } + done := <-benchSinkDone + + for range b.N { + tErr = src.Send(src.NewMsg(payload), 3*time.Second) + if tErr != nil { + b.Fatal(tErr) + } + } + a.Flush(10 * time.Second) + + select { + case <-done: + case <-time.After(60 * time.Second): + b.Fatal("timed out waiting for sink") + } + b.StopTimer() +} + +var benchIdentity *cabin.Identity + +func getBenchIdentity(b *testing.B) *cabin.Identity { + b.Helper() + + if benchIdentity == nil { + var err error + benchIdentity, err = cabin.CreateIdentity(module.mgr.Ctx(), "test") + if err != nil { + b.Fatalf("failed to create identity: %s", err) + } + } + return benchIdentity +} diff --git a/spn/terminal/unit_leak_test.go b/spn/terminal/unit_leak_test.go new file mode 100644 index 000000000..f30620a87 --- /dev/null +++ b/spn/terminal/unit_leak_test.go @@ -0,0 +1,97 @@ +package terminal + +import ( + "context" + "testing" + "time" + + "github.com/safing/portmaster/spn/unit" +) + +// useStatScheduler replaces the global scheduler with one that cycles its +// stats quickly and returns a function that reports whether any unit of that +// scheduler was finished within the observation window. +// The unit lifetime stat is only non-zero if at least one unit was finished +// in the last cycle, which makes leaked units observable from the outside. +func useStatScheduler(t *testing.T) (anyUnitFinished func(wait time.Duration) bool) { + t.Helper() + + old := getScheduler() + s := unit.NewScheduler(&unit.SchedulerConfig{ + SlotDuration: time.Millisecond, + StatCycleDuration: 20 * time.Millisecond, + }) + scheduler.Store(s) + ctx, cancel := context.WithCancel(context.Background()) + module.mgr.Go("test msg unit scheduler", s.SlotScheduler) + t.Cleanup(func() { + cancel() + s.Stop() + scheduler.Store(old) + }) + + return func(wait time.Duration) bool { + deadline := time.Now().Add(wait) + for time.Now().Before(deadline) { + if s.GetAvgUnitLife() > 0 { + return true + } + select { + case <-ctx.Done(): + return false + case <-time.After(time.Millisecond): + } + } + return false + } +} + +// TestSenderFinishesBufferedUnit checks that the unit of a message that is +// still buffered when the sender exits is finished. +func TestSenderFinishesBufferedUnit(t *testing.T) { //nolint:paralleltest // Replaces the global scheduler. + anyUnitFinished := useStatScheduler(t) + + term, _, tErr := NewLocalBaseTerminal( + context.Background(), 1, "test", nil, &TerminalOpts{Padding: 0}, + UpstreamSendFunc(func(msg *Msg, _ time.Duration) *Error { + msg.Finish() + return nil + }), + ) + if tErr != nil { + t.Fatal(tErr) + } + + // Never flush on timeout, so that the message stays in the buffer. + term.WaitForFlush() + + senderDone := make(chan struct{}) + go func() { + defer close(senderDone) + _ = term.Sender(nil) //nolint:errcheck + }() + + msg := NewMsg([]byte("buffered")) + select { + case term.sendQueue <- msg: + case <-time.After(time.Second): + t.Fatal("sender did not accept msg") + } + + // Keep the message buffered for a moment: the stat only counts units with + // a lifetime above zero, and on Windows the monotonic clock only advances + // every few milliseconds. + time.Sleep(20 * time.Millisecond) + + // Stop the sender while the message is buffered. + term.cancelCtx() + select { + case <-senderDone: + case <-time.After(time.Second): + t.Fatal("sender did not exit") + } + + if !anyUnitFinished(500 * time.Millisecond) { + t.Fatal("unit of the buffered msg was not finished when the sender exited") + } +} diff --git a/spn/unit/scheduler.go b/spn/unit/scheduler.go index fc49a0dfb..80a85ea69 100644 --- a/spn/unit/scheduler.go +++ b/spn/unit/scheduler.go @@ -24,7 +24,7 @@ const ( // Scheduler creates and schedules units. // Must be created using NewScheduler(). -type Scheduler struct { //nolint:maligned +type Scheduler struct { // Configuration. config SchedulerConfig @@ -191,8 +191,8 @@ func (s *Scheduler) SlotScheduler(ctx *mgr.WorkerCtx) error { ticker := time.NewTicker(s.config.SlotDuration / 2) defer ticker.Stop() - // Give clearance to all when stopping. - defer s.clearanceUpTo.Store(math.MaxInt64 - math.MaxInt32) + // Give clearance to all when stopping and release all waiting units. + defer s.releaseAllSlotWaiters() var ( halfSlotID uint64 @@ -357,3 +357,23 @@ func (s *Scheduler) SlotScheduler(ctx *mgr.WorkerCtx) error { func (s *Scheduler) Stop() { s.stopping.Set() } + +// releaseAllSlotWaiters gives clearance to all units and permanently releases +// all units waiting for a slot. It must only be called when the slot scheduler +// stops, as no further slots may be announced afterwards. +func (s *Scheduler) releaseAllSlotWaiters() { + // Give clearance to all units. + s.clearanceUpTo.Store(math.MaxInt64 - math.MaxInt32) + + s.slotSignalsLock.Lock() + defer s.slotSignalsLock.Unlock() + + // Close the signal of the next slot without replacing it, so that units + // currently waiting are released and any unit that waits later receives an + // already closed channel and re-checks its (now granted) clearance. + if s.slotSignalSwitch { + close(s.slotSignalA) + } else { + close(s.slotSignalB) + } +} diff --git a/spn/unit/scheduler_stop_test.go b/spn/unit/scheduler_stop_test.go new file mode 100644 index 000000000..b70b25194 --- /dev/null +++ b/spn/unit/scheduler_stop_test.go @@ -0,0 +1,90 @@ +package unit + +import ( + "testing" + "time" + + "github.com/safing/portmaster/service/mgr" +) + +// TestSchedulerStopReleasesWaiters checks that units that are waiting for a +// slot when the scheduler stops are released, instead of blocking forever. +func TestSchedulerStopReleasesWaiters(t *testing.T) { + t.Parallel() + + // Use long slots, so that the test can act within a half-slot. + s := NewScheduler(&SchedulerConfig{ + SlotDuration: 2 * time.Second, + MinSlotPace: 10, + WorkSlotPercentage: 0.9, + }) + + // Create some units, so that the first work slot gives a clearance that + // differs from the initial clearance. + for range 5 { + s.NewUnit().Finish() + } + initialClearance := s.clearanceUpTo.Load() + + m := mgr.New("unit-test") + defer m.Cancel() + schedulerDone := make(chan struct{}) + m.Go("scheduler", func(w *mgr.WorkerCtx) error { + defer close(schedulerDone) + return s.SlotScheduler(w) + }) + + // Wait for the first (work) half-slot to start. + deadline := time.Now().Add(5 * time.Second) + for s.clearanceUpTo.Load() == initialClearance { + if time.Now().After(deadline) { + t.Fatal("scheduler did not start first slot") + } + time.Sleep(time.Millisecond) + } + + // We are now at the start of the work half-slot. The next tick will be the + // catch-up half-slot. Create a unit beyond the current clearance. + var u *Unit + for range 50 { + u = s.NewUnit() + } + if u.id <= s.clearanceUpTo.Load() { + t.Fatal("test unit unexpectedly has clearance") + } + waiterDone := make(chan struct{}) + go func() { + u.WaitForSlot() + close(waiterDone) + }() + // Give the waiter time to block on the slot signal. + time.Sleep(50 * time.Millisecond) + + // Stop the scheduler. It will stop at the catch-up half-slot tick, which + // does not announce a new slot. + s.Stop() + select { + case <-schedulerDone: + case <-time.After(5 * time.Second): + t.Fatal("scheduler did not stop") + } + + // The waiting unit must be released. + select { + case <-waiterDone: + case <-time.After(3 * time.Second): + t.Fatal("unit waiting for slot was not released when the scheduler stopped") + } + + // Units waiting after the scheduler stopped must not block either. + lateDone := make(chan struct{}) + go func() { + s.NewUnit().WaitForSlot() + close(lateDone) + }() + select { + case <-lateDone: + case <-time.After(3 * time.Second): + t.Fatal("unit waiting for slot after scheduler stopped was blocked") + } +} diff --git a/spn/unit/unit_debug.go b/spn/unit/unit_debug.go index 840ca479e..34888ce50 100644 --- a/spn/unit/unit_debug.go +++ b/spn/unit/unit_debug.go @@ -8,13 +8,13 @@ import ( ) // UnitDebugger is used to debug unit leaks. -type UnitDebugger struct { //nolint:golint +type UnitDebugger struct { units map[int64]*UnitDebugData unitsLock sync.Mutex } // UnitDebugData represents a unit that is being debugged. -type UnitDebugData struct { //nolint:golint +type UnitDebugData struct { unit *Unit unitSource string } diff --git a/tools/vmtest/README.md b/tools/vmtest/README.md new file mode 100644 index 000000000..8cb577b4b --- /dev/null +++ b/tools/vmtest/README.md @@ -0,0 +1,113 @@ +# VM test suite + +Runs the Go tests and an integration smoke test of `portmaster-core` in local +VMs: Linux (Fedora Cloud) as root, and Windows 11 as administrator with the +signed kernel extension. Everything runs as your user with QEMU/KVM and +user-mode networking; no root on the host is needed. + +## Requirements + +`qemu-system-x86_64`, `qemu-img`, `swtpm`, `xorriso`, `socat`, `rsync`, +OVMF (`/usr/share/edk2/ovmf`), read/write access to `/dev/kvm`, and Go. + +VM disks, keys and results live in `~/vms/portmaster-test` (override with +`VMTEST_DIR`), never in the repository. The Windows test account's password +is generated at install time and stored in `windows/credentials` there. + +## Set up (once) + +```bash +# Linux: Fedora Cloud Base Generic qcow2 from https://fedoraproject.org/cloud/ +tools/vmtest/linux/vm.sh create ~/vms/portmaster-test/images/Fedora-Cloud-Base-Generic-45-1.4.x86_64.qcow2 + +# Windows: any Windows 11 ISO. The answer file accepts the license terms and +# uses Microsoft's public generic key for Windows 11 Pro (stays unactivated). +tools/vmtest/windows/vm.sh create ~/Downloads/.iso +``` + +The Windows installation runs unattended for 30-60 minutes; watch it on VNC +at `127.0.0.1:5901`. + +## Run + +```bash +tools/vmtest/test-linux.sh # unit tests (race detector) + smoke test, as root +tools/vmtest/test-windows.sh all # unit tests + smoke test, as administrator +``` + +`test-linux.sh` resets the VM to its clean snapshot before every run. + +A soak test runs the service for a longer time under constant traffic +(HTTPS and DNS lookups of always new names) and samples memory, goroutines, +open files and data size every minute. It fails if one of them keeps growing +well beyond the level after warm-up: + +```bash +tools/vmtest/test-linux.sh soak 60 # minutes +``` Both +print a summary and write logs to `~/vms/portmaster-test/results/`. + +What the smoke tests check: + +- the service starts with packet interception (nfqueue / kernel extension); +- DNS and HTTPS work, a domain blocked in `config.json` is blocked; +- the API answers, lists connections in netquery and denies unknown clients; +- 40 parallel connections do not break it; +- it shuts down cleanly and leaves a working network; +- Linux only: after `kill -9`, `recover-iptables` restores the network. + +The Windows smoke test downloads the signed release binaries (including the +kernel extension) from Safing's update server with `portmaster-core update` +and runs the locally built `portmaster-core.exe` with them. The downloaded +core DLL needs the VC++ runtime, which the clean test VM does not have, so it +does not load there. To test a DLL built with the static C runtime (the +`portmaster-core-dll` artifact of the "Windows Portmaster Core DLL" workflow), +pass it with `WINDOWS_CORE_DLL=path/to/portmaster-core.dll`; the smoke test +then fails if it does not load. + +## Run on Proxmox VE + +The same VMs can run on a Proxmox VE host instead of local QEMU. Set +`VMTEST_BACKEND=proxmox` for every command: + +```bash +VMTEST_BACKEND=proxmox tools/vmtest/test-linux.sh +VMTEST_BACKEND=proxmox tools/vmtest/test-windows.sh all +VMTEST_BACKEND=proxmox tools/vmtest/linux/vm.sh status +``` + +Tests are still compiled on this machine; only the VMs move. The suite +reaches the host with `ssh proxmox` (root, key login; override with +`VMTEST_PVE_HOST`) and starts, stops and resets the VMs with `qm`. The VMs are +on the host's LAN bridge `vmbr0` with DHCP. The suite finds their address +from the MAC address on the host and connects through the host (ProxyJump), +so they need not be routable from here. The Linux smoke test reads the serial +console from the host's socket instead of a local file. + +| VM | VMID | Hardware | +|----|------|----------| +| `pm-vmtest-linux` | 900 (`VMTEST_LINUX_VMID`) | SeaBIOS, virtio disk and NIC, serial socket, snapshot `clean` | +| `pm-vmtest-windows` | 901 (`VMTEST_WINDOWS_VMID`) | OVMF with Secure Boot (MS keys), TPM 2.0, SATA disk, e1000e NIC | + +The Proxmox VMs were imported from the local ones rather than installed anew: + +```bash +# local: Linux from its clean snapshot, both flattened and compressed +qemu-img convert -O qcow2 -c -o compression_type=zstd -l snapshot.name=clean linux/disk.qcow2 linux.qcow2 +qemu-img convert -O qcow2 -c -o compression_type=zstd windows/disk.qcow2 windows.qcow2 +# host: create the VMs (see `qm config 900` / `qm config 901`), then +qm disk import 900 linux.qcow2 ssd-thin && qm set 900 --virtio0 ssd-thin:vm-900-disk-0 --boot order=virtio0 +qm disk import 901 windows.qcow2 ssd-thin && qm set 901 --sata0 ssd-thin:vm-901-disk-2 --boot order=sata0 +qm snapshot 900 clean +``` + +`vm.sh create` is not available on Proxmox. The Windows test account's +password stays in `~/vms/portmaster-test/windows/credentials`; the Windows +screen is in the Proxmox web UI (console of VM 901). + +## Manage the VMs + +```bash +tools/vmtest/linux/vm.sh start|stop|status|ssh|reset +tools/vmtest/windows/vm.sh start|stop|status|ssh +``` diff --git a/tools/vmtest/build-tests.sh b/tools/vmtest/build-tests.sh new file mode 100755 index 000000000..6fecc9a46 --- /dev/null +++ b/tools/vmtest/build-tests.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Compile the Go tests of all packages for a target OS into a bundle that can +# run without a Go toolchain: +# +# build-tests.sh linux|windows OUTDIR +# +# The bundle mirrors the repository layout: every package directory holds its +# compiled test binary (pkg.test or pkg.test.exe) and all non-Go files of the +# package (testdata, fixtures), as tests run from their package directory. +# Linux tests are built with the race detector. +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +target="${1:-}" +out="${2:-}" +[[ "$target" == linux || "$target" == windows ]] && [[ -n "$out" ]] || die "usage: build-tests.sh linux|windows OUTDIR" + +GO="$(go_bin)" +export GOOS="$target" GOARCH=amd64 +build_flags=() +ext="" +if [[ "$target" == linux ]]; then + export CGO_ENABLED=1 + build_flags=(-race) +else + export CGO_ENABLED=0 + ext=".exe" +fi + +cd "$VMTEST_REPO" +rm -rf "$out" && mkdir -p "$out" + +# Non-Go files of the repository, without sources of other languages and +# build output, so that tests find their testdata. +log "copying test data" +rsync -a --prune-empty-dirs \ + --exclude '.git/' --exclude 'node_modules/' --exclude 'desktop/' \ + --exclude 'target/' --exclude 'dist/' \ + --exclude '*.go' --exclude 'tools/vmtest/' \ + --include '*/' --include '**/testdata/**' --include '*' \ + ./ "$out/" + +# Packages with tests for the target OS. +mapfile -t pkgs < <("$GO" list -f '{{if or .TestGoFiles .XTestGoFiles}}{{.ImportPath}}|{{.Dir}}{{end}}' ./... | sed '/^$/d') +log "compiling ${#pkgs[@]} test packages for $target" + +build_one() { + local entry="$1" pkg dir rel + pkg="${entry%%|*}" + dir="${entry#*|}" + rel="${dir#"$VMTEST_REPO"/}" + mkdir -p "$out/$rel" + if ! "$GO" test -c "${build_flags[@]}" -o "$out/$rel/pkg.test$ext" "$pkg" >"$out/$rel/build.log" 2>&1; then + echo "BUILD FAILED: $pkg" >&2 + cat "$out/$rel/build.log" >&2 + return 1 + fi + rm -f "$out/$rel/build.log" +} +export -f build_one log die +export GO out ext VMTEST_REPO +export build_flags_str="${build_flags[*]}" + +failed=0 +printf '%s\n' "${pkgs[@]}" | xargs -P "$(nproc)" -I{} bash -c 'build_flags=($build_flags_str); build_one "$@"' _ {} || failed=1 + +# Runner scripts. +cp "$VMTEST_REPO/tools/vmtest/run-tests.sh" "$VMTEST_REPO/tools/vmtest/run-tests.ps1" "$out/" + +count=$(find "$out" -name "pkg.test$ext" | wc -l) +log "bundle in $out: $count test binaries, $(du -sh "$out" | cut -f1)" +((failed == 0)) || die "some packages failed to compile" diff --git a/tools/vmtest/common.sh b/tools/vmtest/common.sh new file mode 100644 index 000000000..2defb04bc --- /dev/null +++ b/tools/vmtest/common.sh @@ -0,0 +1,141 @@ +# Shared settings for the VM test suite. Source this file, do not run it. +# +# All VM images, disks, keys and credentials live in VMTEST_DIR, outside of +# the repository. Nothing here needs root on the host: the VMs run as the +# current user with QEMU, KVM and user-mode networking. + +set -euo pipefail + +VMTEST_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +VMTEST_DIR="${VMTEST_DIR:-$HOME/vms/portmaster-test}" +VMTEST_SSH_KEY="$VMTEST_DIR/ssh/id_ed25519" + +# Linux VM. +LINUX_DIR="$VMTEST_DIR/linux" +LINUX_SSH_PORT="${LINUX_SSH_PORT:-2222}" +LINUX_MEM="${LINUX_MEM:-4096}" +LINUX_CPUS="${LINUX_CPUS:-4}" +LINUX_USER="tester" + +# Windows VM. +WINDOWS_DIR="$VMTEST_DIR/windows" +WINDOWS_SSH_PORT="${WINDOWS_SSH_PORT:-2223}" +WINDOWS_VNC_DISPLAY="${WINDOWS_VNC_DISPLAY:-1}" # 127.0.0.1:5901 +WINDOWS_MEM="${WINDOWS_MEM:-6144}" +WINDOWS_CPUS="${WINDOWS_CPUS:-4}" +WINDOWS_USER="tester" + +OVMF_DIR="${OVMF_DIR:-/usr/share/edk2/ovmf}" + +log() { printf '\033[1m[vmtest]\033[0m %s\n' "$*" >&2; } +die() { log "error: $*"; exit 1; } + +# ensure_ssh_key creates the SSH key used to log into all test VMs. +ensure_ssh_key() { + if [[ ! -f "$VMTEST_SSH_KEY" ]]; then + mkdir -p "$(dirname "$VMTEST_SSH_KEY")" + ssh-keygen -q -t ed25519 -N "" -C "portmaster-vmtest" -f "$VMTEST_SSH_KEY" + fi +} + +VMTEST_BACKEND="${VMTEST_BACKEND:-local}" +case "$VMTEST_BACKEND" in +local) ;; +proxmox) source "$(dirname "${BASH_SOURCE[0]}")/proxmox.sh" ;; +*) die "unknown VMTEST_BACKEND $VMTEST_BACKEND (local or proxmox)" ;; +esac + +# Test bundles and results; separate per backend so that local and Proxmox +# runs can happen at the same time. +VMTEST_WORK="$VMTEST_DIR" +[[ "$VMTEST_BACKEND" == local ]] || VMTEST_WORK="$VMTEST_DIR/$VMTEST_BACKEND" + +# vm_endpoint PORT sets VM_HOST, VM_PORT and VM_SSH_OPTS for the VM named by +# PORT: 127.0.0.1 with QEMU's port forward locally, the VM's LAN address +# through the host on Proxmox. +vm_endpoint() { + VM_SSH_OPTS=(-i "$VMTEST_SSH_KEY" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null + -o LogLevel=ERROR -o ConnectTimeout=5 -o BatchMode=yes) + if [[ "$VMTEST_BACKEND" == proxmox ]]; then + VM_HOST="$(pve_ssh_target "$1")" || return 255 + VM_PORT=22 + VM_SSH_OPTS+=(-o "ProxyCommand=$(pve_proxy_command)") + else + VM_HOST=127.0.0.1 + VM_PORT="$1" + fi +} + +# vm_ssh PORT USER [COMMAND...] runs a command in a test VM. On Proxmox, a +# failed connection looks up the VM's address again, as DHCP may change it. +vm_ssh() { + local port="$1" user="$2" rc + shift 2 + vm_endpoint "$port" || return 255 + ssh "${VM_SSH_OPTS[@]}" -p "$VM_PORT" "$user@$VM_HOST" "$@" + rc=$? + if ((rc == 255)) && [[ "$VMTEST_BACKEND" == proxmox ]]; then + PVE_IP_REFRESH=1 vm_endpoint "$port" || return 255 + ssh "${VM_SSH_OPTS[@]}" -p "$VM_PORT" "$user@$VM_HOST" "$@" + rc=$? + fi + return $rc +} + +# vm_rsh PORT prints an rsync -e command for the VM named by PORT, and +# vm_dest PORT USER PATH the matching rsync destination. +vm_rsh() { + vm_endpoint "$1" || return 1 + # rsync splits -e on spaces and honours quotes, not backslashes. + local a + for a in ssh "${VM_SSH_OPTS[@]}" -p "$VM_PORT"; do printf "'%s' " "$a"; done +} +vm_dest() { + vm_endpoint "$1" || return 1 + echo "$2@$VM_HOST:$3" +} + +# vm_scp PORT USER SRC... DST copies files into a test VM (DST is remote). +vm_scp() { + local port="$1" user="$2" + shift 2 + local args=("$@") + local dst="${args[-1]}" + unset 'args[-1]' + vm_endpoint "$port" || return 1 + scp -q "${VM_SSH_OPTS[@]}" -P "$VM_PORT" "${args[@]}" "$user@$VM_HOST:$dst" +} + +# vm_fetch PORT USER REMOTE_SRC LOCAL_DST copies a file out of a test VM. +vm_fetch() { + vm_endpoint "$1" || return 1 + scp -q "${VM_SSH_OPTS[@]}" -P "$VM_PORT" "$2@$VM_HOST:$3" "$4" +} + +# wait_for_ssh PORT USER TIMEOUT_SECONDS waits until SSH login works. +# The probe is "exit 0", which works in bash and in PowerShell, the SSH +# shell of the Windows VM ("true" is not a PowerShell command). +wait_for_ssh() { + local port="$1" user="$2" timeout="$3" waited=0 + until vm_ssh "$port" "$user" 'exit 0' 2>/dev/null; do + ((waited += 10)) + ((waited <= timeout)) || return 1 + sleep 10 + done +} + +# vm_running PIDFILE reports whether the VM of PIDFILE is running. +vm_running() { + [[ -f "$1" ]] && kill -0 "$(cat "$1")" 2>/dev/null +} + +# go_bin returns the go binary to use. +go_bin() { + if command -v go >/dev/null; then + command -v go + elif [[ -x "$HOME/.local/go1.26.3/go/bin/go" ]]; then + echo "$HOME/.local/go1.26.3/go/bin/go" + else + die "go not found" + fi +} diff --git a/tools/vmtest/linux/smoke.sh b/tools/vmtest/linux/smoke.sh new file mode 100644 index 000000000..eccea1b29 --- /dev/null +++ b/tools/vmtest/linux/smoke.sh @@ -0,0 +1,213 @@ +#!/usr/bin/env bash +# Integration smoke test of portmaster-core on Linux. Runs inside the test VM +# as root (see test-linux.sh): +# +# sudo bash smoke.sh ./portmaster-core +# +# Starts the real service with packet interception and checks that it +# intercepts and filters traffic, answers its API, shuts down cleanly and that +# a crashed instance can be recovered. Exits non-zero if any check fails. +set -uo pipefail + +CORE="$(realpath "${1:?usage: smoke.sh PORTMASTER_CORE}")" +WORK=/tmp/pm-smoke +DATA="$WORK/data" +LOG="$WORK/core.log" +API=http://127.0.0.1:817/api/v1 +ALLOWED=example.com +BLOCKED=example.org +# A name whose CNAME points outside the blocked zone (safing/portmaster#2306). +CNAME_BLOCKED=tr.archive.ubuntu.com +CNAME_ZONE=ubuntu.com +# A tracker on the default filter lists. +TRACKER=doubleclick.net + +failures=0 +pass() { printf ' \033[32mPASS\033[0m %s\n' "$*"; } +fail() { printf ' \033[31mFAIL\033[0m %s\n' "$*"; ((failures++)); } +check() { # check DESCRIPTION COMMAND... + local desc="$1" + shift + if "$@" >/dev/null 2>&1; then pass "$desc"; else fail "$desc"; fi +} +step() { printf '\n== %s\n' "$*"; } + +rules_present() { iptables-save 2>/dev/null | grep -q PORTMASTER || ip6tables-save 2>/dev/null | grep -q PORTMASTER; } +https_ok() { curl -sS -o /dev/null --max-time 15 "https://$1/"; } +http_ok() { curl -sS -o /dev/null --max-time 15 "http://$1/"; } +resolves() { getent ahostsv4 "$1" | grep -qv '^0\.0\.0\.0'; } +api_ready() { curl -sf --max-time 5 "$API/ready"; } +core_pid="" + +start_core() { + "$CORE" --data-dir "$DATA" --log-stdout --log info \ + --allowed-clients "$(realpath "$(command -v curl)")" >>"$LOG" 2>&1 & + core_pid=$! + local waited=0 + until api_ready >/dev/null 2>&1; do + sleep 2 + ((waited += 2)) + ((waited % 30 == 0)) && echo " waiting for portmaster-core (${waited}s): $(tail -1 "$LOG" | cut -c1-120)" + if ! kill -0 "$core_pid" 2>/dev/null; then + echo "portmaster-core exited during start; last log lines:" + tail -30 "$LOG" + return 1 + fi + if ((waited >= 300)); then + echo "portmaster-core not ready after ${waited}s; last log lines:" + tail -30 "$LOG" + return 1 + fi + done + echo " portmaster-core ready after ${waited}s (pid $core_pid)" +} + +netquery_count() { # netquery_count DOMAIN + curl -sf --max-time 10 -X POST "$API/netquery/query" -H 'Content-Type: application/json' \ + -d "{\"query\":{\"domain\":{\"\$like\":\"%$1%\"}},\"select\":[\"id\",\"verdict\"],\"pageSize\":50}" | + jq '.results | length' +} + +rm -rf "$WORK" && mkdir -p "$DATA" + +step "Before start" +check "no Portmaster rules installed" bash -c '! { iptables-save | grep -q PORTMASTER; }' +check "https://$ALLOWED reachable" https_ok "$ALLOWED" +check "http://$CNAME_BLOCKED reachable" http_ok "$CNAME_BLOCKED" + +# Block one domain and allow incoming SSH (the test is controlled over SSH) +# in the global settings. +write_config() { + printf '{"filter":{"endpoints":[%s],"serviceEndpoints":["+ * TCP/22"]}}\n' "$1" >"$DATA/config.json" +} +write_config "\"- $BLOCKED\",\"- .$CNAME_ZONE\"" + +step "Start" +if ! start_core; then + fail "portmaster-core starts and reports ready" + exit 1 +fi +pass "portmaster-core starts and reports ready" +check "interception rules installed" rules_present +check "nfqueue bound" bash -c 'grep -q . /proc/net/netfilter/nfnetlink_queue' +check "systemd-resolved cache flushed" grep -q 'flushed the systemd-resolved cache' "$LOG" + +step "Filtering" +check "$ALLOWED resolves" resolves "$ALLOWED" +check "https://$ALLOWED reachable" https_ok "$ALLOWED" +# Fedora resolves names through systemd-resolved, so the per-app rule applies +# to the connection, not to the DNS query. +echo " info: $BLOCKED resolves through systemd-resolved: $(resolves "$BLOCKED" && echo yes || echo no)" +check "https://$BLOCKED is blocked" bash -c "! curl -sS -o /dev/null --max-time 10 https://$BLOCKED/" +check "http://$CNAME_BLOCKED is blocked by the rule for .$CNAME_ZONE (CNAME outside the zone)" bash -c "! curl -sS -o /dev/null --max-time 10 http://$CNAME_BLOCKED/" +# A blocked connection must fail at once, not by timeout (safing/portmaster#1981). +block_start=$(date +%s%N) +curl -sS -o /dev/null --max-time 40 "http://$CNAME_BLOCKED/" >/dev/null 2>&1 +block_rc=$? +block_ms=$((($(date +%s%N) - block_start) / 1000000)) +check "a blocked connection fails at once, not by timeout (${block_ms}ms, curl exit code $block_rc)" test "$block_rc" -ne 0 -a "$block_ms" -lt 5000 +check "Portmaster nameserver answers" bash -c "dig +short +time=5 +tries=1 $ALLOWED @127.0.0.1 | grep -q ." + +step "Filter lists" +# Downloading, decoding and storing the lists covers the intel updater, the +# list decoder and the SQLite cache database. +waited=0 +until grep -q 'rebuilt bloom filters' "$LOG" || ((waited >= 240)); do + sleep 5 + ((waited += 5)) +done +check "filter lists loaded (${waited}s)" grep -q 'rebuilt bloom filters' "$LOG" +check "https://$TRACKER is blocked by the filter lists" bash -c "! curl -sS -o /dev/null --max-time 10 https://$TRACKER/" +# The block is logged by the nameserver or the filter, whichever sees it +# first, and the log is written asynchronously. +check "the block names the filter lists" bash -c "for i in 1 2 3 4 5; do grep -q '$TRACKER\\. in activated lists' '$LOG' && exit 0; sleep 1; done; exit 1" + +step "API" +check "ping endpoint" curl -sf --max-time 5 "$API/ping" +sleep 3 # let netquery save the connections +n=$(netquery_count "$ALLOWED" 2>/dev/null || echo 0) +if [[ "$n" =~ ^[0-9]+$ ]] && ((n > 0)); then pass "netquery lists connections to $ALLOWED ($n)"; else fail "netquery lists connections to $ALLOWED (got '$n')"; fi +code=$(python3 -c " +import urllib.request, urllib.error +req = urllib.request.Request('$API/netquery/query', data=b'{}', method='POST') +try: + print(urllib.request.urlopen(req, timeout=10).status) +except urllib.error.HTTPError as e: + print(e.code) +" 2>/dev/null) +if [[ "$code" == 403 || "$code" == 401 ]]; then pass "API denies an unauthorized local client ($code)"; else fail "API denies an unauthorized local client (got '$code')"; fi +# app/auth identifies the calling process and waits for the user to answer +# the prompt; without the process (safing/portmaster#2302 B1) it fails at once. +auth_code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$API/app/auth?app-name=vmtest&read=user&write=user&ttl=1h") +if [[ "$auth_code" == 000 ]]; then pass "app/auth identifies the caller and waits for the prompt"; else fail "app/auth identifies the caller and waits for the prompt (got HTTP $auth_code)"; fi + +step "Load" +load_pids=() +for i in $(seq 1 40); do + curl -s -o /dev/null --max-time 10 "https://$ALLOWED/?n=$i" & + load_pids+=($!) +done +wait "${load_pids[@]}" # not "wait" alone, which would wait for portmaster-core +check "service alive after 40 parallel connections" kill -0 "$core_pid" +check "https://$ALLOWED still reachable" https_ok "$ALLOWED" + +step "Bandwidth" +# Several requests over one kept-alive connection, so that the connection +# is open long enough for the eBPF bandwidth monitor to sample it. +curl -s -o /dev/null --max-time 20 --rate 2/s "https://$ALLOWED/?bw=[1-8]" || true +sleep 3 # let the bandwidth updates reach netquery +bw=$(curl -sf --max-time 10 -X POST "$API/netquery/query" -H 'Content-Type: application/json' \ + -d "{\"query\":{\"domain\":{\"\$like\":\"%$ALLOWED%\"}},\"select\":[\"bytes_received\",\"bytes_sent\"],\"pageSize\":100}" | + jq '[.results[] | (.bytes_received // 0) + (.bytes_sent // 0)] | add // 0' 2>/dev/null || echo 0) +if [[ "$bw" =~ ^[0-9]+$ ]] && ((bw > 0)); then pass "eBPF bandwidth data recorded ($bw bytes)"; else fail "eBPF bandwidth data recorded (got '$bw')"; fi + +step "Shutdown" +kill -TERM "$core_pid" +stopped=0 +for _ in $(seq 1 60); do + if ! kill -0 "$core_pid" 2>/dev/null; then stopped=1; break; fi + sleep 1 +done +if ((stopped)); then pass "portmaster-core stops within 60s"; else fail "portmaster-core stops within 60s"; kill -9 "$core_pid"; fi +wait "$core_pid" 2>/dev/null +rc=$? +if ((rc == 0)); then pass "exit code 0"; else fail "exit code $rc"; fi +check "interception rules removed" bash -c '! { iptables-save | grep -q PORTMASTER; }' +check "https://$ALLOWED reachable without Portmaster" https_ok "$ALLOWED" + +step "Crash recovery" +write_config "" +if start_core; then + kill -9 "$core_pid" + wait "$core_pid" 2>/dev/null + if rules_present; then + echo " info: rules remain after a crash; reachable meanwhile: $(https_ok "$ALLOWED" && echo yes || echo no)" + else + echo " info: no rules left after a crash" + fi + "$CORE" recover-iptables >>"$LOG" 2>&1 + check "recover-iptables removes the rules" bash -c '! { iptables-save | grep -q PORTMASTER; }' + check "https://$ALLOWED reachable after recovery" https_ok "$ALLOWED" +else + fail "portmaster-core restarts with existing data" +fi + +step "Log" +panics=$(grep -c -E '^panic:|fatal error:|DATA RACE' "$LOG" || true) +if ((panics == 0)); then pass "no panics in the log"; else fail "$panics panics in the log"; fi +errors=$(grep -cE ' (ERR|CRT) ' "$LOG" || true) +echo " log: $(wc -l <"$LOG") lines" +if ((errors == 0)); then + pass "no errors in the log" +else + fail "$errors errors in the log" + grep -E ' (ERR|CRT) ' "$LOG" | head -10 | cut -c1-200 +fi + +if ((failures > 0)); then + echo " last log lines:" + tail -40 "$LOG" | sed 's/^/ /' +fi +echo +if ((failures == 0)); then echo "SMOKE TEST PASSED"; else echo "SMOKE TEST FAILED: $failures checks"; fi +((failures == 0)) diff --git a/tools/vmtest/linux/soak.sh b/tools/vmtest/linux/soak.sh new file mode 100755 index 000000000..be7e29e3b --- /dev/null +++ b/tools/vmtest/linux/soak.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# Soak test of portmaster-core on Linux. Runs inside the test VM as root (see +# test-linux.sh soak): +# +# sudo bash soak.sh ./portmaster-core [MINUTES] +# +# Runs the service with interception under constant traffic and samples its +# resource usage every minute, to find leaks that short tests do not show. +# Prints one line per sample and a summary of the growth between the first +# samples after warm-up and the last ones. Exits non-zero if the service dies +# or a resource keeps growing well beyond the warm-up level. +set -uo pipefail + +CORE="$(realpath "${1:?usage: soak.sh PORTMASTER_CORE [MINUTES]}")" +MINUTES="${2:-60}" +WORK=/tmp/pm-soak +DATA="$WORK/data" +LOG="$WORK/core.log" +CSV="$WORK/samples.csv" +API=http://127.0.0.1:817/api/v1 + +rm -rf "$WORK" && mkdir -p "$DATA" +# Allow incoming SSH, the test is controlled over SSH. +printf '{"filter":{"serviceEndpoints":["+ * TCP/22"]}}\n' >"$DATA/config.json" + +"$CORE" --data-dir "$DATA" --log-stdout --log warning \ + --allowed-clients "$(realpath "$(command -v curl)")" >"$LOG" 2>&1 & +core_pid=$! +for _ in $(seq 1 150); do + curl -sf --max-time 5 "$API/ready" >/dev/null 2>&1 && break + kill -0 "$core_pid" 2>/dev/null || { echo "SOAK FAILED: portmaster-core exited during start"; tail -20 "$LOG"; exit 1; } + sleep 2 +done +echo "portmaster-core running (pid $core_pid), soaking for $MINUTES minutes" + +# Traffic: HTTPS to a few sites and DNS lookups of always new names, so that +# connections, DNS caches and the connection history keep changing. +traffic() { + local i=0 + local sites=(example.com example.org wikipedia.org debian.org kernel.org) + while true; do + i=$((i + 1)) + for s in "${sites[@]}"; do + curl -s -o /dev/null --max-time 10 "https://$s/?soak=$i" & + done + for n in $(seq 1 10); do + getent hosts "soak-$i-$n.example.com" >/dev/null 2>&1 & + done + wait + sleep 1 + done +} +traffic & +traffic_pid=$! +trap 'kill "$traffic_pid" 2>/dev/null; kill "$core_pid" 2>/dev/null' EXIT + +echo "minute,rss_kb,heap_kb,goroutines,fds,db_kb" >"$CSV" +sample() { + local rss heap goroutines fds db + rss=$(ps -o rss= -p "$core_pid" | tr -d ' ') + # The stack endpoint returns a grouped goroutine profile with the total in + # its first line: "goroutine profile: total N". + goroutines=$(curl -sf --max-time 10 "$API/debug/stack" | sed -n 's/^goroutine profile: total \([0-9]*\).*/\1/p' | head -1) + # Prometheus metrics are served at /metrics, with a namespace prefix and + # possibly labels: portmaster_go_memstats_heap_inuse_bytes{...} VALUE + heap=$(curl -sf --max-time 10 http://127.0.0.1:817/metrics | awk '$1 ~ /^([a-z]+_)?go_memstats_heap_inuse_bytes(\{.*\})?$/ {printf "%d", $NF/1024; exit}') + fds=$(ls "/proc/$core_pid/fd" | wc -l) + db=$(du -sk "$DATA" | cut -f1) + echo "$1,$rss,${heap:-0},$goroutines,$fds,$db" >>"$CSV" + printf 'minute %3d: rss %6d KB heap %6d KB goroutines %5d fds %4d data %6d KB\n' "$1" "$rss" "${heap:-0}" "$goroutines" "$fds" "$db" +} + +for m in $(seq 0 "$MINUTES"); do + if ! kill -0 "$core_pid" 2>/dev/null; then + echo "SOAK FAILED: portmaster-core died after $m minutes" + tail -30 "$LOG" + exit 1 + fi + sample "$m" + [ "$m" -lt "$MINUTES" ] && sleep 60 +done + +# Compare the averages after warm-up with the averages at the end. The +# connection history keeps ended connections for 10 minutes, so memory only +# levels off after about 20 minutes under constant traffic. Open files vary +# with the connections open at each sample, so averages over 10 samples are +# compared. +python3 - "$CSV" <<'PY' +import csv, sys +rows = list(csv.DictReader(open(sys.argv[1]))) +if len(rows) < 15: + print("SOAK INCONCLUSIVE: too few samples"); sys.exit(0) +def avg(rs, k): return sum(int(r[k] or 0) for r in rs) / len(rs) +if len(rows) >= 45: + early, late = rows[20:30], rows[-10:] +else: + early, late = rows[5:10], rows[-5:] +failed = False +for k, limit in (("rss_kb", 1.5), ("heap_kb", 1.5), ("goroutines", 1.3), ("fds", 1.5)): + a, b = avg(early, k), avg(late, k) + ratio = b / a if a else 0 + flag = "GROWING" if ratio > limit else "ok" + failed |= ratio > limit + print(f"{k:11s} after warm-up {a:9.0f} at the end {b:9.0f} ratio {ratio:4.2f} {flag}") +print("SOAK TEST FAILED" if failed else "SOAK TEST PASSED") +sys.exit(1 if failed else 0) +PY diff --git a/tools/vmtest/linux/vm.sh b/tools/vmtest/linux/vm.sh new file mode 100755 index 000000000..0cf75dbba --- /dev/null +++ b/tools/vmtest/linux/vm.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +# Manage the Linux (Fedora Cloud) test VM, in which tests run as root. +# +# vm.sh create IMAGE create the VM from a Fedora Cloud qcow2 image +# vm.sh start start the VM +# vm.sh stop shut the VM down +# vm.sh status show whether the VM runs and SSH works +# vm.sh ssh [CMD] open a shell or run a command in the VM +# vm.sh reset discard all changes since create (snapshot "clean") +source "$(dirname "${BASH_SOURCE[0]}")/../common.sh" + +if [[ "$VMTEST_BACKEND" == proxmox ]]; then + pve_vm_main "$LINUX_VMID" linux "$@" + exit +fi + +DIR="$LINUX_DIR" +DISK="$DIR/disk.qcow2" +PIDFILE="$DIR/qemu.pid" +MONITOR="$DIR/monitor.sock" + +start_qemu() { + vm_running "$PIDFILE" && die "VM already running" + qemu-system-x86_64 \ + -name portmaster-vmtest-linux \ + -machine q35,accel=kvm -cpu host \ + -smp "$LINUX_CPUS" -m "$LINUX_MEM" \ + -drive "file=$DISK,if=virtio,format=qcow2,discard=unmap" \ + -netdev "user,id=n0,hostfwd=tcp:127.0.0.1:$LINUX_SSH_PORT-:22" \ + -device virtio-net-pci,netdev=n0 \ + -display none -serial "file:$DIR/serial.log" \ + -monitor "unix:$MONITOR,server,nowait" \ + -pidfile "$PIDFILE" -daemonize \ + "$@" +} + +monitor_cmd() { + printf '%s\n' "$1" | socat - "UNIX-CONNECT:$MONITOR" >/dev/null 2>&1 || true +} + +cmd_create() { + local image="${1:-}" + [[ -f "$image" ]] || die "usage: vm.sh create FEDORA_CLOUD_QCOW2" + [[ -f "$DISK" ]] && die "$DISK exists; remove $DIR to recreate" + ensure_ssh_key + mkdir -p "$DIR" + + # cloud-init seed with the test user, the SSH key and the packages that + # Portmaster needs at runtime. + local seed="$DIR/seed" + rm -rf "$seed" && mkdir -p "$seed" + cat >"$seed/meta-data" <<-EOF + instance-id: portmaster-vmtest + local-hostname: pm-vmtest + EOF + cat >"$seed/user-data" <<-EOF + #cloud-config + users: + - name: $LINUX_USER + sudo: ALL=(ALL) NOPASSWD:ALL + shell: /bin/bash + ssh_authorized_keys: + - $(cat "$VMTEST_SSH_KEY.pub") + growpart: {mode: auto, devices: ['/']} + packages: [iptables-nft, nftables, conntrack-tools, bind-utils, rsync, jq] + runcmd: + # The cloud kernel ships without most netfilter modules (nfqueue). + - dnf install -y "kernel-modules-\$(uname -r)" "kernel-modules-extra-\$(uname -r)" || dnf install -y kernel-modules kernel-modules-extra + - touch /var/lib/vmtest-ready + EOF + xorriso -as mkisofs -quiet -J -r -V cidata -o "$DIR/seed.iso" "$seed" + rm -rf "$seed" + + qemu-img create -q -f qcow2 -F qcow2 -b "$(realpath "$image")" "$DISK" 30G + + log "booting and provisioning the VM" + start_qemu -drive "file=$DIR/seed.iso,media=cdrom,readonly=on" + wait_for_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 600 || die "SSH did not come up; see $DIR/serial.log" + log "waiting for cloud-init" + vm_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 'until [ -f /var/lib/vmtest-ready ]; do sleep 5; done; sudo cloud-init status --wait >/dev/null || true' + + # Reboot so that the kernel modules match, then keep a clean snapshot. + cmd_stop + start_qemu + wait_for_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 300 || die "SSH did not come up after reboot" + vm_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 'sudo modprobe nfnetlink_queue && sudo modprobe xt_NFQUEUE && uname -r' + cmd_stop + qemu-img snapshot -c clean "$DISK" + log "Linux VM is ready (snapshot \"clean\" taken)" +} + +cmd_start() { + start_qemu + wait_for_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 300 || die "SSH did not come up" + log "Linux VM is ready" +} + +cmd_stop() { + vm_running "$PIDFILE" || { log "VM not running"; return; } + vm_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 'sudo systemctl poweroff' 2>/dev/null || monitor_cmd system_powerdown + for _ in $(seq 1 60); do + vm_running "$PIDFILE" || { log "VM stopped"; return; } + sleep 1 + done + log "VM did not shut down, killing it" + kill "$(cat "$PIDFILE")" + sleep 1 +} + +cmd_reset() { + vm_running "$PIDFILE" && cmd_stop + qemu-img snapshot -a clean "$DISK" + log "VM reset to snapshot \"clean\"" +} + +cmd_status() { + if vm_running "$PIDFILE"; then + echo "running (pid $(cat "$PIDFILE"))" + vm_ssh "$LINUX_SSH_PORT" "$LINUX_USER" 'uname -sr' 2>/dev/null || echo "ssh: not reachable" + else + echo "stopped" + fi +} + +case "${1:-}" in +create) shift; cmd_create "$@" ;; +start) cmd_start ;; +stop) cmd_stop ;; +reset) cmd_reset ;; +status) cmd_status ;; +ssh) shift; vm_ssh "$LINUX_SSH_PORT" "$LINUX_USER" "$@" ;; +*) sed -n '2,10p' "$0"; exit 2 ;; +esac diff --git a/tools/vmtest/proxmox.sh b/tools/vmtest/proxmox.sh new file mode 100644 index 000000000..c19153f76 --- /dev/null +++ b/tools/vmtest/proxmox.sh @@ -0,0 +1,146 @@ +# Proxmox backend of the VM test suite. Sourced by common.sh, do not run it. +# +# With VMTEST_BACKEND=proxmox the test VMs run on a Proxmox VE host instead +# of local QEMU. The host is reached with `ssh $PVE_HOST` (set up an alias in +# ~/.ssh/config with key login as root). The VMs sit on the host's LAN bridge +# and get their address by DHCP; the suite finds it from the VM's MAC address +# on the host and connects through the host (ProxyJump), so the VMs do not +# need to be routable from this machine. + +PVE_HOST="${VMTEST_PVE_HOST:-proxmox}" +PVE_BRIDGE="${VMTEST_PVE_BRIDGE:-vmbr0}" +LINUX_VMID="${VMTEST_LINUX_VMID:-900}" +WINDOWS_VMID="${VMTEST_WINDOWS_VMID:-901}" + +# One shared connection to the host for all calls of a run. +PVE_SSH_OPTS=(-o BatchMode=yes -o ControlMaster=auto + -o "ControlPath=$HOME/.ssh/cm-vmtest-%C" -o ControlPersist=120) + +# pve COMMAND... runs a shell command on the Proxmox host. +pve() { + ssh "${PVE_SSH_OPTS[@]}" "$PVE_HOST" "$@" +} + +# pve_vmid PORT maps the SSH port that names a VM in the scripts to its VMID. +pve_vmid() { + case "$1" in + "$LINUX_SSH_PORT") echo "$LINUX_VMID" ;; + "$WINDOWS_SSH_PORT") echo "$WINDOWS_VMID" ;; + *) die "no Proxmox VM for port $1" ;; + esac +} + +# pve_vm_ip VMID prints the VM's current IPv4 address. It refreshes the +# host's neighbour entries for the VM's MAC and, if none answers, pings the +# bridge's subnet once so that the VM shows up via ARP (this works even when +# the guest firewall drops ICMP). +pve_vm_ip() { + local cache="$VMTEST_DIR/proxmox-$1.ip" ip + ip="$(pve bash -s -- "$1" "$PVE_BRIDGE" <<-'EOF' + vmid="$1" br="$2" + mac="$(qm config "$vmid" | sed -n 's/^net0: [a-z0-9]*=\([0-9A-Fa-f:]*\),.*/\1/p' | tr A-F a-f)" + [ -n "$mac" ] || exit 1 + lookup() { ip -4 neigh show dev "$br" | grep -i " $mac " | grep -E 'REACHABLE|DELAY|PERMANENT' | awk '{print $1; exit}'; } + for a in $(ip -4 neigh show dev "$br" | grep -i " $mac " | awk '{print $1}'); do ping -c1 -W1 "$a" >/dev/null 2>&1; done + found="$(lookup)" + if [ -z "$found" ]; then + net="$(ip -4 -o addr show dev "$br" | awk '{print $4; exit}')" + prefix="${net%.*}" + for i in $(seq 1 254); do ping -c1 -W1 "$prefix.$i" >/dev/null 2>&1 & done + wait + found="$(lookup)" + fi + [ -n "$found" ] && echo "$found" + EOF + )" || return 1 + [[ -n "$ip" ]] || return 1 + echo "$ip" >"$cache" + echo "$ip" +} + +# pve_ssh_target PORT prints the IP of the VM named by PORT, cached between +# calls; set PVE_IP_REFRESH=1 to look it up again. +pve_ssh_target() { + local vmid cache ip + vmid="$(pve_vmid "$1")" + cache="$VMTEST_DIR/proxmox-$vmid.ip" + if [[ -s "$cache" ]] && [[ "${PVE_IP_REFRESH:-0}" == 0 ]]; then + ip="$(cat "$cache")" + else + ip="$(pve_vm_ip "$vmid")" || return 1 + fi + echo "$ip" +} + +# pve_proxy_command is the ProxyCommand that tunnels VM SSH through the host. +pve_proxy_command() { + # Escape the host options' % for the outer ssh, which expands the command. + local opts="${PVE_SSH_OPTS[*]}" + printf 'ssh %s %s -W %%h:%%p' "${opts//%/%%}" "$PVE_HOST" +} + +# pve_vm_main VMID KIND COMMAND... implements vm.sh for the Proxmox backend. +pve_vm_main() { + local vmid="$1" kind="$2" port user + shift 2 + if [[ "$kind" == linux ]]; then port="$LINUX_SSH_PORT" user="$LINUX_USER"; else port="$WINDOWS_SSH_PORT" user="$WINDOWS_USER"; fi + case "${1:-}" in + create) + die "on Proxmox, import the VM instead of creating it; see tools/vmtest/README.md" + ;; + start) + pve qm status "$vmid" | grep -q running && die "VM $vmid already running" + pve qm start "$vmid" + rm -f "$VMTEST_DIR/proxmox-$vmid.ip" + wait_for_ssh "$port" "$user" 600 || die "SSH did not come up" + log "$kind VM $vmid is ready ($(cat "$VMTEST_DIR/proxmox-$vmid.ip"))" + ;; + stop) + pve qm status "$vmid" | grep -q running || { log "VM not running"; return; } + if [[ "$kind" == linux ]]; then + vm_ssh "$port" "$user" 'sudo systemctl poweroff' 2>/dev/null || true + else + vm_ssh "$port" "$user" 'Stop-Computer -Force' 2>/dev/null || true + fi + # qm shutdown sends ACPI if the guest did not go down by itself, and + # stops it hard after the timeout. + pve qm shutdown "$vmid" --timeout 120 --forceStop 1 >/dev/null 2>&1 || true + log "VM stopped" + ;; + reset) + pve qm listsnapshot "$vmid" | grep -q ' clean ' || die "VM $vmid has no snapshot \"clean\"" + pve qm status "$vmid" | grep -q running && "$0" stop + pve qm rollback "$vmid" clean + log "VM reset to snapshot \"clean\"" + ;; + status) + local st + st="$(pve qm status "$vmid" | awk '{print $2}')" + echo "$st (Proxmox VM $vmid on $PVE_HOST)" + if [[ "$st" == running ]]; then + if [[ "$kind" == linux ]]; then + vm_ssh "$port" "$user" 'uname -sr' 2>/dev/null || echo "ssh: not reachable" + else + vm_ssh "$port" "$user" '$PSVersionTable.OS' 2>/dev/null || echo "ssh: not reachable" + fi + fi + ;; + ssh) + shift + vm_ssh "$port" "$user" "$@" + ;; + *) + sed -n '2,10p' "$0" + echo "Backend: Proxmox VM $vmid on $PVE_HOST (VMTEST_BACKEND=proxmox)" + exit 2 + ;; + esac +} + +# pve_serial_capture VMID FILE copies the VM's serial console to FILE in the +# background (as local QEMU does with -serial file:). Prints the PID. +pve_serial_capture() { + ssh -n "${PVE_SSH_OPTS[@]}" "$PVE_HOST" \ + "socat -u UNIX-CONNECT:/var/run/qemu-server/$1.serial0 STDOUT" >>"$2" 2>/dev/null .log. +$ErrorActionPreference = 'Continue' +$root = $PSScriptRoot +$results = Join-Path $root 'results' +Remove-Item -Recurse -Force $results -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Path $results | Out-Null + +$pass = 0; $fail = 0; $failed = @() +$bins = Get-ChildItem -Path $root -Recurse -Filter 'pkg.test.exe' | Sort-Object FullName +foreach ($bin in $bins) { + $rel = $bin.DirectoryName.Substring($root.Length).TrimStart('\') -replace '\\', '/' + $logf = Join-Path $results (($rel -replace '/', '_') + '.log') + $sw = [Diagnostics.Stopwatch]::StartNew() + Push-Location $bin.DirectoryName + $proc = Start-Process -FilePath $bin.FullName -NoNewWindow -PassThru ` + -RedirectStandardOutput $logf -RedirectStandardError "$logf.err" ` + -ArgumentList (@('-test.short', '-test.count=1', '-test.timeout=10m') + $args) + # Without querying the handle, ExitCode stays empty after WaitForExit. + $null = $proc.Handle + if (-not $proc.WaitForExit(15 * 60 * 1000)) { $proc.Kill(); $rc = 124 } else { $rc = $proc.ExitCode } + Pop-Location + Get-Content "$logf.err" -ErrorAction SilentlyContinue | Add-Content $logf + Remove-Item "$logf.err" -ErrorAction SilentlyContinue + $dur = [int]$sw.Elapsed.TotalSeconds + if ($rc -eq 0) { + $pass++ + '{0,-6}{1,-60} {2,4}s' -f 'ok', $rel, $dur + Remove-Item $logf + } else { + $fail++ + $failed += $rel + '{0,-6}{1,-60} {2,4}s (exit {3})' -f 'FAIL', $rel, $dur, $rc + } +} +'' +"passed: $pass failed: $fail" +foreach ($f in $failed) { " failed: $f" } +if ($fail -gt 0) { exit 1 } diff --git a/tools/vmtest/run-tests.sh b/tools/vmtest/run-tests.sh new file mode 100755 index 000000000..4a6d57eb7 --- /dev/null +++ b/tools/vmtest/run-tests.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Runs all compiled tests of a bundle (see build-tests.sh) on Linux. +# Run it from the bundle root, as root to cover privileged code paths: +# +# sudo ./run-tests.sh [EXTRA TEST FLAGS...] +# +# Prints one line per package and a summary; exits non-zero on failures. +# Full output of failed packages is in results/.log. +set -uo pipefail + +root="$(cd "$(dirname "$0")" && pwd)" +results="$root/results" +rm -rf "$results" && mkdir -p "$results" + +pass=0 fail=0 +failed=() +while IFS= read -r bin; do + dir="$(dirname "$bin")" + rel="${dir#"$root"/}" + logf="$results/${rel//\//_}.log" + start=$(date +%s) + (cd "$dir" && timeout 15m ./pkg.test -test.short -test.count=1 -test.timeout=10m "$@") >"$logf" 2>&1 + rc=$? + dur=$(($(date +%s) - start)) + if ((rc == 0)); then + ((pass++)) + printf 'ok %-60s %4ss\n' "$rel" "$dur" + rm -f "$logf" + else + ((fail++)) + failed+=("$rel") + printf 'FAIL %-60s %4ss (exit %d)\n' "$rel" "$dur" "$rc" + fi +done < <(find "$root" -name pkg.test -type f | sort) + +echo +echo "passed: $pass failed: $fail" +for f in "${failed[@]}"; do echo " failed: $f"; done +((fail == 0)) diff --git a/tools/vmtest/test-linux.sh b/tools/vmtest/test-linux.sh new file mode 100755 index 000000000..e1b82def8 --- /dev/null +++ b/tools/vmtest/test-linux.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# Run the test suite in the Linux VM as root: +# +# test-linux.sh [unit|smoke|all] (default: all) +# test-linux.sh soak [MINUTES] (not part of all; default 60 minutes) +# +# The VM is reset to its clean snapshot first, so every run starts from the +# same state. Results are written to $VMTEST_WORK/results/linux-*. +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +what="${1:-all}" +bundle="$VMTEST_WORK/bundle-linux" +results="$VMTEST_WORK/results/linux-$(date +%Y%m%d-%H%M%S)" +mkdir -p "$results" +SSH=(vm_ssh "$LINUX_SSH_PORT" "$LINUX_USER") + +"$VMTEST_REPO/tools/vmtest/linux/vm.sh" reset +"$VMTEST_REPO/tools/vmtest/linux/vm.sh" start +trap '"$VMTEST_REPO/tools/vmtest/linux/vm.sh" stop' EXIT + +rc=0 +if [[ "$what" == unit || "$what" == all ]]; then + "$VMTEST_REPO/tools/vmtest/build-tests.sh" linux "$bundle" + log "copying test bundle" + rsync -a --delete -e "$(vm_rsh "$LINUX_SSH_PORT")" \ + "$bundle/" "$(vm_dest "$LINUX_SSH_PORT" "$LINUX_USER" bundle/)" + log "running unit tests as root" + "${SSH[@]}" 'cd bundle && sudo ./run-tests.sh' | tee "$results/unit.txt" || rc=1 + "${SSH[@]}" 'sudo tar -C bundle -cf - results' | tar -C "$results" -xf - 2>/dev/null || true +fi + +if [[ "$what" == smoke || "$what" == all ]]; then + log "building portmaster-core" + (cd "$VMTEST_REPO" && GOOS=linux CGO_ENABLED=0 "$(go_bin)" build -o "$results/portmaster-core" ./cmds/portmaster-core) + vm_scp "$LINUX_SSH_PORT" "$LINUX_USER" "$results/portmaster-core" "$VMTEST_REPO/tools/vmtest/linux/smoke.sh" "/home/$LINUX_USER/" + # Run detached from the SSH session, as Portmaster may hold SSH while it + # intercepts. The test reports on the serial console, which QEMU writes + # to serial.log on the host, so the result arrives even without SSH. + serial="$LINUX_DIR/serial.log" + capture_pid="" + if [[ "$VMTEST_BACKEND" == proxmox ]]; then + serial="$results/serial.log" + : >"$serial" + capture_pid="$(pve_serial_capture "$LINUX_VMID" "$serial")" + sleep 2 + fi + log "running smoke test as root (live output: $serial)" + offset=$(stat -c %s "$serial") + "${SSH[@]}" 'sudo systemd-run --unit=pm-smoke --collect bash -c "bash /home/'"$LINUX_USER"'/smoke.sh /home/'"$LINUX_USER"'/portmaster-core 2>&1 | tee /dev/ttyS0"' + waited=0 + until tail -c +"$((offset + 1))" "$serial" | grep -qa 'SMOKE TEST \(PASSED\|FAILED\)'; do + sleep 10 + ((waited += 10)) + ((waited < 1800)) || { log "smoke test did not finish within 30 min"; rc=1; break; } + done + [[ -n "$capture_pid" ]] && kill "$capture_pid" 2>/dev/null + tail -c +"$((offset + 1))" "$serial" | tr -d '\r' | sed -n '/^== Before start/,/^SMOKE TEST/p' | tee "$results/smoke.txt" + grep -q 'SMOKE TEST PASSED' "$results/smoke.txt" || rc=1 + "${SSH[@]}" 'sudo cat /tmp/pm-smoke/core.log' >"$results/core.log" 2>/dev/null || true +fi + +if [[ "$what" == soak ]]; then + minutes="${2:-60}" + log "building portmaster-core" + (cd "$VMTEST_REPO" && GOOS=linux CGO_ENABLED=0 "$(go_bin)" build -o "$results/portmaster-core" ./cmds/portmaster-core) + vm_scp "$LINUX_SSH_PORT" "$LINUX_USER" "$results/portmaster-core" "$VMTEST_REPO/tools/vmtest/linux/soak.sh" "/home/$LINUX_USER/" + # Like the smoke test: run detached and report on the serial console. + serial="$LINUX_DIR/serial.log" + capture_pid="" + if [[ "$VMTEST_BACKEND" == proxmox ]]; then + serial="$results/serial.log" + : >"$serial" + capture_pid="$(pve_serial_capture "$LINUX_VMID" "$serial")" + sleep 2 + fi + log "running soak test for $minutes minutes as root (live output: $serial)" + offset=$(stat -c %s "$serial") + "${SSH[@]}" 'sudo systemd-run --unit=pm-soak --collect bash -c "bash /home/'"$LINUX_USER"'/soak.sh /home/'"$LINUX_USER"'/portmaster-core '"$minutes"' 2>&1 | tee /dev/ttyS0"' + waited=0 + limit=$(((minutes + 15) * 60)) + until tail -c +"$((offset + 1))" "$serial" | grep -qa 'SOAK \(TEST PASSED\|TEST FAILED\|FAILED\|INCONCLUSIVE\)'; do + sleep 30 + ((waited += 30)) + ((waited < limit)) || { log "soak test did not finish in time"; rc=1; break; } + done + [[ -n "$capture_pid" ]] && kill "$capture_pid" 2>/dev/null + tail -c +"$((offset + 1))" "$serial" | tr -d '\r' | sed -n '/^portmaster-core running/,/^SOAK/p' | tee "$results/soak.txt" + grep -q 'SOAK TEST PASSED' "$results/soak.txt" || rc=1 + "${SSH[@]}" 'sudo cat /tmp/pm-soak/samples.csv' >"$results/samples.csv" 2>/dev/null || true + "${SSH[@]}" 'sudo cat /tmp/pm-soak/core.log' >"$results/core.log" 2>/dev/null || true +fi + +log "results in $results" +exit $rc diff --git a/tools/vmtest/test-windows.sh b/tools/vmtest/test-windows.sh new file mode 100755 index 000000000..29586c836 --- /dev/null +++ b/tools/vmtest/test-windows.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Run the test suite in the Windows VM as administrator: +# +# test-windows.sh [unit|smoke|all] (default: unit) +# test-windows.sh soak [MINUTES] (not part of all; default 60 minutes) +# +# Results are written to $VMTEST_WORK/results/windows-*. +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +what="${1:-unit}" +bundle="$VMTEST_WORK/bundle-windows" +results="$VMTEST_WORK/results/windows-$(date +%Y%m%d-%H%M%S)" +mkdir -p "$results" +SSH=(vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER") +VM="$VMTEST_REPO/tools/vmtest/windows/vm.sh" + +started_vm=0 +if ! "${SSH[@]}" 'exit 0' 2>/dev/null; then + "$VM" start + started_vm=1 +fi +trap '((started_vm)) && "$VM" stop' EXIT + +rc=0 +if [[ "$what" == unit || "$what" == all ]]; then + "$VMTEST_REPO/tools/vmtest/build-tests.sh" windows "$bundle" + log "copying test bundle" + tar -C "$bundle" -czf "$VMTEST_WORK/bundle-windows.tgz" . + "${SSH[@]}" 'Remove-Item -Recurse -Force C:\vmtest\bundle -ErrorAction SilentlyContinue; New-Item -ItemType Directory -Force C:\vmtest\bundle | Out-Null' + vm_scp "$WINDOWS_SSH_PORT" "$WINDOWS_USER" "$VMTEST_WORK/bundle-windows.tgz" 'C:/vmtest/bundle.tgz' + "${SSH[@]}" 'tar -xzf C:\vmtest\bundle.tgz -C C:\vmtest\bundle; Remove-Item C:\vmtest\bundle.tgz' + log "running unit tests as administrator" + "${SSH[@]}" 'powershell -NoProfile -ExecutionPolicy Bypass -File C:\vmtest\bundle\run-tests.ps1; exit $LASTEXITCODE' | tee "$results/unit.txt" || rc=1 + "${SSH[@]}" 'tar -cf C:\vmtest\results.tar -C C:\vmtest\bundle results' >/dev/null 2>&1 && + vm_fetch "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'C:/vmtest/results.tar' "$results/results.tar" && + tar -C "$results" -xf "$results/results.tar" && rm -f "$results/results.tar" +fi + +if [[ "$what" == smoke || "$what" == all ]]; then + log "building portmaster-core.exe" + (cd "$VMTEST_REPO" && GOOS=windows GOARCH=amd64 CGO_ENABLED=0 "$(go_bin)" build -o "$results/portmaster-core.exe" ./cmds/portmaster-core) + vm_scp "$WINDOWS_SSH_PORT" "$WINDOWS_USER" "$results/portmaster-core.exe" "$VMTEST_REPO/tools/vmtest/windows/smoke.ps1" "$VMTEST_REPO/tools/vmtest/windows/smoke-task.ps1" 'C:/vmtest/' + # WINDOWS_CORE_DLL: test this core DLL instead of the downloaded one. + vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'Remove-Item C:\vmtest\portmaster-core.dll -ErrorAction SilentlyContinue' || true + if [[ -n "${WINDOWS_CORE_DLL:-}" ]]; then + log "using core DLL $WINDOWS_CORE_DLL" + vm_scp "$WINDOWS_SSH_PORT" "$WINDOWS_USER" "$WINDOWS_CORE_DLL" 'C:/vmtest/portmaster-core.dll' + fi + log "running smoke test as administrator" + # Run as a scheduled task, detached from the SSH session: while Portmaster + # starts intercepting, the session may be dropped. Then wait for the + # result with new sessions. + "${SSH[@]}" ' + Remove-Item C:\vmtest\smoke.txt, C:\vmtest\smoke.done -ErrorAction SilentlyContinue + $action = New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -ExecutionPolicy Bypass -File C:\vmtest\smoke-task.ps1" + Register-ScheduledTask -TaskName pm-smoke -Action $action -User SYSTEM -RunLevel Highest -Force | Out-Null + Start-ScheduledTask -TaskName pm-smoke' + waited=0 + until vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'if (-not (Test-Path C:\vmtest\smoke.done)) { exit 1 }' 2>/dev/null; do + sleep 15 + ((waited += 15)) + ((waited < 1800)) || { log "smoke test did not finish within 30 min"; rc=1; break; } + done + "${SSH[@]}" 'Get-Content C:\vmtest\smoke.txt' | tee "$results/smoke.txt" + [[ "$("${SSH[@]}" '(Get-Content C:\vmtest\smoke.done).Trim()' 2>/dev/null | tr -d '\r')" == 0 ]] || rc=1 + "${SSH[@]}" 'Unregister-ScheduledTask -TaskName pm-smoke -Confirm:$false' >/dev/null 2>&1 || true + vm_fetch "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'C:/vmtest/pm-smoke/core.log' "$results/core.log" 2>/dev/null || true +fi + +if [[ "$what" == soak ]]; then + minutes="${2:-60}" + log "building portmaster-core.exe" + (cd "$VMTEST_REPO" && GOOS=windows GOARCH=amd64 CGO_ENABLED=0 "$(go_bin)" build -o "$results/portmaster-core.exe" ./cmds/portmaster-core) + vm_scp "$WINDOWS_SSH_PORT" "$WINDOWS_USER" "$results/portmaster-core.exe" "$VMTEST_REPO/tools/vmtest/windows/soak.ps1" 'C:/vmtest/' + log "running soak test for $minutes minutes as administrator" + # Like the smoke test: run as a scheduled task, detached from SSH. + "${SSH[@]}" " + Remove-Item C:\\vmtest\\soak.txt, C:\\vmtest\\soak.done -ErrorAction SilentlyContinue + Set-Content -Path C:\\vmtest\\soak-task.ps1 -Value '& C:\\vmtest\\soak.ps1 -Core C:\\vmtest\\portmaster-core.exe -Minutes $minutes *> C:\\vmtest\\soak.txt; Set-Content -Path C:\\vmtest\\soak.done -Value \$LASTEXITCODE' + \$action = New-ScheduledTaskAction -Execute powershell.exe -Argument '-NoProfile -ExecutionPolicy Bypass -File C:\\vmtest\\soak-task.ps1' + Register-ScheduledTask -TaskName pm-soak -Action \$action -User SYSTEM -RunLevel Highest -Force | Out-Null + Start-ScheduledTask -TaskName pm-soak" + waited=0 + limit=$(((minutes + 20) * 60)) + until vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'if (-not (Test-Path C:\vmtest\soak.done)) { exit 1 }' 2>/dev/null; do + sleep 30 + ((waited += 30)) + ((waited < limit)) || { log "soak test did not finish in time"; rc=1; break; } + done + "${SSH[@]}" 'Get-Content C:\vmtest\soak.txt' | tee "$results/soak.txt" + [[ "$("${SSH[@]}" '(Get-Content C:\vmtest\soak.done).Trim()' 2>/dev/null | tr -d '\r')" == 0 ]] || rc=1 + "${SSH[@]}" 'Unregister-ScheduledTask -TaskName pm-soak -Confirm:$false' >/dev/null 2>&1 || true + vm_fetch "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'C:/vmtest/pm-soak/samples.csv' "$results/samples.csv" 2>/dev/null || true + vm_fetch "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 'C:/vmtest/pm-soak/core.log' "$results/core.log" 2>/dev/null || true +fi + +log "results in $results" +exit $rc diff --git a/tools/vmtest/windows/autounattend.xml.in b/tools/vmtest/windows/autounattend.xml.in new file mode 100644 index 000000000..e901de9fb --- /dev/null +++ b/tools/vmtest/windows/autounattend.xml.in @@ -0,0 +1,103 @@ + + + + + + de-DE + de-DE + de-DE + de-DE + de-DE + + + + + 1reg add HKLM\SYSTEM\Setup\LabConfig /v BypassTPMCheck /t REG_DWORD /d 1 /f + 2reg add HKLM\SYSTEM\Setup\LabConfig /v BypassSecureBootCheck /t REG_DWORD /d 1 /f + + + + 0 + true + + 1EFI300 + 2MSR16 + 3Primarytrue + + + 11FAT32 + 23NTFSC + + + + + + 03 + + + + VK7JG-NPHTM-C97JM-9MPGT-3V66TNever + true + + + + + + PM-VMTEST + W. Europe Standard Time + + + + + 1 + reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\OOBE /v BypassNRO /t REG_DWORD /d 1 /f + + + + + + + de-DE + de-DE + de-DE + de-DE + + + + true + true + true + true + true + 3 + + + + + tester + Administrators + __PASSWORD__true</PlainText></Password> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + <AutoLogon> + <Enabled>true</Enabled> + <LogonCount>1</LogonCount> + <Username>tester</Username> + <Password><Value>__PASSWORD__</Value><PlainText>true</PlainText></Password> + </AutoLogon> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Order>1</Order> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "$d = (Get-PSDrive -PSProvider FileSystem | Where-Object { Test-Path ($_.Root + 'vmtest-setup.ps1') } | Select-Object -First 1).Root; &amp; ($d + 'vmtest-setup.ps1') -ConfigDrive $d *&gt; C:\vmtest-setup.log"</CommandLine> + <Description>Set up SSH access for the VM test suite</Description> + </SynchronousCommand> + </FirstLogonCommands> + </component> + </settings> +</unattend> diff --git a/tools/vmtest/windows/smoke-task.ps1 b/tools/vmtest/windows/smoke-task.ps1 new file mode 100644 index 000000000..f88904d40 --- /dev/null +++ b/tools/vmtest/windows/smoke-task.ps1 @@ -0,0 +1,6 @@ +# Runs smoke.ps1 as a scheduled task (see test-windows.sh) and records its +# output and exit code for the host to collect. +$dll = @{} +if (Test-Path C:\vmtest\portmaster-core.dll) { $dll = @{ Dll = 'C:\vmtest\portmaster-core.dll' } } +& C:\vmtest\smoke.ps1 -Core C:\vmtest\portmaster-core.exe @dll *> C:\vmtest\smoke.txt +Set-Content -Path C:\vmtest\smoke.done -Value $LASTEXITCODE diff --git a/tools/vmtest/windows/smoke.ps1 b/tools/vmtest/windows/smoke.ps1 new file mode 100644 index 000000000..3c59ac829 --- /dev/null +++ b/tools/vmtest/windows/smoke.ps1 @@ -0,0 +1,221 @@ +# Integration smoke test of portmaster-core on Windows. Runs inside the test +# VM as administrator (see test-windows.sh): +# +# .\smoke.ps1 -Core C:\vmtest\portmaster-core.exe [-Dll C:\vmtest\portmaster-core.dll] +# +# With -Dll, the given core DLL replaces the downloaded one and must load. +# Fetches the signed release binaries (including the kernel extension) with +# the update command, then starts the given portmaster-core with packet +# interception and checks that it intercepts and filters traffic, answers its +# API and shuts down cleanly. Exits non-zero if any check fails. +param( + [Parameter(Mandatory = $true)][string]$Core, + [string]$Dll +) + +$ErrorActionPreference = 'Continue' +$ProgressPreference = 'SilentlyContinue' + +$Work = 'C:\vmtest\pm-smoke' +$Bin = Join-Path $Work 'bin' +$Data = Join-Path $Work 'data' +$Log = Join-Path $Work 'core.log' +$Api = 'http://127.0.0.1:817/api/v1' +$Curl = 'C:\Windows\System32\curl.exe' +$Allowed = 'example.com' +$Blocked = 'example.org' +# A name whose CNAME points outside the blocked zone (safing/portmaster#2306). +$CnameBlocked = 'tr.archive.ubuntu.com' +$CnameZone = 'ubuntu.com' + +$script:failures = 0 +function Pass($msg) { Write-Output " PASS $msg" } +function Fail($msg) { Write-Output " FAIL $msg"; $script:failures++ } +function Check($msg, [scriptblock]$test) { + $ok = $false + try { $ok = [bool](& $test) } catch { $ok = $false } + if ($ok) { Pass $msg } else { Fail $msg } +} +function Step($msg) { Write-Output ''; Write-Output "== $msg" } + +function HttpsOk($domain) { + & $Curl -sS -o NUL --max-time 15 "https://$domain/" 2>$null + return $LASTEXITCODE -eq 0 +} +function HttpOk($domain) { + & $Curl -sS -o NUL --max-time 15 "http://$domain/" 2>$null + return $LASTEXITCODE -eq 0 +} +function Resolves($domain) { + $r = Resolve-DnsName -Name $domain -Type A -DnsOnly -QuickTimeout -ErrorAction SilentlyContinue | + Where-Object { $_.IPAddress -and $_.IPAddress -ne '0.0.0.0' } + return [bool]$r +} +# UdpDatagramsReceived sends three datagrams to a local UDP listener and +# returns how many arrived (safing/portmaster#2286). With -CloseAfterEach, a +# new sender socket sends one datagram and closes right away. +function UdpDatagramsReceived($address, [switch]$CloseAfterEach) { + $listener = New-Object System.Net.Sockets.UdpClient(0) + $sender = $null + try { + $port = $listener.Client.LocalEndPoint.Port + $data = [Text.Encoding]::ASCII.GetBytes('portmaster-udp-test') + foreach ($i in 1..3) { + if ($null -eq $sender) { $sender = New-Object System.Net.Sockets.UdpClient } + [void]$sender.Send($data, $data.Length, $address, $port) + if ($CloseAfterEach) { $sender.Close(); $sender = $null } + Start-Sleep -Milliseconds 300 + } + $got = 0 + $from = New-Object System.Net.IPEndPoint([Net.IPAddress]::Any, 0) + $listener.Client.ReceiveTimeout = 1000 + try { while ($true) { [void]$listener.Receive([ref]$from); $got++ } } catch { } + return $got + } finally { + if ($null -ne $sender) { $sender.Close() } + $listener.Close() + } +} + +function ApiReady { + & $Curl -sf --max-time 5 "$Api/ready" 2>$null | Out-Null + return $LASTEXITCODE -eq 0 +} + +Remove-Item -Recurse -Force $Work -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Force -Path $Bin, $Data | Out-Null + +Step 'Before start' +Check "https://$Allowed reachable" { HttpsOk $Allowed } +# This also puts the name into the DNS Client cache: Portmaster must flush it +# on start, or the connection would have no domain and pass the rule below. +Check "http://$CnameBlocked reachable" { HttpOk $CnameBlocked } +Check 'UDP to a local listener on 127.0.0.1' { (UdpDatagramsReceived '127.0.0.1') -eq 3 } + +Step 'Release binaries' +& $Core update --bin-dir $Bin --data-dir $Data *>> $Log +# An installed upgrade that needs a restart is a success for the command. +$updateRc = $LASTEXITCODE +Check "update command succeeds (exit code $updateRc)" { $updateRc -eq 0 } +$kext = Get-ChildItem -Path $Bin -Recurse -Filter 'portmaster-kext*.sys' -ErrorAction SilentlyContinue | Select-Object -First 1 +if ($kext) { + Pass "kernel extension downloaded ($($kext.Name), signed by $((Get-AuthenticodeSignature $kext.FullName).SignerCertificate.Subject))" +} else { + Fail 'kernel extension downloaded' + Get-Content $Log -Tail 30 + exit 1 +} + +if ($Dll) { + $target = Get-ChildItem -Path $Bin -Recurse -Filter 'portmaster-core*.dll' -ErrorAction SilentlyContinue | Select-Object -First 1 + $targetPath = if ($target) { $target.FullName } else { Join-Path $Bin 'portmaster-core.dll' } + Copy-Item -Force $Dll $targetPath + Pass "core DLL replaced with $Dll" +} + +# Block one domain in the global settings. +# Also allow incoming SSH, as the test is controlled over SSH. +Set-Content -Path (Join-Path $Data 'config.json') -Encoding ASCII ` + -Value ('{"filter":{"endpoints":["- ' + $Blocked + '","- .' + $CnameZone + '"],"serviceEndpoints":["+ * TCP/22"]}}') + +Step 'Start' +$proc = Start-Process -FilePath $Core -PassThru -WindowStyle Hidden ` + -RedirectStandardOutput $Log -RedirectStandardError "$Log.err" ` + -ArgumentList @('--bin-dir', $Bin, '--data-dir', $Data, '--log-stdout', '--log', 'info', '--allowed-clients', $Curl) +# Without querying the handle, ExitCode stays empty after WaitForExit. +$null = $proc.Handle +$waited = 0 +while (-not (ApiReady)) { + Start-Sleep -Seconds 2 + $waited += 2 + if ($proc.HasExited -or $waited -ge 300) { + Fail "portmaster-core starts and reports ready (exited: $($proc.HasExited), waited ${waited}s)" + Get-Content $Log, "$Log.err" -Tail 30 -ErrorAction SilentlyContinue + exit 1 + } +} +Pass "portmaster-core starts and reports ready (${waited}s)" +Check 'DNS Client cache flushed' { Select-String -Path $Log -Quiet -SimpleMatch 'flushed the DNS Client cache' } +Check 'kernel extension service running' { (Get-Service -Name 'PortmasterKext' -ErrorAction SilentlyContinue).Status -eq 'Running' -or (sc.exe query type= driver | Select-String -Quiet 'PortmasterKext') } + +Step 'Filtering' +Start-Sleep -Seconds 3 +Check "$Allowed resolves" { Resolves $Allowed } +Check "https://$Allowed reachable" { HttpsOk $Allowed } +# Windows resolves names through the DNS Client service (svchost), so the +# per-app rule applies to the connection, not to the DNS query. +Write-Output " info: $Blocked resolves through the DNS Client service: $(Resolves $Blocked)" +Check "https://$Blocked is blocked" { -not (HttpsOk $Blocked) } +Check "http://$CnameBlocked is blocked by the rule for .$CnameZone (CNAME outside the zone)" { -not (HttpOk $CnameBlocked) } +# How fast a connection blocked by a rule fails (safing/portmaster#1981). +$sw = [Diagnostics.Stopwatch]::StartNew() +& $Curl -sS -o NUL --max-time 40 "http://$CnameBlocked/" 2>$null +$blockRc = $LASTEXITCODE +$sw.Stop() +$blockSecs = [math]::Round($sw.Elapsed.TotalSeconds, 1) +Check "a blocked connection fails at once, not by timeout (${blockSecs}s, curl exit code $blockRc)" { $blockRc -ne 0 -and $blockSecs -lt 5 } +Check 'UDP to a local listener on 127.0.0.1' { (UdpDatagramsReceived '127.0.0.1') -eq 3 } +# Known kext limitation: the first datagram of a socket waits for the verdict +# and is re-injected through the sending socket, so it is lost when the socket +# is already closed by then. +Write-Output " info: UDP from send-and-close sockets received: $(UdpDatagramsReceived '127.0.0.1' -CloseAfterEach) of 3" + +Step 'API' +Check 'ping endpoint' { & $Curl -sf --max-time 5 "$Api/ping" 2>$null | Out-Null; $LASTEXITCODE -eq 0 } +Start-Sleep -Seconds 3 +$body = '{"query":{"domain":{"$like":"%' + $Allowed + '%"}},"select":["id","verdict"],"pageSize":50}' +$bodyFile = Join-Path $Work 'query.json' +Set-Content -Path $bodyFile -Value $body -Encoding ASCII +$out = & $Curl -sf --max-time 10 -X POST "$Api/netquery/query" -H 'Content-Type: application/json' --data-binary "@$bodyFile" 2>$null +$n = 0 +try { $n = @(($out | Out-String | ConvertFrom-Json).results).Count } catch {} +if ($n -gt 0) { Pass "netquery lists connections to $Allowed ($n)" } else { Fail "netquery lists connections to $Allowed (got '$out')" } +$body = '{"query":{"remote_ip":{"$in":["' + (@(Resolve-DnsName -Name $CnameBlocked -Type A -ErrorAction SilentlyContinue | Where-Object IPAddress | ForEach-Object IPAddress) -join '","') + '"]}},"select":["domain","verdict"],"groupBy":["domain","verdict"],"pageSize":20}' +Set-Content -Path $bodyFile -Value $body -Encoding ASCII +Write-Output " info: connections to the IPs of ${CnameBlocked}: $(& $Curl -sf --max-time 10 -X POST "$Api/netquery/query" -H 'Content-Type: application/json' --data-binary "@$bodyFile" 2>$null)" +$code = 0 +try { + Invoke-WebRequest -UseBasicParsing -Method Post -Uri "$Api/netquery/query" -Body '{}' -TimeoutSec 10 | Out-Null + $code = 200 +} catch { $code = [int]$_.Exception.Response.StatusCode } +if ($code -eq 403 -or $code -eq 401) { Pass "API denies an unauthorized local client ($code)" } else { Fail "API denies an unauthorized local client (got $code)" } +# app/auth identifies the calling process and waits for the user to answer +# the prompt; without the process (safing/portmaster#2302 B1) it fails at once. +$authCode = & $Curl -s -o NUL -w '%{http_code}' --max-time 5 "$Api/app/auth?app-name=vmtest&read=user&write=user&ttl=1h" 2>$null +if ($authCode -eq '000') { Pass 'app/auth identifies the caller and waits for the prompt' } else { Fail "app/auth identifies the caller and waits for the prompt (got HTTP $authCode)" } + +Step 'Load' +$jobs = 1..40 | ForEach-Object { Start-Process -FilePath $Curl -PassThru -WindowStyle Hidden -ArgumentList @('-s', '-o', 'NUL', '--max-time', '10', "https://$Allowed/?n=$_") } +$jobs | ForEach-Object { $_.WaitForExit(20000) | Out-Null } +Check 'service alive after 40 parallel connections' { -not $proc.HasExited } +Check "https://$Allowed still reachable" { HttpsOk $Allowed } + +Step 'Shutdown' +& $Curl -sf --max-time 10 -X POST "$Api/core/shutdown" 2>$null | Out-Null +if ($proc.WaitForExit(60000)) { Pass 'portmaster-core stops within 60s' } else { Fail 'portmaster-core stops within 60s'; Stop-Process -Id $proc.Id -Force } +Check "exit code 0 (got $($proc.ExitCode))" { $proc.ExitCode -eq 0 } +Start-Sleep -Seconds 2 +Check "https://$Allowed reachable without Portmaster" { HttpsOk $Allowed } +Check "$Blocked resolves again without Portmaster" { Resolves $Blocked } + +Step 'Log' +Get-Content "$Log.err" -ErrorAction SilentlyContinue | Add-Content $Log +$panics = @(Select-String -Path $Log -Pattern '^panic:|fatal error:' -ErrorAction SilentlyContinue).Count +if ($panics -eq 0) { Pass 'no panics in the log' } else { Fail "$panics panics in the log" } +# The core DLL provides the ETW DNS integration. It fails to load when it +# needs a C runtime that the system does not have. +$dllLoaded = [bool](Select-String -Path $Log -Pattern 'integration: initialize successful' -SimpleMatch -ErrorAction SilentlyContinue) +if ($dllLoaded) { + Pass 'core DLL loaded' +} elseif ($Dll) { + Fail 'core DLL loaded' +} else { + Write-Output ' info: core DLL not loaded (the upstream DLL needs the VC++ runtime)' +} +$errors = @(Select-String -Path $Log -Pattern ' (ERR|CRT) ' -CaseSensitive -ErrorAction SilentlyContinue).Count +Write-Output " log: $(@(Get-Content $Log).Count) lines, $errors error lines (see core.log)" + +Write-Output '' +if ($script:failures -eq 0) { Write-Output 'SMOKE TEST PASSED'; exit 0 } +Write-Output "SMOKE TEST FAILED: $($script:failures) checks" +exit 1 diff --git a/tools/vmtest/windows/soak.ps1 b/tools/vmtest/windows/soak.ps1 new file mode 100644 index 000000000..0fdf5250d --- /dev/null +++ b/tools/vmtest/windows/soak.ps1 @@ -0,0 +1,129 @@ +# Soak test of portmaster-core on Windows. Runs inside the test VM as +# administrator (see test-windows.sh soak): +# +# .\soak.ps1 -Core C:\vmtest\portmaster-core.exe -Minutes 60 +# +# Fetches the signed release binaries (including the kernel extension), runs +# the given portmaster-core under constant traffic and samples its resource +# usage every minute, to find leaks that short tests do not show. Prints one +# line per sample and a summary of the growth between the samples after +# warm-up and the last ones. Exits non-zero if the service dies or a resource +# keeps growing well beyond the warm-up level. +param( + [Parameter(Mandatory = $true)][string]$Core, + [int]$Minutes = 60 +) + +$ErrorActionPreference = 'Continue' +$ProgressPreference = 'SilentlyContinue' + +$Work = 'C:\vmtest\pm-soak' +$Bin = Join-Path $Work 'bin' +$Data = Join-Path $Work 'data' +$Log = Join-Path $Work 'core.log' +$Csv = Join-Path $Work 'samples.csv' +$Api = 'http://127.0.0.1:817/api/v1' +$Curl = 'C:\Windows\System32\curl.exe' + +Remove-Item -Recurse -Force $Work -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Force -Path $Bin, $Data | Out-Null + +& $Core update --bin-dir $Bin --data-dir $Data *> (Join-Path $Work 'update.log') +# Allow incoming SSH, the test is controlled over SSH. +Set-Content -Path (Join-Path $Data 'config.json') -Encoding ASCII -Value '{"filter":{"serviceEndpoints":["+ * TCP/22"]}}' + +$proc = Start-Process -FilePath $Core -PassThru -WindowStyle Hidden ` + -RedirectStandardOutput $Log -RedirectStandardError "$Log.err" ` + -ArgumentList @('--bin-dir', $Bin, '--data-dir', $Data, '--log-stdout', '--log', 'warning', '--allowed-clients', $Curl) +$null = $proc.Handle +$ready = $false +for ($i = 0; $i -lt 150 -and -not $proc.HasExited; $i++) { + & $Curl -sf --max-time 5 "$Api/ready" 2>$null | Out-Null + if ($LASTEXITCODE -eq 0) { $ready = $true; break } + Start-Sleep -Seconds 2 +} +if (-not $ready) { + Write-Output 'SOAK FAILED: portmaster-core did not start' + Get-Content $Log, "$Log.err" -Tail 20 -ErrorAction SilentlyContinue + exit 1 +} +Write-Output "portmaster-core running (pid $($proc.Id)), soaking for $Minutes minutes" + +# Traffic: HTTPS to a few sites and DNS lookups of always new names, so that +# connections, DNS caches and the connection history keep changing. +$traffic = Start-Job -ScriptBlock { + param($Curl) + $sites = 'example.com', 'example.org', 'wikipedia.org', 'debian.org', 'kernel.org' + $i = 0 + while ($true) { + $i++ + $procs = foreach ($s in $sites) { + Start-Process -FilePath $Curl -PassThru -WindowStyle Hidden -ArgumentList @('-s', '-o', 'NUL', '--max-time', '10', "https://$s/?soak=$i") + } + 1..10 | ForEach-Object { Resolve-DnsName -Name "soak-$i-$_.example.com" -DnsOnly -QuickTimeout -ErrorAction SilentlyContinue | Out-Null } + $procs | ForEach-Object { $_.WaitForExit(15000) | Out-Null } + Start-Sleep -Seconds 1 + } +} -ArgumentList $Curl + +'minute,ws_kb,heap_kb,goroutines,handles,data_kb' | Set-Content -Path $Csv +$failed = $false +for ($m = 0; $m -le $Minutes; $m++) { + if ($proc.HasExited) { + Write-Output "SOAK FAILED: portmaster-core died after $m minutes (exit $($proc.ExitCode))" + Get-Content $Log, "$Log.err" -Tail 30 -ErrorAction SilentlyContinue + $failed = $true + break + } + $p = Get-Process -Id $proc.Id + $ws = [int]($p.WorkingSet64 / 1KB) + $handles = $p.HandleCount + $stack = & $Curl -sf --max-time 10 "$Api/debug/stack" 2>$null | Select-Object -First 1 + $goroutines = 0 + if ($stack -match 'goroutine profile: total (\d+)') { $goroutines = [int]$Matches[1] } + # The Go heap is the reliable measure for leaks: Windows trims and + # refills the working set independently of what the process uses. + $heapKb = 0 + # Prometheus metrics are served at /metrics, with a namespace prefix and + # possibly labels: portmaster_go_memstats_heap_inuse_bytes{...} VALUE + $metrics = & $Curl -sf --max-time 10 'http://127.0.0.1:817/metrics' 2>$null + $heapLine = $metrics | Select-String -Pattern '^(\w+_)?go_memstats_heap_inuse_bytes(\{[^}]*\})? ' | Select-Object -First 1 + if ($heapLine) { $heapKb = [int]([double]($heapLine.Line -split ' ')[-1] / 1KB) } + $dataKb = [int]((Get-ChildItem -Path $Data -Recurse -File -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum / 1KB) + "$m,$ws,$heapKb,$goroutines,$handles,$dataKb" | Add-Content -Path $Csv + 'minute {0,3}: ws {1,7} KB heap {2,7} KB goroutines {3,5} handles {4,5} data {5,7} KB' -f $m, $ws, $heapKb, $goroutines, $handles, $dataKb + if ($m -lt $Minutes) { Start-Sleep -Seconds 60 } +} + +Stop-Job $traffic -ErrorAction SilentlyContinue +Remove-Job $traffic -Force -ErrorAction SilentlyContinue +& $Curl -sf --max-time 10 -X POST "$Api/core/shutdown" 2>$null | Out-Null +if (-not $proc.WaitForExit(60000)) { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } +if ($failed) { exit 1 } + +# Compare the averages after warm-up with the averages at the end. The +# connection history keeps ended connections for 10 minutes, so memory only +# levels off after about 20 minutes under constant traffic. Handles vary with +# the connections open at each sample, so averages over 10 samples are +# compared. +$rows = Import-Csv $Csv +if ($rows.Count -lt 15) { Write-Output 'SOAK INCONCLUSIVE: too few samples'; exit 0 } +if ($rows.Count -ge 45) { + $early = $rows[20..29] + $late = $rows[($rows.Count - 10)..($rows.Count - 1)] +} else { + $early = $rows[5..9] + $late = $rows[($rows.Count - 5)..($rows.Count - 1)] +} +foreach ($check in @(@('heap_kb', 1.5), @('goroutines', 1.3), @('handles', 1.5))) { + $key, $limit = $check + $a = ($early | Measure-Object -Property $key -Average).Average + $b = ($late | Measure-Object -Property $key -Average).Average + $ratio = if ($a) { $b / $a } else { 0 } + $flag = if ($ratio -gt $limit) { 'GROWING' } else { 'ok' } + if ($ratio -gt $limit) { $failed = $true } + '{0,-11} after warm-up {1,9:N0} at the end {2,9:N0} ratio {3:N2} {4}' -f $key, $a, $b, $ratio, $flag +} +if ($failed) { Write-Output 'SOAK TEST FAILED'; exit 1 } +Write-Output 'SOAK TEST PASSED' +exit 0 diff --git a/tools/vmtest/windows/vm.sh b/tools/vmtest/windows/vm.sh new file mode 100755 index 000000000..be9bacf47 --- /dev/null +++ b/tools/vmtest/windows/vm.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# Manage the Windows 11 test VM. +# +# vm.sh create ISO install Windows unattended from ISO (30-60 min) +# vm.sh start start the installed VM +# vm.sh stop shut the VM down +# vm.sh status show whether the VM runs and SSH works +# vm.sh ssh [CMD] open a shell or run a PowerShell command in the VM +# +# The VM uses UEFI with Secure Boot and a software TPM, as Windows 11 +# requires. The screen is on VNC at 127.0.0.1:590$WINDOWS_VNC_DISPLAY. +source "$(dirname "${BASH_SOURCE[0]}")/../common.sh" + +if [[ "$VMTEST_BACKEND" == proxmox ]]; then + pve_vm_main "$WINDOWS_VMID" windows "$@" + exit +fi + +DIR="$WINDOWS_DIR" +DISK="$DIR/disk.qcow2" +VARS="$DIR/OVMF_VARS.fd" +PIDFILE="$DIR/qemu.pid" +MONITOR="$DIR/monitor.sock" +TPM_DIR="$DIR/tpm" + +start_tpm() { + mkdir -p "$TPM_DIR" + if [[ -S "$TPM_DIR/swtpm-sock" ]] && vm_running "$TPM_DIR/swtpm.pid"; then + return + fi + swtpm socket --tpm2 --daemon \ + --tpmstate "dir=$TPM_DIR" \ + --ctrl "type=unixio,path=$TPM_DIR/swtpm-sock" \ + --pid "file=$TPM_DIR/swtpm.pid" \ + --log "file=$TPM_DIR/swtpm.log,level=1" +} + +# start_qemu [EXTRA_ARGS...] starts the VM in the background. +start_qemu() { + vm_running "$PIDFILE" && die "VM already running" + start_tpm + qemu-system-x86_64 \ + -name portmaster-vmtest-windows \ + -machine q35,smm=on,accel=kvm \ + -cpu host -smp "$WINDOWS_CPUS" -m "$WINDOWS_MEM" \ + -global driver=cfi.pflash01,property=secure,value=on \ + -drive "if=pflash,format=raw,unit=0,readonly=on,file=$OVMF_DIR/OVMF_CODE.secboot.fd" \ + -drive "if=pflash,format=raw,unit=1,file=$VARS" \ + -chardev "socket,id=chrtpm,path=$TPM_DIR/swtpm-sock" \ + -tpmdev emulator,id=tpm0,chardev=chrtpm -device tpm-crb,tpmdev=tpm0 \ + -device ahci,id=ahci \ + -drive "file=$DISK,if=none,id=disk0,format=qcow2,discard=unmap" \ + -device ide-hd,drive=disk0,bus=ahci.0,bootindex=0 \ + -netdev "user,id=n0,hostfwd=tcp:127.0.0.1:$WINDOWS_SSH_PORT-:22" \ + -device e1000e,netdev=n0 \ + -device qemu-xhci -device usb-tablet \ + -vnc "127.0.0.1:$WINDOWS_VNC_DISPLAY" \ + -monitor "unix:$MONITOR,server,nowait" \ + -pidfile "$PIDFILE" -daemonize \ + "$@" +} + +monitor_cmd() { + printf '%s\n' "$1" | socat - "UNIX-CONNECT:$MONITOR" >/dev/null 2>&1 || true +} + +cmd_create() { + local iso="${1:-}" + [[ -f "$iso" ]] || die "usage: vm.sh create WINDOWS_ISO" + [[ -f "$DISK" ]] && die "$DISK exists; remove $DIR to reinstall" + ensure_ssh_key + mkdir -p "$DIR" + + # Credentials for the local test account, never stored in the repository. + local password + password="$(python3 -c 'import secrets; print(secrets.token_urlsafe(15).replace("-", "x").replace("_", "y"))')Aa1" + umask 077 + printf 'user=%s\npassword=%s\n' "$WINDOWS_USER" "$password" >"$DIR/credentials" + umask 022 + + # Config CD with the answer file, the setup script and the public key. + local cfg="$DIR/config" + rm -rf "$cfg" && mkdir -p "$cfg" + sed "s|__PASSWORD__|$password|g" "$(dirname "$0")/autounattend.xml.in" >"$cfg/autounattend.xml" + cp "$(dirname "$0")/vmtest-setup.ps1" "$cfg/vmtest-setup.ps1" + cp "$VMTEST_SSH_KEY.pub" "$cfg/vmtest_id_ed25519.pub" + xorriso -as mkisofs -quiet -J -r -V VMTEST_CFG -o "$DIR/config.iso" "$cfg" + rm -rf "$cfg" + + qemu-img create -q -f qcow2 "$DISK" 80G + cp "$OVMF_DIR/OVMF_VARS.secboot.fd" "$VARS" + + log "installing Windows; watch on VNC 127.0.0.1:590$WINDOWS_VNC_DISPLAY" + start_qemu \ + -drive "file=$iso,media=cdrom,if=none,id=cd0,readonly=on" \ + -device ide-cd,drive=cd0,bus=ahci.1,bootindex=1 \ + -drive "file=$DIR/config.iso,media=cdrom,if=none,id=cd1,readonly=on" \ + -device ide-cd,drive=cd1,bus=ahci.2 + + # Answer the "Press any key to boot from CD or DVD" prompt. + for _ in $(seq 1 40); do + monitor_cmd "sendkey ret" + sleep 0.5 + done + + log "waiting for setup and first logon (up to 90 min)" + if ! wait_for_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 5400; then + die "SSH did not come up; check VNC and C:\\vmtest-setup.log" + fi + log "Windows VM is ready" +} + +cmd_start() { + start_qemu + log "waiting for SSH" + wait_for_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" 600 || die "SSH did not come up" + log "Windows VM is ready" +} + +cmd_stop() { + vm_running "$PIDFILE" || { log "VM not running"; return; } + vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" "Stop-Computer -Force" 2>/dev/null || monitor_cmd system_powerdown + for _ in $(seq 1 60); do + vm_running "$PIDFILE" || { log "VM stopped"; return; } + sleep 2 + done + log "VM did not shut down, killing it" + kill "$(cat "$PIDFILE")" +} + +cmd_status() { + if vm_running "$PIDFILE"; then + echo "running (pid $(cat "$PIDFILE"))" + vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" '$PSVersionTable.OS' 2>/dev/null || echo "ssh: not reachable" + else + echo "stopped" + fi +} + +case "${1:-}" in +create) shift; cmd_create "$@" ;; +start) cmd_start ;; +stop) cmd_stop ;; +status) cmd_status ;; +ssh) shift; vm_ssh "$WINDOWS_SSH_PORT" "$WINDOWS_USER" "$@" ;; +*) sed -n '2,10p' "$0"; exit 2 ;; +esac diff --git a/tools/vmtest/windows/vmtest-setup.ps1 b/tools/vmtest/windows/vmtest-setup.ps1 new file mode 100644 index 000000000..3d1020c95 --- /dev/null +++ b/tools/vmtest/windows/vmtest-setup.ps1 @@ -0,0 +1,53 @@ +# Runs once at the first logon of the Windows test VM (see autounattend.xml). +# Sets up the OpenSSH server with the suite's public key, so that the host +# can copy and run tests. Progress is logged to C:\vmtest-setup.log. +param([Parameter(Mandatory = $true)][string]$ConfigDrive) + +$ErrorActionPreference = 'Stop' +Start-Transcript -Path 'C:\vmtest-setup-transcript.log' -Append | Out-Null + +# Keep the VM awake. +powercfg /change standby-timeout-ac 0 +powercfg /change monitor-timeout-ac 0 +powercfg /hibernate off + +# Install the OpenSSH server. It is a feature on demand and is fetched from +# Windows Update, which may not be reachable right after setup. +for ($i = 1; $i -le 30; $i++) { + try { + $cap = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' | Select-Object -First 1 + if ($cap.State -ne 'Installed') { + Add-WindowsCapability -Online -Name $cap.Name | Out-Null + } + break + } catch { + Write-Output "OpenSSH install attempt $i failed: $_" + Start-Sleep -Seconds 30 + } +} + +Set-Service -Name sshd -StartupType Automatic +Start-Service sshd + +# Use PowerShell as the SSH shell. +New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell ` + -Value 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -PropertyType String -Force | Out-Null + +# Authorize the suite's key for the administrator account. +$keys = 'C:\ProgramData\ssh\administrators_authorized_keys' +Copy-Item (Join-Path $ConfigDrive 'vmtest_id_ed25519.pub') $keys -Force +# Use SIDs, as group names are localized (Administrators, SYSTEM). +icacls $keys /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null + +if (-not (Get-NetFirewallRule -Name 'vmtest-sshd' -ErrorAction SilentlyContinue)) { + New-NetFirewallRule -Name 'vmtest-sshd' -DisplayName 'OpenSSH (vmtest)' -Direction Inbound ` + -Protocol TCP -LocalPort 22 -Action Allow | Out-Null +} + +# Work directory for tests, excluded from Defender scans to keep runs fast. +New-Item -ItemType Directory -Force -Path 'C:\vmtest' | Out-Null +Add-MpPreference -ExclusionPath 'C:\vmtest' -ErrorAction SilentlyContinue + +Restart-Service sshd +Set-Content -Path 'C:\vmtest-ready.txt' -Value (Get-Date -Format o) +Write-Output 'vmtest setup done' diff --git a/windows_core_dll/windows_core_dll.vcxproj b/windows_core_dll/windows_core_dll.vcxproj index cf6d65f12..d29fd90ba 100644 --- a/windows_core_dll/windows_core_dll.vcxproj +++ b/windows_core_dll/windows_core_dll.vcxproj @@ -113,6 +113,8 @@ <ConformanceMode>true</ConformanceMode> <PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile> + <!-- Link the C runtime statically: a clean Windows has no VCRUNTIME140.dll. --> + <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Windows</SubSystem> @@ -130,6 +132,8 @@ <ConformanceMode>true</ConformanceMode> <PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile> + <!-- Link the C runtime statically: a clean Windows has no VCRUNTIME140.dll. --> + <RuntimeLibrary>MultiThreaded</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Windows</SubSystem>