mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 11:16:52 +01:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
983784bc41 | ||
|
|
30e2735af3 | ||
|
|
bce0b4249e |
No files matched your search
@@ -1,2 +0,0 @@
|
|||||||
# Goldens are compared byte for byte, so they must come out of git the way they went in.
|
|
||||||
*.golden -text
|
|
||||||
@@ -43,15 +43,8 @@ runs:
|
|||||||
with:
|
with:
|
||||||
role-to-assume: ${{ inputs.role }}
|
role-to-assume: ${{ inputs.role }}
|
||||||
aws-region: ${{ inputs.region }}
|
aws-region: ${{ inputs.region }}
|
||||||
# An STS secret key with special characters does not survive the
|
# Default is 12 retries to ride out IAM trust-policy propagation; once
|
||||||
# pwsh -> make -> MSYS sh -> aws.exe chain, and SigV4 then signs with a
|
# the role is stable we want a real misconfiguration to fail fast.
|
||||||
# key that no longer matches, so the first S3 upload fails with
|
|
||||||
# SignatureDoesNotMatch. Retries the assume until it comes back clean.
|
|
||||||
# Same fix as DefinedNet/dnclient#867.
|
|
||||||
special-characters-workaround: true
|
|
||||||
# Overridden by the workaround above and kept for whenever that goes:
|
|
||||||
# the default 12 rides out IAM trust-policy propagation, and once the
|
|
||||||
# role is stable a real misconfiguration should fail fast.
|
|
||||||
retry-max-attempts: 5
|
retry-max-attempts: 5
|
||||||
|
|
||||||
- name: Sign .exe files
|
- name: Sign .exe files
|
||||||
|
|||||||
@@ -1,142 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# Backport a merged PR to a release branch.
|
|
||||||
#
|
|
||||||
# Cherry-picks the merge commit of a merged PR onto release-1.11 and opens a
|
|
||||||
# backport PR, mirroring the shape of #1842.
|
|
||||||
#
|
|
||||||
# Usage: ./backport.sh <pr-number> [target-version] [--continue]
|
|
||||||
# pr-number The merged PR to backport
|
|
||||||
# target-version Release version to target (default: 1.11)
|
|
||||||
# --continue Resume after resolving cherry-pick conflicts: assumes the
|
|
||||||
# fixes are staged, runs `git cherry-pick --continue`, and
|
|
||||||
# proceeds to push and open the backport PR.
|
|
||||||
#
|
|
||||||
# Requires: gh (authenticated), git, jq.
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
PR_NUMBER=${1:?usage: backport.sh <pr-number> [target-version] [--continue]}
|
|
||||||
shift
|
|
||||||
CONTINUE=0
|
|
||||||
TARGET_VERSION=""
|
|
||||||
for arg in "$@"; do
|
|
||||||
case "$arg" in
|
|
||||||
--continue) CONTINUE=1 ;;
|
|
||||||
*) TARGET_VERSION=$arg ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
for cmd in gh git jq; do
|
|
||||||
command -v "$cmd" >/dev/null || { echo "error: $cmd is required" >&2; exit 1; }
|
|
||||||
done
|
|
||||||
|
|
||||||
# Pull the source PR's metadata. Refuse to backport a PR that never merged.
|
|
||||||
pr_json=$(gh pr view "$PR_NUMBER" --json title,body,mergedAt,mergeCommit,milestone)
|
|
||||||
PR_TITLE=$(jq -r '.title' <<<"$pr_json")
|
|
||||||
PR_BODY=$(jq -r '.body' <<<"$pr_json")
|
|
||||||
MERGE_SHA=$(jq -r '.mergeCommit.oid // empty' <<<"$pr_json")
|
|
||||||
PR_MILESTONE=$(jq -r '.milestone.title // empty' <<<"$pr_json")
|
|
||||||
|
|
||||||
if [ "$(jq -r '.mergedAt // empty' <<<"$pr_json")" = "" ] || [ -z "$MERGE_SHA" ]; then
|
|
||||||
echo "error: PR #${PR_NUMBER} is not merged (no merge commit to cherry-pick)" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Default the target to one minor below the PR's milestone: a PR landing in
|
|
||||||
# v1.12.0 backports to release-1.11. An explicit target-version arg overrides.
|
|
||||||
if [ -z "$TARGET_VERSION" ]; then
|
|
||||||
if [[ $PR_MILESTONE =~ ^v?([0-9]+)\.([0-9]+) ]]; then
|
|
||||||
TARGET_VERSION="${BASH_REMATCH[1]}.$(( BASH_REMATCH[2] - 1 ))"
|
|
||||||
else
|
|
||||||
echo "error: PR #${PR_NUMBER} has no v<major>.<minor>.* milestone to infer the target from." >&2
|
|
||||||
echo "Pass the target version explicitly, e.g. $0 ${PR_NUMBER} 1.11" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
TARGET_BRANCH="release-${TARGET_VERSION}"
|
|
||||||
|
|
||||||
# Slug from the PR title: lower-case, non-alphanumerics to dashes, trimmed.
|
|
||||||
slug=$(printf '%s' "$PR_TITLE" \
|
|
||||||
| tr '[:upper:]' '[:lower:]' \
|
|
||||||
| sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//' \
|
|
||||||
| cut -c1-50 \
|
|
||||||
| sed -E 's/-+$//')
|
|
||||||
BRANCH="backport-${TARGET_VERSION//./-}-${slug}"
|
|
||||||
|
|
||||||
if [ "$CONTINUE" -eq 1 ]; then
|
|
||||||
# Resuming: the branch already exists and a cherry-pick is mid-conflict.
|
|
||||||
current=$(git rev-parse --abbrev-ref HEAD)
|
|
||||||
if [ "$current" != "$BRANCH" ]; then
|
|
||||||
echo "error: --continue expects to be on ${BRANCH}, but HEAD is ${current}" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Resuming backport of #${PR_NUMBER} on ${BRANCH}"
|
|
||||||
# Conflicts assumed resolved and staged; core.editor=true keeps the commit message.
|
|
||||||
git -c core.editor=true cherry-pick --continue
|
|
||||||
else
|
|
||||||
# A fresh run switches branches and cherry-picks, so tracked changes must be
|
|
||||||
# clean. Untracked files are fine, and --continue is exempt (its resolved
|
|
||||||
# conflicts are meant to be staged).
|
|
||||||
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
|
||||||
echo "error: working tree has uncommitted changes to tracked files; commit or stash them first." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Backporting #${PR_NUMBER} (${MERGE_SHA}) onto ${TARGET_BRANCH} as ${BRANCH}"
|
|
||||||
|
|
||||||
git fetch origin
|
|
||||||
git checkout -b "$BRANCH" "origin/${TARGET_BRANCH}"
|
|
||||||
|
|
||||||
# -m 1 handles a real merge commit; plain cherry-pick handles a squash merge.
|
|
||||||
if ! { git cherry-pick -x -m 1 "$MERGE_SHA" 2>/dev/null || git cherry-pick -x "$MERGE_SHA"; }; then
|
|
||||||
echo "error: ${MERGE_SHA} did not cherry-pick cleanly onto ${TARGET_BRANCH}." >&2
|
|
||||||
echo "Resolve the conflicts, 'git add' them, then re-run:" >&2
|
|
||||||
echo " $0 ${PR_NUMBER} ${TARGET_VERSION} --continue" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
title="backport v${TARGET_VERSION}: ${PR_TITLE}"
|
|
||||||
body=$(printf 'Backport from #%s to release v%s\n\n---\n\n%s' \
|
|
||||||
"$PR_NUMBER" "$TARGET_VERSION" "$PR_BODY")
|
|
||||||
|
|
||||||
# Highest open milestone matching v<version>.* (e.g. v1.11.1), if any.
|
|
||||||
MILESTONE=$(gh api "repos/{owner}/{repo}/milestones?state=open" \
|
|
||||||
--jq ".[].title | select(startswith(\"v${TARGET_VERSION}.\"))" \
|
|
||||||
| sort -V | tail -n1)
|
|
||||||
milestone_args=()
|
|
||||||
if [ -n "$MILESTONE" ]; then
|
|
||||||
milestone_args=(--milestone "$MILESTONE")
|
|
||||||
else
|
|
||||||
echo "warning: no open milestone matching v${TARGET_VERSION}.* found; PR will have no milestone" >&2
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "About to run:"
|
|
||||||
printf ' git push -u --force-with-lease origin %q\n' "$BRANCH"
|
|
||||||
printf ' gh pr create --base %q --head %q --title %q --body %q' \
|
|
||||||
"$TARGET_BRANCH" "$BRANCH" "$title" "$body"
|
|
||||||
[ -n "$MILESTONE" ] && printf ' --milestone %q' "$MILESTONE"
|
|
||||||
printf '\n'
|
|
||||||
echo
|
|
||||||
read -r -p "Open this pull request? [y/N] " reply
|
|
||||||
case "$reply" in
|
|
||||||
[yY] | [yY][eE][sS]) ;;
|
|
||||||
*) echo "Aborted. The cherry-pick is on local branch ${BRANCH}; push it manually if desired."; exit 0 ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
git push -u --force-with-lease origin "$BRANCH"
|
|
||||||
|
|
||||||
gh pr create \
|
|
||||||
--base "$TARGET_BRANCH" \
|
|
||||||
--head "$BRANCH" \
|
|
||||||
--title "$title" \
|
|
||||||
--body "$body" \
|
|
||||||
${milestone_args[@]+"${milestone_args[@]}"}
|
|
||||||
|
|
||||||
# The backport now exists, so drop the label that flagged this PR for one.
|
|
||||||
gh pr edit "$PR_NUMBER" --remove-label needs-backport
|
|
||||||
|
|
||||||
# Switch back to the original branch we were on before doing the backport
|
|
||||||
git checkout -
|
|
||||||
@@ -14,7 +14,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
@@ -40,7 +40,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
@@ -73,81 +73,27 @@ jobs:
|
|||||||
build-darwin:
|
build-darwin:
|
||||||
name: Build Universal Darwin
|
name: Build Universal Darwin
|
||||||
env:
|
env:
|
||||||
HAS_SIGNING_CREDS: ${{ secrets.APPLE_SIGNING_ROLE_ARN != '' }}
|
HAS_SIGNING_CREDS: ${{ secrets.AC_USERNAME != '' }}
|
||||||
runs-on: macos-latest
|
runs-on: macos-latest
|
||||||
permissions:
|
|
||||||
id-token: write
|
|
||||||
contents: read
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
# GitHub holds ARNs, not credentials, and ARNs outlive a rotation
|
|
||||||
- name: Configure AWS credentials
|
|
||||||
if: env.HAS_SIGNING_CREDS == 'true'
|
|
||||||
uses: aws-actions/configure-aws-credentials@v6
|
|
||||||
with:
|
|
||||||
role-to-assume: ${{ secrets.APPLE_SIGNING_ROLE_ARN }}
|
|
||||||
aws-region: us-east-2
|
|
||||||
|
|
||||||
# parse-json-secrets unpacks into SIGNING_* and ASC_*, masked on the way in
|
|
||||||
- name: Fetch signing credentials
|
|
||||||
if: env.HAS_SIGNING_CREDS == 'true'
|
|
||||||
uses: aws-actions/aws-secretsmanager-get-secrets@v3
|
|
||||||
with:
|
|
||||||
parse-json-secrets: true
|
|
||||||
secret-ids: |
|
|
||||||
SIGNING,${{ secrets.APPLE_SIGNING_DEVELOPER_ID_ARN }}
|
|
||||||
ASC,${{ secrets.APPLE_NOTARY_KEY_ARN }}
|
|
||||||
|
|
||||||
- name: Import certificates
|
- name: Import certificates
|
||||||
if: env.HAS_SIGNING_CREDS == 'true'
|
if: env.HAS_SIGNING_CREDS == 'true'
|
||||||
uses: Apple-Actions/import-codesign-certs@v7
|
uses: Apple-Actions/import-codesign-certs@v7
|
||||||
with:
|
with:
|
||||||
p12-file-base64: ${{ env.SIGNING_P12_BASE64 }}
|
p12-file-base64: ${{ secrets.APPLE_DEVELOPER_CERTIFICATE_P12_BASE64 }}
|
||||||
p12-password: ${{ env.SIGNING_PASSWORD }}
|
p12-password: ${{ secrets.APPLE_DEVELOPER_CERTIFICATE_PASSWORD }}
|
||||||
|
|
||||||
# The action imports but does not check the chain validates, which is how a p12
|
|
||||||
# missing its intermediate reaches a failing codesign
|
|
||||||
- name: Check the identity is usable
|
|
||||||
if: env.HAS_SIGNING_CREDS == 'true'
|
|
||||||
run: |
|
|
||||||
: "${SIGNING_IDENTITY_SHA1:?empty, so the secret has no identity_sha1}"
|
|
||||||
identities=$(security find-identity -v -p codesigning signing_temp.keychain)
|
|
||||||
case "$identities" in
|
|
||||||
*"$SIGNING_IDENTITY_SHA1"*) ;;
|
|
||||||
*) printf '%s\n' "$identities" >&2; exit 1 ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
# notarytool wants the key as a file
|
|
||||||
- name: Write the App Store Connect key
|
|
||||||
if: env.HAS_SIGNING_CREDS == 'true'
|
|
||||||
run: |
|
|
||||||
mkdir -p ~/private_keys
|
|
||||||
chmod 700 ~/private_keys
|
|
||||||
key_path="$HOME/private_keys/AuthKey_${ASC_KEY_ID}.p8"
|
|
||||||
(umask 077; printf '%s\n' "$ASC_PRIVATE_KEY" > "$key_path")
|
|
||||||
echo "ASC_P8=$key_path" >> "$GITHUB_ENV"
|
|
||||||
|
|
||||||
- name: Drop the credentials from the environment
|
|
||||||
if: env.HAS_SIGNING_CREDS == 'true'
|
|
||||||
run: |
|
|
||||||
# The action's own inventory, so a new field in a secret is covered
|
|
||||||
python3 -c '
|
|
||||||
import json, os
|
|
||||||
raw = os.environ.get("SECRETS_LIST_CLEAN_UP")
|
|
||||||
if raw is None and os.environ.get("SIGNING_P12_BASE64"):
|
|
||||||
raise SystemExit("SECRETS_LIST_CLEAN_UP is gone, fetched secrets are not being scrubbed")
|
|
||||||
keep = {"SIGNING_IDENTITY_SHA1", "ASC_KEY_ID", "ASC_ISSUER_ID"}
|
|
||||||
names = [n for n in json.loads(raw or "[]") if n not in keep]
|
|
||||||
print("\n".join(f"{n}=" for n in dict.fromkeys(names)))
|
|
||||||
' >> "$GITHUB_ENV"
|
|
||||||
|
|
||||||
- name: Build, sign, and notarize
|
- name: Build, sign, and notarize
|
||||||
|
env:
|
||||||
|
AC_USERNAME: ${{ secrets.AC_USERNAME }}
|
||||||
|
AC_PASSWORD: ${{ secrets.AC_PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
rm -rf release
|
rm -rf release
|
||||||
mkdir release
|
mkdir release
|
||||||
@@ -156,34 +102,17 @@ jobs:
|
|||||||
lipo -create -output ./release/nebula ./build/darwin-amd64/nebula ./build/darwin-arm64/nebula
|
lipo -create -output ./release/nebula ./build/darwin-amd64/nebula ./build/darwin-arm64/nebula
|
||||||
lipo -create -output ./release/nebula-cert ./build/darwin-amd64/nebula-cert ./build/darwin-arm64/nebula-cert
|
lipo -create -output ./release/nebula-cert ./build/darwin-amd64/nebula-cert ./build/darwin-arm64/nebula-cert
|
||||||
|
|
||||||
# Unset in a fork, which has no credentials to sign with
|
if [ -n "$AC_USERNAME" ]; then
|
||||||
if [ -n "$SIGNING_IDENTITY_SHA1" ]; then
|
codesign -s "10BC1FDDEB6CE753550156C0669109FAC49E4D1E" -f -v --timestamp --options=runtime -i "net.defined.nebula" ./release/nebula
|
||||||
codesign -s "$SIGNING_IDENTITY_SHA1" -f -v --timestamp --options=runtime -i "net.defined.nebula" ./release/nebula
|
codesign -s "10BC1FDDEB6CE753550156C0669109FAC49E4D1E" -f -v --timestamp --options=runtime -i "net.defined.nebula-cert" ./release/nebula-cert
|
||||||
codesign -s "$SIGNING_IDENTITY_SHA1" -f -v --timestamp --options=runtime -i "net.defined.nebula-cert" ./release/nebula-cert
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
zip -j release/nebula-darwin.zip release/nebula-cert release/nebula
|
zip -j release/nebula-darwin.zip release/nebula-cert release/nebula
|
||||||
|
|
||||||
if [ -n "$ASC_P8" ]; then
|
if [ -n "$AC_USERNAME" ]; then
|
||||||
xcrun notarytool submit ./release/nebula-darwin.zip --key "$ASC_P8" --key-id "$ASC_KEY_ID" --issuer "$ASC_ISSUER_ID" --wait
|
xcrun notarytool submit ./release/nebula-darwin.zip --team-id "576H3XS7FP" --apple-id "$AC_USERNAME" --password "$AC_PASSWORD" --wait
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Drop the signing key
|
|
||||||
if: always() && env.HAS_SIGNING_CREDS == 'true'
|
|
||||||
run: |
|
|
||||||
# Locked, not deleted: import-codesign-certs deletes it in its own post
|
|
||||||
# step and fails the job if it is already gone. Locked is unusable.
|
|
||||||
security lock-keychain signing_temp.keychain || true
|
|
||||||
rm -f "$ASC_P8"
|
|
||||||
# Nothing later in this job needs AWS
|
|
||||||
python3 -c '
|
|
||||||
import json, os
|
|
||||||
names = json.loads(os.environ.get("SECRETS_LIST_CLEAN_UP") or "[]")
|
|
||||||
names += ["ASC_P8", "SIGNING_IDENTITY_SHA1", "ASC_KEY_ID", "ASC_ISSUER_ID",
|
|
||||||
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"]
|
|
||||||
print("\n".join(f"{n}=" for n in dict.fromkeys(names)))
|
|
||||||
' >> "$GITHUB_ENV"
|
|
||||||
|
|
||||||
- name: Upload artifacts
|
- name: Upload artifacts
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: add hashicorp source
|
- name: add hashicorp source
|
||||||
@@ -66,7 +66,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: add hashicorp source
|
- name: add hashicorp source
|
||||||
@@ -92,13 +92,13 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
# WSL2 + Ubuntu so the smoke can run a real linux peer with its own
|
# WSL2 + Ubuntu so the smoke can run a real linux peer with its own
|
||||||
# netns. iputils-ping is needed for the in-WSL ping check. WSL1 has no
|
# netns. iputils-ping is needed for the in-WSL ping check. WSL1 has no
|
||||||
# real kernel and would lack /dev/net/tun, so we have to force WSL2.
|
# real kernel and would lack /dev/net/tun, so we have to force WSL2.
|
||||||
- uses: Vampire/setup-wsl@v7
|
- uses: Vampire/setup-wsl@v3
|
||||||
with:
|
with:
|
||||||
distribution: Ubuntu-24.04
|
distribution: Ubuntu-24.04
|
||||||
additional-packages: iputils-ping iproute2
|
additional-packages: iputils-ping iproute2
|
||||||
|
|||||||
+32
-33
@@ -22,43 +22,42 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Smoke Docker
|
|
||||||
run: make smoke-docker
|
|
||||||
|
|
||||||
- name: Smoke Docker IPv6 overlay
|
|
||||||
run: make smoke-docker-ipv6
|
|
||||||
|
|
||||||
- name: Smoke Relay Docker
|
|
||||||
run: make smoke-relay-docker
|
|
||||||
|
|
||||||
- name: Smoke Docker boringcrypto
|
|
||||||
run: make boringcrypto smoke-docker
|
|
||||||
|
|
||||||
- name: Smoke Docker fips140
|
|
||||||
run: make fips140-all GOALS=smoke-docker
|
|
||||||
|
|
||||||
timeout-minutes: 10
|
|
||||||
|
|
||||||
smoke-self:
|
|
||||||
name: Run self traffic smoke test on macOS
|
|
||||||
runs-on: macos-latest
|
|
||||||
steps:
|
|
||||||
|
|
||||||
- uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- uses: actions/setup-go@v7
|
|
||||||
with:
|
|
||||||
go-version: '1.27'
|
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: build
|
- name: build
|
||||||
run: make bin
|
run: make bin-docker CGO_ENABLED=1 BUILD_ARGS=-race
|
||||||
|
|
||||||
- name: run smoke-self
|
- name: setup docker image
|
||||||
working-directory: ./.github/workflows/smoke
|
working-directory: ./.github/workflows/smoke
|
||||||
run: ./smoke-self.sh
|
run: ./build.sh
|
||||||
|
|
||||||
|
- name: run smoke
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: ./smoke.sh
|
||||||
|
|
||||||
|
- name: setup docker image ipv6
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: SMOKE_OVERLAY_IPV6=1 ./build.sh
|
||||||
|
|
||||||
|
- name: run smoke ipv6
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: SMOKE_OVERLAY_IPV6=1 ./smoke.sh
|
||||||
|
|
||||||
|
- name: setup relay docker image
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: ./build-relay.sh
|
||||||
|
|
||||||
|
- name: run smoke relay
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: ./smoke-relay.sh
|
||||||
|
|
||||||
|
- name: setup docker image for P256
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: NAME="smoke-p256" CURVE=P256 ./build.sh
|
||||||
|
|
||||||
|
- name: run smoke-p256
|
||||||
|
working-directory: ./.github/workflows/smoke
|
||||||
|
run: NAME="smoke-p256" ./smoke.sh
|
||||||
|
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# A host must be able to reach its own overlay address. Where the kernel sends
|
|
||||||
# that traffic through the tun rather than over loopback, nebula sees it and
|
|
||||||
# hands it straight back (immediatelyForwardToSelf), and whether the kernel
|
|
||||||
# accepts what comes back is only answerable against a real kernel. Runs one
|
|
||||||
# nebula on this machine as root and aims every probe at its own address.
|
|
||||||
|
|
||||||
set -e -x
|
|
||||||
|
|
||||||
set -o pipefail
|
|
||||||
|
|
||||||
V4=192.0.2.1
|
|
||||||
V6=2001:db8::1
|
|
||||||
|
|
||||||
case "$(uname -s)" in
|
|
||||||
Darwin) TUN_DEV=utun ;;
|
|
||||||
*) TUN_DEV=tun0 ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
ROOT="$(cd ../../.. && pwd)"
|
|
||||||
|
|
||||||
rm -rf build/self
|
|
||||||
mkdir -p build/self
|
|
||||||
cd build/self
|
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
echo
|
|
||||||
echo " *** cleanup"
|
|
||||||
echo
|
|
||||||
|
|
||||||
set +e
|
|
||||||
if [ -n "$NEBULA_PID" ]
|
|
||||||
then
|
|
||||||
sudo kill "$NEBULA_PID"
|
|
||||||
fi
|
|
||||||
{ kill $(jobs -p); wait; } 2>/dev/null
|
|
||||||
sed 's/^/ [self] /' nebula.log
|
|
||||||
}
|
|
||||||
|
|
||||||
trap cleanup EXIT
|
|
||||||
|
|
||||||
# perl is on every platform this runs on; timeout(1) is not.
|
|
||||||
alarm() {
|
|
||||||
perl -e 'alarm shift; exec @ARGV' "$@"
|
|
||||||
}
|
|
||||||
|
|
||||||
RESULTS=""
|
|
||||||
FAILED=""
|
|
||||||
probe() {
|
|
||||||
local name="$1"
|
|
||||||
shift
|
|
||||||
if "$@"
|
|
||||||
then
|
|
||||||
RESULTS="$RESULTS $name=ok"
|
|
||||||
else
|
|
||||||
RESULTS="$RESULTS $name=FAIL"
|
|
||||||
FAILED="$FAILED $name"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# Send one datagram, then wait for the listener to have written it out.
|
|
||||||
udp_probe() {
|
|
||||||
echo self | alarm 5 nc -u -w1 "$1" 3000 || true
|
|
||||||
set +x
|
|
||||||
for _ in $(seq 1 20)
|
|
||||||
do
|
|
||||||
if grep -q self "$2"
|
|
||||||
then
|
|
||||||
set -x
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
sleep 0.25
|
|
||||||
done
|
|
||||||
set -x
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
"$ROOT/nebula-cert" ca -name "Smoke Test"
|
|
||||||
"$ROOT/nebula-cert" sign -name self -networks "$V4/24,$V6/64"
|
|
||||||
|
|
||||||
HOST=self AM_LIGHTHOUSE=true TUN_DEV="$TUN_DEV" ../../genconfig.sh >self.yml
|
|
||||||
|
|
||||||
"$ROOT/nebula" -config self.yml -test
|
|
||||||
|
|
||||||
sudo -v
|
|
||||||
sudo "$ROOT/nebula" -config self.yml >nebula.log 2>&1 &
|
|
||||||
NEBULA_PID=$!
|
|
||||||
|
|
||||||
for _ in $(seq 1 40)
|
|
||||||
do
|
|
||||||
ifconfig | grep "inet6 $V6 " >/dev/null && break
|
|
||||||
sleep 0.25
|
|
||||||
done
|
|
||||||
ifconfig | grep "inet $V4 "
|
|
||||||
ifconfig | grep "inet6 $V6 "
|
|
||||||
|
|
||||||
nc -l "$V4" 2000 >/dev/null &
|
|
||||||
nc -l "$V6" 2000 >/dev/null &
|
|
||||||
nc -u -l "$V4" 3000 >udp4.txt &
|
|
||||||
nc -u -l "$V6" 3000 >udp6.txt &
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
set +x
|
|
||||||
echo
|
|
||||||
echo " *** Testing self traffic from $V4"
|
|
||||||
echo
|
|
||||||
set -x
|
|
||||||
probe icmp4 alarm 5 ping -c1 "$V4"
|
|
||||||
probe tcp4 alarm 5 nc -z "$V4" 2000
|
|
||||||
probe udp4 udp_probe "$V4" udp4.txt
|
|
||||||
|
|
||||||
set +x
|
|
||||||
echo
|
|
||||||
echo " *** Testing self traffic from $V6"
|
|
||||||
echo
|
|
||||||
set -x
|
|
||||||
probe icmp6 alarm 5 ping6 -c1 "$V6"
|
|
||||||
probe tcp6 alarm 5 nc -z "$V6" 2000
|
|
||||||
probe udp6 udp_probe "$V6" udp6.txt
|
|
||||||
|
|
||||||
set +x
|
|
||||||
echo
|
|
||||||
echo " *** self traffic:$RESULTS"
|
|
||||||
echo
|
|
||||||
if [ -n "$FAILED" ]
|
|
||||||
then
|
|
||||||
echo "self traffic failed:$FAILED" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
@@ -51,19 +51,15 @@ wsl -d $Distro -- bash -c "rm -rf $WslDir && mkdir -p $WslDir" | Out-Null
|
|||||||
$DevName = 'nebula-smoke'
|
$DevName = 'nebula-smoke'
|
||||||
$Ip1 = '192.168.241.1'
|
$Ip1 = '192.168.241.1'
|
||||||
$Ip2 = '192.168.241.2'
|
$Ip2 = '192.168.241.2'
|
||||||
# Dual stack on purpose: a v4-only overlay never exercises the v6 side of tun.mtu.
|
|
||||||
$Ip6_1 = 'fd42:4242:241::1'
|
|
||||||
$Ip6_2 = 'fd42:4242:241::2'
|
|
||||||
$Mtu = 1300
|
|
||||||
$Port = 4242
|
$Port = 4242
|
||||||
|
|
||||||
& $NebulaCert ca -name 'smoke-ca' -out-crt "$WorkDir\ca.crt" -out-key "$WorkDir\ca.key"
|
& $NebulaCert ca -name 'smoke-ca' -out-crt "$WorkDir\ca.crt" -out-key "$WorkDir\ca.key"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "nebula-cert ca failed (exit $LASTEXITCODE)" }
|
if ($LASTEXITCODE -ne 0) { throw "nebula-cert ca failed (exit $LASTEXITCODE)" }
|
||||||
|
|
||||||
& $NebulaCert sign -name 'lighthouse' -networks "$Ip1/24,$Ip6_1/64" -ca-crt "$WorkDir\ca.crt" -ca-key "$WorkDir\ca.key" -out-crt "$WorkDir\lighthouse.crt" -out-key "$WorkDir\lighthouse.key"
|
& $NebulaCert sign -name 'lighthouse' -networks "$Ip1/24" -ca-crt "$WorkDir\ca.crt" -ca-key "$WorkDir\ca.key" -out-crt "$WorkDir\lighthouse.crt" -out-key "$WorkDir\lighthouse.key"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "nebula-cert sign lighthouse failed (exit $LASTEXITCODE)" }
|
if ($LASTEXITCODE -ne 0) { throw "nebula-cert sign lighthouse failed (exit $LASTEXITCODE)" }
|
||||||
|
|
||||||
& $NebulaCert sign -name 'peer' -networks "$Ip2/24,$Ip6_2/64" -ca-crt "$WorkDir\ca.crt" -ca-key "$WorkDir\ca.key" -out-crt "$WorkDir\peer.crt" -out-key "$WorkDir\peer.key"
|
& $NebulaCert sign -name 'peer' -networks "$Ip2/24" -ca-crt "$WorkDir\ca.crt" -ca-key "$WorkDir\ca.key" -out-crt "$WorkDir\peer.crt" -out-key "$WorkDir\peer.key"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "nebula-cert sign peer failed (exit $LASTEXITCODE)" }
|
if ($LASTEXITCODE -ne 0) { throw "nebula-cert sign peer failed (exit $LASTEXITCODE)" }
|
||||||
|
|
||||||
# Windows lighthouse config.
|
# Windows lighthouse config.
|
||||||
@@ -86,7 +82,7 @@ tun:
|
|||||||
drop_local_broadcast: false
|
drop_local_broadcast: false
|
||||||
drop_multicast: false
|
drop_multicast: false
|
||||||
tx_queue: 500
|
tx_queue: 500
|
||||||
mtu: $Mtu
|
mtu: 1300
|
||||||
network_category: private
|
network_category: private
|
||||||
logging:
|
logging:
|
||||||
level: info
|
level: info
|
||||||
@@ -130,7 +126,7 @@ tun:
|
|||||||
drop_local_broadcast: false
|
drop_local_broadcast: false
|
||||||
drop_multicast: false
|
drop_multicast: false
|
||||||
tx_queue: 500
|
tx_queue: 500
|
||||||
mtu: $Mtu
|
mtu: 1300
|
||||||
logging:
|
logging:
|
||||||
level: info
|
level: info
|
||||||
format: text
|
format: text
|
||||||
@@ -173,7 +169,7 @@ Write-Host '=== WSL diagnostic ==='
|
|||||||
wsl --version 2>&1 | Out-Host
|
wsl --version 2>&1 | Out-Host
|
||||||
wsl --list --verbose 2>&1 | Out-Host
|
wsl --list --verbose 2>&1 | Out-Host
|
||||||
wsl -d $Distro -u root -- uname -a | Out-Host
|
wsl -d $Distro -u root -- uname -a | Out-Host
|
||||||
wsl -d $Distro -u root -- bash -c "modprobe tun 2>&1 || true; mkdir -p /dev/net; [ -c /dev/net/tun ] || mknod /dev/net/tun c 10 200; chmod 600 /dev/net/tun; { echo 0 > /proc/sys/net/ipv6/conf/all/disable_ipv6; echo 0 > /proc/sys/net/ipv6/conf/default/disable_ipv6; } 2>/dev/null || true; ls -l /dev/net/tun"
|
wsl -d $Distro -u root -- bash -c "modprobe tun 2>&1 || true; mkdir -p /dev/net; [ -c /dev/net/tun ] || mknod /dev/net/tun c 10 200; chmod 600 /dev/net/tun; ls -l /dev/net/tun"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "failed to prepare /dev/net/tun in WSL (TUN support missing?)" }
|
if ($LASTEXITCODE -ne 0) { throw "failed to prepare /dev/net/tun in WSL (TUN support missing?)" }
|
||||||
|
|
||||||
# Deliberately no New-NetFirewallRule calls here -- nebula's windows_bypass_wdf
|
# Deliberately no New-NetFirewallRule calls here -- nebula's windows_bypass_wdf
|
||||||
@@ -218,16 +214,6 @@ try {
|
|||||||
}
|
}
|
||||||
Write-Host "OK: $DevName NetworkCategory=Private"
|
Write-Host "OK: $DevName NetworkCategory=Private"
|
||||||
|
|
||||||
# v6 silently kept the adapter default of 65535 while v4 was correct.
|
|
||||||
foreach ($family in @('IPv4', 'IPv6')) {
|
|
||||||
Wait-Until -TimeoutSec 30 -What "$DevName $family NlMtu=$Mtu" -Predicate {
|
|
||||||
if ($lhProc.HasExited) { throw "lighthouse exited (code $($lhProc.ExitCode)) before $family mtu was set" }
|
|
||||||
$rows = @(Get-NetIPInterface -InterfaceAlias $DevName -AddressFamily $family -ErrorAction SilentlyContinue)
|
|
||||||
$rows.Count -gt 0 -and -not ($rows | Where-Object { $_.NlMtu -ne $Mtu })
|
|
||||||
}
|
|
||||||
Write-Host "OK: $DevName $family NlMtu=$Mtu"
|
|
||||||
}
|
|
||||||
|
|
||||||
Wait-Until -TimeoutSec 30 -What "WSL nebula1 with $Ip2" -Predicate {
|
Wait-Until -TimeoutSec 30 -What "WSL nebula1 with $Ip2" -Predicate {
|
||||||
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before tun was ready" }
|
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before tun was ready" }
|
||||||
$r = wsl -d $Distro -u root -- bash -c "ip -o addr show nebula1 2>/dev/null | grep -q 'inet $Ip2' && echo yes"
|
$r = wsl -d $Distro -u root -- bash -c "ip -o addr show nebula1 2>/dev/null | grep -q 'inet $Ip2' && echo yes"
|
||||||
@@ -235,13 +221,6 @@ try {
|
|||||||
}
|
}
|
||||||
Write-Host "OK: WSL nebula1 has $Ip2"
|
Write-Host "OK: WSL nebula1 has $Ip2"
|
||||||
|
|
||||||
Wait-Until -TimeoutSec 30 -What "WSL nebula1 with $Ip6_2" -Predicate {
|
|
||||||
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before the v6 address was up" }
|
|
||||||
$r = wsl -d $Distro -u root -- bash -c "ip -o addr show nebula1 2>/dev/null | grep -q 'inet6 $Ip6_2' && echo yes"
|
|
||||||
("$r").Trim() -eq 'yes'
|
|
||||||
}
|
|
||||||
Write-Host "OK: WSL nebula1 has $Ip6_2"
|
|
||||||
|
|
||||||
Wait-Until -TimeoutSec 30 -What "ping from WSL peer to windows lighthouse ($Ip1)" -Predicate {
|
Wait-Until -TimeoutSec 30 -What "ping from WSL peer to windows lighthouse ($Ip1)" -Predicate {
|
||||||
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before ping succeeded" }
|
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before ping succeeded" }
|
||||||
$r = wsl -d $Distro -u root -- bash -c "ping -c1 -W1 $Ip1 >/dev/null 2>&1 && echo OK"
|
$r = wsl -d $Distro -u root -- bash -c "ping -c1 -W1 $Ip1 >/dev/null 2>&1 && echo OK"
|
||||||
@@ -255,28 +234,6 @@ try {
|
|||||||
}
|
}
|
||||||
Write-Host "OK: windows lighthouse -> WSL peer"
|
Write-Host "OK: windows lighthouse -> WSL peer"
|
||||||
|
|
||||||
# Otherwise the v6 networks only prove the interface exists, not that it forwards.
|
|
||||||
Wait-Until -TimeoutSec 30 -What "v6 ping from WSL peer to windows lighthouse ($Ip6_1)" -Predicate {
|
|
||||||
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before the v6 ping succeeded" }
|
|
||||||
$r = wsl -d $Distro -u root -- bash -c "ping -6 -c1 -W1 $Ip6_1 >/dev/null 2>&1 && echo OK"
|
|
||||||
("$r").Trim() -eq 'OK'
|
|
||||||
}
|
|
||||||
Write-Host "OK: WSL peer -> windows lighthouse over v6"
|
|
||||||
|
|
||||||
# The NlMtu check above proves the value was written, not that windows honors it. A payload this size only
|
|
||||||
# crosses the tunnel as fragments cut at NlMtu on the way out of the adapter. Left at the adapter default it
|
|
||||||
# reaches nebula whole, overflows the udp.MTU (9001) write buffer and is dropped, so the ping never answers.
|
|
||||||
# Anything smaller would ride out as one oversized datagram and survive on IP fragmentation of the underlay.
|
|
||||||
$BigPayload = 9000
|
|
||||||
foreach ($target in @(@{ Family = 'v4'; Ip = $Ip2 }, @{ Family = 'v6'; Ip = $Ip6_2 })) {
|
|
||||||
Wait-Until -TimeoutSec 30 -What "$($target.Family) ping with a $BigPayload byte payload from windows lighthouse to WSL peer ($($target.Ip))" -Predicate {
|
|
||||||
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before the large $($target.Family) ping succeeded" }
|
|
||||||
$null = & ping.exe -n 1 -w 1000 -l $BigPayload $target.Ip
|
|
||||||
$LASTEXITCODE -eq 0
|
|
||||||
}
|
|
||||||
Write-Host "OK: windows lighthouse -> WSL peer, $BigPayload byte $($target.Family) payload"
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host ''
|
Write-Host ''
|
||||||
Write-Host 'All smoke checks passed.'
|
Write-Host 'All smoke checks passed.'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Install goimports
|
- name: Install goimports
|
||||||
@@ -42,7 +42,7 @@ jobs:
|
|||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v9
|
uses: golangci/golangci-lint-action@v9
|
||||||
with:
|
with:
|
||||||
version: v2.14
|
version: v2.12
|
||||||
|
|
||||||
test:
|
test:
|
||||||
name: Test ${{ matrix.name }}
|
name: Test ${{ matrix.name }}
|
||||||
@@ -58,14 +58,9 @@ jobs:
|
|||||||
e2e-cmd: make e2evv
|
e2e-cmd: make e2evv
|
||||||
- name: linux-boringcrypto
|
- name: linux-boringcrypto
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
build-cmd: make boringcrypto
|
build-cmd: make bin-boringcrypto
|
||||||
test-cmd: make boringcrypto test
|
test-cmd: make test-boringcrypto
|
||||||
e2e-cmd: make boringcrypto e2evv
|
e2e-cmd: make e2e GOEXPERIMENT=boringcrypto CGO_ENABLED=1 TEST_ENV="TEST_LOGS=1" TEST_FLAGS="-v -ldflags -checklinkname=0"
|
||||||
- name: linux-fips140
|
|
||||||
os: ubuntu-latest
|
|
||||||
build-cmd: make fips140-all
|
|
||||||
test-cmd: make fips140-all GOALS=test
|
|
||||||
e2e-cmd: make fips140-all GOALS=e2evv
|
|
||||||
- name: linux-pkcs11
|
- name: linux-pkcs11
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
build-cmd: make bin-pkcs11
|
build-cmd: make bin-pkcs11
|
||||||
@@ -87,7 +82,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
@@ -132,7 +127,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v7
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.27'
|
go-version: '1.26'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build ${{ matrix.name }}
|
- name: Build ${{ matrix.name }}
|
||||||
|
|||||||
+1
-53
@@ -7,56 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Added
|
|
||||||
|
|
||||||
- A control socket that provides access to all of the ssh debug server's commands along with support
|
|
||||||
for running `nebula ctl <command>` as a client from the CLI.
|
|
||||||
- An info socket that provides access to information related to identity: identity, whoami, and print-cert.
|
|
||||||
|
|
||||||
### Removed
|
|
||||||
|
|
||||||
- The SSH debug server's `start-cpu-profile`, `stop-cpu-profile`, `save-heap-profile`, `save-mutex-profile`, and
|
|
||||||
`mutex-profile-fraction` commands, and `sshd.sandbox_dir`, which is now ignored if set.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- A peer whose certificate carries an unsafe network overlapping the overlay could send packets as any node in
|
|
||||||
it: the firewall accepted any source inside the unsafe network. A source address inside this node's own
|
|
||||||
networks must now be the sending peer's own; through an unsafe network it is dropped, counted as a dropped
|
|
||||||
remote address.
|
|
||||||
|
|
||||||
- Signing a v2 certificate with an empty name, a name longer than 253 bytes, or an empty group now fails.
|
|
||||||
These certificates were signed successfully but could not be loaded.
|
|
||||||
- `create-tunnel -address <ip:port>` panicked on a nil RemoteList and, over the ssh debug server, took nebula
|
|
||||||
down with it. A hostinfo returned by StartHandshake had no RemoteList until the handshake loop's first
|
|
||||||
pass attached one, and `create-tunnel -address` set the remote before that. The list is now attached when
|
|
||||||
the handshake starts, so a pending hostinfo never exists without one.
|
|
||||||
|
|
||||||
## [1.11.1] - 2026-08-21
|
|
||||||
|
|
||||||
See the [v1.11.1](https://github.com/slackhq/nebula/milestone/30?closed=1) milestone for a complete list of changes.
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
|
|
||||||
- IPv6 packets whose next header is a protocol Nebula does not parse (SCTP, GRE, IP-in-IP, etc.) are now
|
|
||||||
classified as that protocol with no ports, closing a firewall bypass where a crafted payload could steer
|
|
||||||
the classifier into reading one as TCP/UDP and matching a TCP/UDP rule. These packets are now matched as
|
|
||||||
their true protocol, so only a `proto: any` rule allows them. If you carry one of these protocols over the
|
|
||||||
overlay, confirm a `proto: any` rule covers it before upgrading, it may have been passing only through this
|
|
||||||
bypass. (#1840)
|
|
||||||
- Drop the dependency on `github.com/cyberdelia/go-metrics-graphite`, which has been unmaintained for over ten
|
|
||||||
years, by inlining the small amount of code Nebula used. (#1832)
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- The ICMPv6 type was read from the wrong byte when classifying IPv6 packets, so the echo identifier used
|
|
||||||
for conntrack was never picked up. (#1840)
|
|
||||||
- Enforce outbound message counter limits so a tunnel is rehandshaked before the counter can wrap, preventing
|
|
||||||
nonce reuse. This is unreachable in practice, but is enforced as a defense-in-depth measure. (#1841)
|
|
||||||
- Prevent `nebula-cert ca` from running out of memory on 32bit systems when generating encrypted private keys. (#1834)
|
|
||||||
- Tolerate `ErrDumpInterrupted` when listing tun addresses on Linux, so a transient interrupted netlink dump
|
|
||||||
no longer aborts startup. (#1835)
|
|
||||||
|
|
||||||
## [1.11.0] - 2026-07-23
|
## [1.11.0] - 2026-07-23
|
||||||
|
|
||||||
See the [v1.11.0](https://github.com/slackhq/nebula/milestone/25?closed=1) milestone for a complete list of changes.
|
See the [v1.11.0](https://github.com/slackhq/nebula/milestone/25?closed=1) milestone for a complete list of changes.
|
||||||
@@ -920,9 +870,7 @@ created.)
|
|||||||
|
|
||||||
- Initial public release.
|
- Initial public release.
|
||||||
|
|
||||||
[Unreleased]: https://github.com/slackhq/nebula/compare/v1.11.1...HEAD
|
[Unreleased]: https://github.com/slackhq/nebula/compare/v1.10.3...HEAD
|
||||||
[1.11.1]: https://github.com/slackhq/nebula/releases/tag/v1.11.1
|
|
||||||
[1.11.0]: https://github.com/slackhq/nebula/releases/tag/v1.11.0
|
|
||||||
[1.10.3]: https://github.com/slackhq/nebula/releases/tag/v1.10.3
|
[1.10.3]: https://github.com/slackhq/nebula/releases/tag/v1.10.3
|
||||||
[1.10.2]: https://github.com/slackhq/nebula/releases/tag/v1.10.2
|
[1.10.2]: https://github.com/slackhq/nebula/releases/tag/v1.10.2
|
||||||
[1.10.1]: https://github.com/slackhq/nebula/releases/tag/v1.10.1
|
[1.10.1]: https://github.com/slackhq/nebula/releases/tag/v1.10.1
|
||||||
|
|||||||
@@ -72,17 +72,6 @@ ALL_CROSS_LINUX_ARM = linux-arm-5 linux-arm-6 linux-arm-7 linux-arm64
|
|||||||
ALL_CROSS_LINUX_MIPS = linux-mips linux-mipsle linux-mips64 linux-mips64le linux-mips-softfloat
|
ALL_CROSS_LINUX_MIPS = linux-mips linux-mipsle linux-mips64 linux-mips64le linux-mips-softfloat
|
||||||
ALL_CROSS_LINUX_OTHER = linux-386 linux-ppc64le linux-riscv64 linux-loong64
|
ALL_CROSS_LINUX_OTHER = linux-386 linux-ppc64le linux-riscv64 linux-loong64
|
||||||
|
|
||||||
# Based on section 2.2 of the Go Cryptographic Module CVMP Security Policy #5247
|
|
||||||
ALL_FIPS140 = linux-amd64-fips140 \
|
|
||||||
linux-arm64-fips140 \
|
|
||||||
windows-amd64-fips140 \
|
|
||||||
windows-arm64-fips140 \
|
|
||||||
darwin-arm64-fips140 \
|
|
||||||
freebsd-amd64-fips140 \
|
|
||||||
linux-arm-7-fips140 \
|
|
||||||
linux-mips64-fips140 \
|
|
||||||
linux-ppc64le-fips140
|
|
||||||
|
|
||||||
e2e:
|
e2e:
|
||||||
$(TEST_ENV) go test -tags=e2e_testing -count=1 $(TEST_FLAGS) ./e2e
|
$(TEST_ENV) go test -tags=e2e_testing -count=1 $(TEST_FLAGS) ./e2e
|
||||||
|
|
||||||
@@ -148,8 +137,6 @@ release-netbsd: $(ALL_NETBSD:%=build/nebula-%.tar.gz)
|
|||||||
|
|
||||||
release-boringcrypto: build/nebula-linux-$(shell go env GOARCH)-boringcrypto.tar.gz
|
release-boringcrypto: build/nebula-linux-$(shell go env GOARCH)-boringcrypto.tar.gz
|
||||||
|
|
||||||
release-fips140: $(ALL_FIPS140:%=build/nebula-%.tar.gz)
|
|
||||||
|
|
||||||
BUILD_ARGS += -trimpath
|
BUILD_ARGS += -trimpath
|
||||||
|
|
||||||
bin-windows: build/windows-amd64/nebula.exe build/windows-amd64/nebula-cert.exe
|
bin-windows: build/windows-amd64/nebula.exe build/windows-amd64/nebula-cert.exe
|
||||||
@@ -170,24 +157,17 @@ bin-freebsd-arm64: build/freebsd-arm64/nebula build/freebsd-arm64/nebula-cert
|
|||||||
bin-boringcrypto: build/linux-$(shell go env GOARCH)-boringcrypto/nebula build/linux-$(shell go env GOARCH)-boringcrypto/nebula-cert
|
bin-boringcrypto: build/linux-$(shell go env GOARCH)-boringcrypto/nebula build/linux-$(shell go env GOARCH)-boringcrypto/nebula-cert
|
||||||
mv $? .
|
mv $? .
|
||||||
|
|
||||||
bin-fips140: build/linux-$(shell go env GOARCH)-fips140/nebula build/linux-$(shell go env GOARCH)-fips140/nebula-cert
|
|
||||||
mv $? .
|
|
||||||
|
|
||||||
bin-pkcs11: BUILD_ARGS += -tags pkcs11
|
bin-pkcs11: BUILD_ARGS += -tags pkcs11
|
||||||
bin-pkcs11: CGO_ENABLED = 1
|
bin-pkcs11: CGO_ENABLED = 1
|
||||||
bin-pkcs11: bin
|
bin-pkcs11: bin
|
||||||
|
|
||||||
# Build with the pprof debug server (serves on :6060). See startPprofServer.
|
|
||||||
debug: BUILD_ARGS += -tags debug
|
|
||||||
debug: bin
|
|
||||||
|
|
||||||
bin:
|
bin:
|
||||||
$(GOENV) go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula${NEBULA_CMD_SUFFIX} ${NEBULA_CMD_PATH}
|
go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula${NEBULA_CMD_SUFFIX} ${NEBULA_CMD_PATH}
|
||||||
$(GOENV) go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula-cert${NEBULA_CMD_SUFFIX} ./cmd/nebula-cert
|
go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula-cert${NEBULA_CMD_SUFFIX} ./cmd/nebula-cert
|
||||||
|
|
||||||
install:
|
install:
|
||||||
$(GOENV) go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ${NEBULA_CMD_PATH}
|
go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ${NEBULA_CMD_PATH}
|
||||||
$(GOENV) go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ./cmd/nebula-cert
|
go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ./cmd/nebula-cert
|
||||||
|
|
||||||
build/linux-arm-%: GOENV += GOARM=$(word 3, $(subst -, ,$*))
|
build/linux-arm-%: GOENV += GOARM=$(word 3, $(subst -, ,$*))
|
||||||
build/linux-mips-%: GOENV += GOMIPS=$(word 3, $(subst -, ,$*))
|
build/linux-mips-%: GOENV += GOMIPS=$(word 3, $(subst -, ,$*))
|
||||||
@@ -198,11 +178,8 @@ build/linux-mips-softfloat/%: LDFLAGS += -s -w
|
|||||||
# boringcrypto
|
# boringcrypto
|
||||||
build/linux-amd64-boringcrypto/%: GOENV += GOEXPERIMENT=boringcrypto CGO_ENABLED=1
|
build/linux-amd64-boringcrypto/%: GOENV += GOEXPERIMENT=boringcrypto CGO_ENABLED=1
|
||||||
build/linux-arm64-boringcrypto/%: GOENV += GOEXPERIMENT=boringcrypto CGO_ENABLED=1
|
build/linux-arm64-boringcrypto/%: GOENV += GOEXPERIMENT=boringcrypto CGO_ENABLED=1
|
||||||
|
build/linux-amd64-boringcrypto/%: LDFLAGS += -checklinkname=0
|
||||||
# fips140
|
build/linux-arm64-boringcrypto/%: LDFLAGS += -checklinkname=0
|
||||||
FIPSVERSION = v1.0.0
|
|
||||||
$(foreach _rule, $(ALL_FIPS140), build/$(_rule)/%): GOENV += GOFIPS140=$(FIPSVERSION)
|
|
||||||
$(foreach _rule, $(ALL_FIPS140), build/$(_rule)/%): BUILD_ARGS += -tags fips140enforce
|
|
||||||
|
|
||||||
build/%/nebula: .FORCE
|
build/%/nebula: .FORCE
|
||||||
GOOS=$(firstword $(subst -, , $*)) \
|
GOOS=$(firstword $(subst -, , $*)) \
|
||||||
@@ -233,7 +210,10 @@ vet:
|
|||||||
go vet $(VET_FLAGS) -v ./...
|
go vet $(VET_FLAGS) -v ./...
|
||||||
|
|
||||||
test:
|
test:
|
||||||
$(TEST_ENV) go test $(TEST_FLAGS) -v ./...
|
go test -v ./...
|
||||||
|
|
||||||
|
test-boringcrypto:
|
||||||
|
GOEXPERIMENT=boringcrypto CGO_ENABLED=1 go test -ldflags "-checklinkname=0" -v ./...
|
||||||
|
|
||||||
test-pkcs11:
|
test-pkcs11:
|
||||||
CGO_ENABLED=1 go test -v -tags pkcs11 ./...
|
CGO_ENABLED=1 go test -v -tags pkcs11 ./...
|
||||||
@@ -242,14 +222,11 @@ test-cov-html:
|
|||||||
go test -coverprofile=coverage.out
|
go test -coverprofile=coverage.out
|
||||||
go tool cover -html=coverage.out
|
go tool cover -html=coverage.out
|
||||||
|
|
||||||
# The package builds only compile. The final line links an android binary so a linker-only failure
|
|
||||||
# cannot pass CI.
|
|
||||||
build-test-mobile:
|
build-test-mobile:
|
||||||
GOARCH=amd64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
GOARCH=amd64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
||||||
GOARCH=arm64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
GOARCH=arm64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
||||||
GOARCH=amd64 GOOS=android go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
GOARCH=amd64 GOOS=android go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
||||||
GOARCH=arm64 GOOS=android go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
GOARCH=arm64 GOOS=android go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
||||||
GOARCH=arm64 GOOS=android go build -o /dev/null ${NEBULA_CMD_PATH}
|
|
||||||
|
|
||||||
bench:
|
bench:
|
||||||
go test -bench=.
|
go test -bench=.
|
||||||
@@ -279,75 +256,29 @@ ifeq ($(words $(MAKECMDGOALS)),1)
|
|||||||
@$(MAKE) service ${.DEFAULT_GOAL} --no-print-directory
|
@$(MAKE) service ${.DEFAULT_GOAL} --no-print-directory
|
||||||
endif
|
endif
|
||||||
|
|
||||||
# Useful to chain together, like:
|
|
||||||
# - make fips140 e2evv
|
|
||||||
# - make fips140 smoke-docker
|
|
||||||
# Use `release-fips140` to build release binaries
|
|
||||||
fips140:
|
|
||||||
@echo > $(NULL_FILE)
|
|
||||||
ifeq ($(strip $(GOFIPS140)),)
|
|
||||||
$(eval GOFIPS140 = $(FIPSVERSION))
|
|
||||||
endif
|
|
||||||
$(eval GOENV += GOFIPS140=$(GOFIPS140))
|
|
||||||
$(eval BUILD_ARGS += -tags fips140enforce)
|
|
||||||
$(eval TEST_ENV += $(GOENV))
|
|
||||||
$(eval CURVE = P256)
|
|
||||||
ifeq ($(words $(MAKECMDGOALS)),1)
|
|
||||||
@$(MAKE) fips140 GOFIPS140=$(GOFIPS140) ${.DEFAULT_GOAL} --no-print-directory
|
|
||||||
endif
|
|
||||||
|
|
||||||
# To test the future pending module, use like `make fips140-latest test`
|
|
||||||
ALL_GOFIPS140 = v1.0.0 v1.26.0 latest
|
|
||||||
define FIPS140_rule
|
|
||||||
fips140-$(1): GOFIPS140 = $(1)
|
|
||||||
fips140-$(1): fips140
|
|
||||||
endef
|
|
||||||
$(foreach _rule, $(ALL_GOFIPS140), $(eval $(call FIPS140_rule,$(_rule))))
|
|
||||||
|
|
||||||
# Iterate and run the goals for all fips versions, like `make fips140-all GOALS=test`
|
|
||||||
fips140-all:
|
|
||||||
@$(foreach _v,$(ALL_GOFIPS140),$(MAKE) fips140-$(_v) $(GOALS) &&) true
|
|
||||||
|
|
||||||
# Useful to chain together, like:
|
|
||||||
# - make boringcrypto e2evv
|
|
||||||
# - make boringcrypto smoke-docker
|
|
||||||
# Use `release-boringcrypto` or `bin-boringcrypto` to build release binaries
|
|
||||||
boringcrypto:
|
|
||||||
@echo > $(NULL_FILE)
|
|
||||||
$(eval GOENV += GOEXPERIMENT=boringcrypto CGO_ENABLED=1)
|
|
||||||
$(eval TEST_ENV += $(GOENV))
|
|
||||||
$(eval CURVE = P256)
|
|
||||||
ifeq ($(words $(MAKECMDGOALS)),1)
|
|
||||||
@$(MAKE) boringcrypto ${.DEFAULT_GOAL} --no-print-directory
|
|
||||||
endif
|
|
||||||
|
|
||||||
bin-docker: bin build/linux-amd64/nebula build/linux-amd64/nebula-cert
|
bin-docker: bin build/linux-amd64/nebula build/linux-amd64/nebula-cert
|
||||||
|
|
||||||
smoke-docker: BUILD_ARGS += -race
|
|
||||||
smoke-docker: GOENV += CGO_ENABLED=1
|
|
||||||
smoke-docker: bin-docker
|
smoke-docker: bin-docker
|
||||||
# This is so we can limit `fips140` smoke test to just P256 curve.
|
cd .github/workflows/smoke/ && ./build.sh
|
||||||
if [ "$(CURVE)" != "P256" ]; then cd .github/workflows/smoke/ && $(GOENV) ./build.sh; fi
|
cd .github/workflows/smoke/ && ./smoke.sh
|
||||||
if [ "$(CURVE)" != "P256" ]; then cd .github/workflows/smoke/ && $(GOENV) ./smoke.sh; fi
|
cd .github/workflows/smoke/ && NAME="smoke-p256" CURVE="P256" ./build.sh
|
||||||
cd .github/workflows/smoke/ && $(GOENV) NAME="smoke-p256" CURVE="P256" ./build.sh
|
cd .github/workflows/smoke/ && NAME="smoke-p256" ./smoke.sh
|
||||||
cd .github/workflows/smoke/ && $(GOENV) NAME="smoke-p256" ./smoke.sh
|
|
||||||
|
|
||||||
smoke-relay-docker: BUILD_ARGS += -race
|
|
||||||
smoke-relay-docker: GOENV += CGO_ENABLED=1
|
|
||||||
smoke-relay-docker: bin-docker
|
smoke-relay-docker: bin-docker
|
||||||
cd .github/workflows/smoke/ && $(GOENV) ./build-relay.sh
|
cd .github/workflows/smoke/ && ./build-relay.sh
|
||||||
cd .github/workflows/smoke/ && $(GOENV) ./smoke-relay.sh
|
cd .github/workflows/smoke/ && ./smoke-relay.sh
|
||||||
|
|
||||||
smoke-docker-ipv6: export SMOKE_OVERLAY_IPV6 = 1
|
smoke-docker-ipv6: export SMOKE_OVERLAY_IPV6 = 1
|
||||||
smoke-docker-ipv6: smoke-docker
|
smoke-docker-ipv6: smoke-docker
|
||||||
|
|
||||||
smoke-self: bin
|
smoke-docker-race: BUILD_ARGS = -race
|
||||||
cd .github/workflows/smoke/ && ./smoke-self.sh
|
smoke-docker-race: CGO_ENABLED = 1
|
||||||
|
smoke-docker-race: smoke-docker
|
||||||
|
|
||||||
smoke-vagrant/%: bin-docker build/%/nebula
|
smoke-vagrant/%: bin-docker build/%/nebula
|
||||||
cd .github/workflows/smoke/ && ./build.sh $*
|
cd .github/workflows/smoke/ && ./build.sh $*
|
||||||
cd .github/workflows/smoke/ && ./smoke-vagrant.sh $*
|
cd .github/workflows/smoke/ && ./smoke-vagrant.sh $*
|
||||||
|
|
||||||
.FORCE:
|
.FORCE:
|
||||||
.PHONY: all all-linux all-freebsd all-openbsd all-netbsd all-darwin all-windows all-cross-linux all-cross-linux-arm all-cross-linux-mips all-cross-linux-other all-cross-darwin all-cross-windows bench bench-cpu bench-cpu-long bin bin-windows bin-windows-arm64 bin-darwin bin-freebsd bin-freebsd-arm64 bin-boringcrypto bin-fips140 bin-pkcs11 bin-docker boringcrypto build-test-mobile debug docker e2e e2ev e2evv e2evvv e2evvvv e2e-bench fips140 fips140-all $(ALL_GOFIPS140:%=fips140-%) install proto release release-linux release-freebsd release-openbsd release-netbsd release-boringcrypto release-fips140 service smoke-docker smoke-relay-docker smoke-docker-ipv6 smoke-self test test-pkcs11 test-cov-html vet smoke-vagrant/%
|
.PHONY: all all-linux all-freebsd all-openbsd all-netbsd all-darwin all-windows all-cross-linux all-cross-linux-arm all-cross-linux-mips all-cross-linux-other all-cross-darwin all-cross-windows bench bench-cpu bench-cpu-long bin build-test-mobile e2e e2ev e2evv e2evvv e2evvvv proto release service smoke-docker smoke-docker-race test test-cov-html smoke-vagrant/%
|
||||||
.DEFAULT_GOAL := bin
|
.DEFAULT_GOAL := bin
|
||||||
@@ -145,27 +145,17 @@ To build nebula for a specific platform (ex, Windows):
|
|||||||
|
|
||||||
See the [Makefile](Makefile) for more details on build targets
|
See the [Makefile](Makefile) for more details on build targets
|
||||||
|
|
||||||
## Curve P256 and FIPS 140-3 mode
|
## Curve P256 and BoringCrypto
|
||||||
|
|
||||||
The default curve used for cryptographic handshakes and signatures is Curve25519. This is the recommended setting for most users. If your deployment has certain compliance requirements, you have the option of creating your CA using `nebula-cert ca -curve P256` to use NIST Curve P256. The CA will then sign certificates using ECDSA P256, and any hosts using these certificates will use P256 for ECDH handshakes.
|
The default curve used for cryptographic handshakes and signatures is Curve25519. This is the recommended setting for most users. If your deployment has certain compliance requirements, you have the option of creating your CA using `nebula-cert ca -curve P256` to use NIST Curve P256. The CA will then sign certificates using ECDSA P256, and any hosts using these certificates will use P256 for ECDH handshakes.
|
||||||
|
|
||||||
Nebula can be built to support the [FIPS 140-3](https://go.dev/doc/security/fips140) mode of Go by running either of the following make targets. (This sets GOFIPS140=v1.0.0, which must be done at compile time so that the correct AES-GCM can be used for FIPS 140-3 enforcement mode).
|
In addition, Nebula can be built using the [BoringCrypto GOEXPERIMENT](https://github.com/golang/go/blob/go1.20/src/crypto/internal/boring/README.md) by running either of the following make targets:
|
||||||
|
|
||||||
```sh
|
|
||||||
make fips140
|
|
||||||
make fips140 test
|
|
||||||
make release-fips140
|
|
||||||
```
|
|
||||||
|
|
||||||
Nebula can also be built using the [BoringCrypto GOEXPERIMENT](https://github.com/golang/go/blob/go1.20/src/crypto/internal/boring/README.md) by running either of the following make targets.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make bin-boringcrypto
|
make bin-boringcrypto
|
||||||
make release-boringcrypto
|
make release-boringcrypto
|
||||||
```
|
```
|
||||||
|
|
||||||
NOTE: boringcrypto support is deprecated and will be removed in the next release. Users should migrate to the native FIPS 140-3 mode described above.
|
|
||||||
|
|
||||||
This is not the recommended default deployment, but may be useful based on your compliance requirements.
|
This is not the recommended default deployment, but may be useful based on your compliance requirements.
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|||||||
@@ -79,7 +79,13 @@ func (b *Bits) clearRange(startPos, count uint64) uint64 {
|
|||||||
// handle the potential partial word before pos becomes u64 aligned
|
// handle the potential partial word before pos becomes u64 aligned
|
||||||
word := pos >> 6
|
word := pos >> 6
|
||||||
bit := pos & 63
|
bit := pos & 63
|
||||||
take := min(min(uint64(64)-bit, remaining), b.length-pos)
|
take := uint64(64) - bit
|
||||||
|
if take > remaining {
|
||||||
|
take = remaining
|
||||||
|
}
|
||||||
|
if take > b.length-pos {
|
||||||
|
take = b.length - pos
|
||||||
|
}
|
||||||
var mask uint64
|
var mask uint64
|
||||||
if take == 64 {
|
if take == 64 {
|
||||||
mask = math.MaxUint64
|
mask = math.MaxUint64
|
||||||
@@ -183,7 +189,10 @@ func (b *Bits) Update(l *slog.Logger, i uint64) bool {
|
|||||||
func (b *Bits) updateSlow(l *slog.Logger, i uint64) bool {
|
func (b *Bits) updateSlow(l *slog.Logger, i uint64) bool {
|
||||||
// If i is a jump, adjust the window, record lost, update current, and return true
|
// If i is a jump, adjust the window, record lost, update current, and return true
|
||||||
if i > b.current {
|
if i > b.current {
|
||||||
end := min(i, b.current+b.length)
|
end := i
|
||||||
|
if end > b.current+b.length {
|
||||||
|
end = b.current + b.length
|
||||||
|
}
|
||||||
count := end - b.current
|
count := end - b.current
|
||||||
startPos := (b.current + 1) & b.lengthMask
|
startPos := (b.current + 1) & b.lengthMask
|
||||||
|
|
||||||
|
|||||||
+1
-10
@@ -389,16 +389,7 @@ func (c *certificateV2) fromTBSCertificate(t *TBSCertificate) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *certificateV2) validate() error {
|
func (c *certificateV2) validate() error {
|
||||||
// Mirror the name and group rules in unmarshalDetails so signing fails instead of producing an unparseable certificate
|
// Empty names are allowed
|
||||||
if c.details.name == "" || len(c.details.name) > MaxNameLength {
|
|
||||||
return NewErrInvalidCertificateProperties("name must be between 1 and %d bytes", MaxNameLength)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, group := range c.details.groups {
|
|
||||||
if group == "" {
|
|
||||||
return NewErrInvalidCertificateProperties("groups may not be empty")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(c.publicKey) == 0 {
|
if len(c.publicKey) == 0 {
|
||||||
return ErrInvalidPublicKey
|
return ErrInvalidPublicKey
|
||||||
|
|||||||
+1
-46
@@ -6,7 +6,6 @@ import (
|
|||||||
"crypto/elliptic"
|
"crypto/elliptic"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -121,7 +120,7 @@ func TestCertificate_SignP256_AlwaysNormalized(t *testing.T) {
|
|||||||
pub := elliptic.Marshal(elliptic.P256(), priv.PublicKey.X, priv.PublicKey.Y)
|
pub := elliptic.Marshal(elliptic.P256(), priv.PublicKey.X, priv.PublicKey.Y)
|
||||||
rawPriv := priv.D.FillBytes(make([]byte, 32))
|
rawPriv := priv.D.FillBytes(make([]byte, 32))
|
||||||
|
|
||||||
for i := range 1000 {
|
for i := 0; i < 1000; i++ {
|
||||||
if i&1 == 1 {
|
if i&1 == 1 {
|
||||||
tbs.Version = Version1
|
tbs.Version = Version1
|
||||||
} else {
|
} else {
|
||||||
@@ -136,47 +135,3 @@ func TestCertificate_SignP256_AlwaysNormalized(t *testing.T) {
|
|||||||
assert.True(t, normie)
|
assert.True(t, normie)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCertificateV2_SignRejectsUnparseable(t *testing.T) {
|
|
||||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
|
||||||
require.NoError(t, err)
|
|
||||||
var invalid *ErrInvalidCertificateProperties
|
|
||||||
|
|
||||||
newTBS := func() TBSCertificate {
|
|
||||||
return TBSCertificate{
|
|
||||||
Version: Version2,
|
|
||||||
Name: "testing",
|
|
||||||
Networks: []netip.Prefix{mustParsePrefixUnmapped("10.1.1.1/24")},
|
|
||||||
Groups: []string{"test-group1"},
|
|
||||||
NotBefore: time.Now().Add(-time.Minute),
|
|
||||||
NotAfter: time.Now().Add(time.Minute),
|
|
||||||
PublicKey: []byte("1234567890abcedfghij1234567890ab"),
|
|
||||||
Curve: Curve_CURVE25519,
|
|
||||||
IsCA: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tbs := newTBS()
|
|
||||||
tbs.Name = strings.Repeat("a", MaxNameLength)
|
|
||||||
c, err := tbs.Sign(nil, Curve_CURVE25519, priv)
|
|
||||||
require.NoError(t, err)
|
|
||||||
b, err := c.Marshal()
|
|
||||||
require.NoError(t, err)
|
|
||||||
_, err = unmarshalCertificateV2(b, nil, Curve_CURVE25519)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
tbs = newTBS()
|
|
||||||
tbs.Name = strings.Repeat("a", MaxNameLength+1)
|
|
||||||
_, err = tbs.Sign(nil, Curve_CURVE25519, priv)
|
|
||||||
require.ErrorAs(t, err, &invalid)
|
|
||||||
|
|
||||||
tbs = newTBS()
|
|
||||||
tbs.Name = ""
|
|
||||||
_, err = tbs.Sign(nil, Curve_CURVE25519, priv)
|
|
||||||
require.ErrorAs(t, err, &invalid)
|
|
||||||
|
|
||||||
tbs = newTBS()
|
|
||||||
tbs.Groups = []string{"test-group1", ""}
|
|
||||||
_, err = tbs.Sign(nil, Curve_CURVE25519, priv)
|
|
||||||
require.ErrorAs(t, err, &invalid)
|
|
||||||
}
|
|
||||||
@@ -1,420 +0,0 @@
|
|||||||
package ctl
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/config"
|
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Word is the argument that selects the control client instead of the daemon.
|
|
||||||
const Word = "ctl"
|
|
||||||
|
|
||||||
// Subcommand handles the one bare word a daemon binary accepts before its flags. `nebula
|
|
||||||
// ctl <command>` runs the client. Any other first argument that is not a flag is a
|
|
||||||
// mistyped subcommand, reported with a usage line: the daemon's flag parser would ignore
|
|
||||||
// the stray word and start nebula, so `nebula clt` would bring up a second daemon
|
|
||||||
// instead of reporting a typo. It returns the exit code and true when the process is
|
|
||||||
// done, and false when argv is the daemon's to parse. Both daemon binaries, cmd/nebula
|
|
||||||
// and cmd/nebula-service, call it before anything else, so each has a nebula ctl and
|
|
||||||
// neither has the hazard. A word that follows the daemon's flags instead is Trailing's.
|
|
||||||
func Subcommand(argv []string) (code int, done bool) {
|
|
||||||
if len(argv) < 2 || strings.HasPrefix(argv[1], "-") {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
|
|
||||||
if argv[1] == Word {
|
|
||||||
return Run(argv[2:]), true
|
|
||||||
}
|
|
||||||
|
|
||||||
return unknownCommand(argv[1]), true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Trailing handles the words the daemon's flag parser leaves unparsed: flag.Parse stops
|
|
||||||
// at the first argument that is not a flag and hands the rest back. rest is flag.Args()
|
|
||||||
// after the daemon has parsed, and configPath is the config the daemon's -config named,
|
|
||||||
// "" when it did not. Both daemon binaries call it right after flag.Parse, so that
|
|
||||||
// `nebula -config x ctl identity` runs the client and `nebula -config x clt` reports a
|
|
||||||
// typo, as Subcommand does for a word at the front of the line; a daemon that ignored
|
|
||||||
// the words would start in their place.
|
|
||||||
//
|
|
||||||
// A leading ctl word runs the client on what follows, with the daemon's -config carried
|
|
||||||
// over: an operator who typed it meant the daemon running on that config, and the client
|
|
||||||
// derives the same socket from it. Any other word is a mistake, reported as Subcommand
|
|
||||||
// reports one.
|
|
||||||
func Trailing(rest []string, configPath string) (code int, done bool) {
|
|
||||||
if len(rest) == 0 {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
|
|
||||||
if rest[0] != Word {
|
|
||||||
return unknownCommand(rest[0]), true
|
|
||||||
}
|
|
||||||
|
|
||||||
args := rest[1:]
|
|
||||||
if configPath != "" {
|
|
||||||
// First, so a -config on the ctl side of the line still wins: Parse applies
|
|
||||||
// flags in order and the last value set is the one read.
|
|
||||||
args = append([]string{"-" + commands.FlagConfig, configPath}, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
return Run(args), true
|
|
||||||
}
|
|
||||||
|
|
||||||
// unknownCommand reports a bare word that is neither a flag nor ctl, with the one usage
|
|
||||||
// line that says what the two forms of the command line are.
|
|
||||||
func unknownCommand(word string) int {
|
|
||||||
fmt.Fprintf(os.Stderr, "nebula: unknown command %q\n\n", word)
|
|
||||||
fmt.Fprintf(os.Stderr, "Run nebula with flags to start it, or `nebula %s <command>` to control one that is already running.\n", Word)
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run implements `nebula ctl <command> [args]`
|
|
||||||
//
|
|
||||||
// args is everything after the `ctl` word.
|
|
||||||
func Run(args []string) int {
|
|
||||||
fs := flag.NewFlagSet("nebula ctl", flag.ContinueOnError)
|
|
||||||
fs.SetOutput(os.Stderr)
|
|
||||||
|
|
||||||
configPath := fs.String(commands.FlagConfig, "", "Path to the config of the running nebula, used to locate its control socket")
|
|
||||||
socketPath := fs.String(commands.FlagSocket, "", "Path to the control socket, instead of the one the config implies")
|
|
||||||
fs.Usage = func() {
|
|
||||||
fmt.Fprintf(os.Stderr, "Usage: nebula ctl [flags] <command> [command flags]\n\n")
|
|
||||||
fmt.Fprintf(os.Stderr, "Inspects and controls a nebula already running on this machine.\n")
|
|
||||||
fmt.Fprintf(os.Stderr, "Run it as the user who ran nebula, or as a member of the group %s names.\n\n", localapi.CtlGroupKey)
|
|
||||||
fmt.Fprintf(os.Stderr, "Flags, which may come before or after the command:\n")
|
|
||||||
fs.PrintDefaults()
|
|
||||||
fmt.Fprintf(os.Stderr, "\nRun `nebula ctl help` for the available commands.\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
own, cmdArgs := splitLine(fs, args)
|
|
||||||
if err := fs.Parse(own); err != nil {
|
|
||||||
// fs has already printed the usage, or the problem. Asking for help is not a
|
|
||||||
// failure, and a script that chains on `nebula ctl -h` should not see one.
|
|
||||||
if errors.Is(err, flag.ErrHelp) {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(cmdArgs) == 0 {
|
|
||||||
cmdArgs = []string{"help"}
|
|
||||||
}
|
|
||||||
|
|
||||||
path, err := resolveSocket(*socketPath, *configPath)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
client := &localapi.Client{Path: path}
|
|
||||||
|
|
||||||
// Ask the daemon what it serves before parsing anything. The flags belong to the
|
|
||||||
// command, which lives over there, so this is what lets the CLI keep its usual shape
|
|
||||||
// while the wire protocol stays a named-parameter API rather than a shipped argv.
|
|
||||||
schema, err := client.Describe()
|
|
||||||
if err != nil {
|
|
||||||
// A daemon that answered was reached, and what it said, or that it could not be
|
|
||||||
// read, is the whole message.
|
|
||||||
var refused *localapi.DaemonError
|
|
||||||
var unread *localapi.ReplyError
|
|
||||||
if errors.As(err, &refused) || errors.As(err, &unread) {
|
|
||||||
fmt.Fprintf(os.Stderr, "nebula: %s\n", err)
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
// Otherwise the operating system said why, and it is passed on as it came: a
|
|
||||||
// permission denied or a missing socket says more about what to do than a
|
|
||||||
// guess at the operator's setup would.
|
|
||||||
fmt.Fprintf(os.Stderr, "nebula: could not reach the control socket at %s: %s\n", path, err)
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
req, printedHelp, err := parseCommand(schema, cmdArgs)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if printedHelp {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := client.Invoke(string(req.name), req.Params, req.Args, wireFormat(req.Format))
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "nebula: %s\n", err)
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
out := output(res, req.Format)
|
|
||||||
if out != "" {
|
|
||||||
fmt.Fprint(os.Stdout, out)
|
|
||||||
if !strings.HasSuffix(out, "\n") {
|
|
||||||
fmt.Fprintln(os.Stdout)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Error set is the one failure signal, whether the request never ran or the command
|
|
||||||
// ran and refused. A refusal asked for in JSON has already gone to stdout as the
|
|
||||||
// {ok, reason} object, and is not said again on stderr; the exit status carries it.
|
|
||||||
if res.Error == "" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(res.Result) == 0 && len(res.Text) == 0 {
|
|
||||||
msg := res.Error
|
|
||||||
if !strings.HasSuffix(msg, "\n") {
|
|
||||||
msg += "\n"
|
|
||||||
}
|
|
||||||
fmt.Fprint(os.Stderr, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
// output renders what the daemon answered for the format the line asked for. A text
|
|
||||||
// request is answered in Text with the bytes the command wrote, printed as they are; a
|
|
||||||
// JSON request is answered in Result with the value itself, printed as it came, since a
|
|
||||||
// value that happens to be a string is still JSON to the script reading it. Indentation
|
|
||||||
// is the client's business: whitespace does not survive a JSON envelope, and the daemon
|
|
||||||
// has no reason to care how its answer is laid out. The bytes are re-indented rather
|
|
||||||
// than decoded and encoded again, which would sort the keys and round the numbers.
|
|
||||||
func output(res *localapi.Response, format commands.Format) string {
|
|
||||||
switch format {
|
|
||||||
case commands.FormatJSON:
|
|
||||||
return string(res.Result)
|
|
||||||
case commands.FormatPrettyJSON:
|
|
||||||
var buf bytes.Buffer
|
|
||||||
if err := json.Indent(&buf, res.Result, "", " "); err != nil {
|
|
||||||
return string(res.Result)
|
|
||||||
}
|
|
||||||
return buf.String()
|
|
||||||
default:
|
|
||||||
return string(res.Text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ctlRequest is one parsed nebula ctl command line: the command's name, which only the
|
|
||||||
// daemon can resolve, and the line as every surface parses it. The Request's Command is
|
|
||||||
// nil here, since the CLI holds a schema rather than the command, and its Format is
|
|
||||||
// FormatUnset when the line named none, which to nebula ctl means text: its default
|
|
||||||
// differs from the API's.
|
|
||||||
type ctlRequest struct {
|
|
||||||
name commands.Name
|
|
||||||
commands.Request
|
|
||||||
}
|
|
||||||
|
|
||||||
// wireFormat is what a request asks the daemon for. Pretty is the client's business,
|
|
||||||
// since whitespace does not survive a JSON envelope, so it travels as json. No
|
|
||||||
// preference is text, nebula ctl's default: a person gets the human rendering wherever
|
|
||||||
// one exists.
|
|
||||||
func wireFormat(f commands.Format) string {
|
|
||||||
switch f {
|
|
||||||
case commands.FormatJSON, commands.FormatPrettyJSON:
|
|
||||||
return "json"
|
|
||||||
default:
|
|
||||||
return "text"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseCommand turns the user's command line into a ctlRequest, using the schema the
|
|
||||||
// daemon supplied. The line is parsed with the same rules the daemon applies to an ssh
|
|
||||||
// line, through ParseArgs, and ParseLine reads what was set into the Request to send, so
|
|
||||||
// a line means the same on both.
|
|
||||||
//
|
|
||||||
// printedHelp reports that help was written for the command instead, and there is
|
|
||||||
// nothing to send.
|
|
||||||
func parseCommand(schema []commands.CommandSchema, argv []string) (req ctlRequest, printedHelp bool, err error) {
|
|
||||||
name := commands.Name(argv[0])
|
|
||||||
|
|
||||||
var found *commands.CommandSchema
|
|
||||||
for i := range schema {
|
|
||||||
if schema[i].Name == name {
|
|
||||||
found = &schema[i]
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if found == nil {
|
|
||||||
// Let the daemon answer. It knows whether this is a typo or a command it holds
|
|
||||||
// back, and its message for the second case is better than anything guessable
|
|
||||||
// from the schema alone.
|
|
||||||
return ctlRequest{name: name, Request: commands.Request{Args: argv[1:]}}, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// The flag package's own report is a bare message followed by a usage dump in a layout
|
|
||||||
// that does not match WriteCommandHelp, so it is silenced and the error is reported
|
|
||||||
// once, below, with a pointer at the help this command actually prints.
|
|
||||||
fs := flag.NewFlagSet(string(name), flag.ContinueOnError)
|
|
||||||
fs.SetOutput(io.Discard)
|
|
||||||
|
|
||||||
for _, f := range found.Flags {
|
|
||||||
if f.Bool {
|
|
||||||
fs.Bool(f.Name, f.Default == "true", f.Usage)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
fs.String(f.Name, f.Default, f.Usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
operands, err := commands.ParseArgs(fs, argv[1:])
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, flag.ErrHelp) {
|
|
||||||
// The same rendering the daemon uses for `help <command>`, so -h and help agree.
|
|
||||||
_ = commands.WriteCommandHelp(*found, os.Stdout)
|
|
||||||
return ctlRequest{}, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Say what flag did: an unknown flag, a missing value and a malformed value are
|
|
||||||
// different mistakes, and "does not take" would be wrong for two of them.
|
|
||||||
return ctlRequest{}, false, fmt.Errorf("nebula: %s: %s (see 'nebula ctl %s -h')", name, err, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only what the user actually set travels. A parameter left alone is the daemon's
|
|
||||||
// default to apply, not the client's to assert, and the presentation flags are the
|
|
||||||
// client's to interpret, never sent.
|
|
||||||
//
|
|
||||||
// Where the command has no human form the daemon says so, and only once the command
|
|
||||||
// has run: a refusal ("No vpn address was provided") always has a human form, so
|
|
||||||
// telling the user to pass -json before finding out whether the command would even
|
|
||||||
// accept the line sends them to fix the wrong thing. That is why the schema does not
|
|
||||||
// say which commands have a human form: nothing should decide on it before running.
|
|
||||||
return ctlRequest{name: name, Request: commands.ParseLine(fs, operands)}, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// splitLine divides a nebula ctl line into the client's own flags, for fs to parse, and
|
|
||||||
// the command line to send, which begins with the command word. The client's flags may
|
|
||||||
// come before the command or after it: `nebula ctl -config x identity` and
|
|
||||||
// `nebula ctl identity -config x` mean the same, so an operator who has typed a command
|
|
||||||
// and then remembers which daemon they meant does not have to retype the line.
|
|
||||||
//
|
|
||||||
// Before the command word every flag is the client's, whatever it is, so an unknown one
|
|
||||||
// is reported by fs, and -h is the client's usage. After it only the
|
|
||||||
// flags fs defines are lifted out, and only those: the command's own flags are unknown
|
|
||||||
// here, since they come from the daemon the line has yet to name, and -h after the
|
|
||||||
// command asks for that command's help. Which command flags take a value is unknown too,
|
|
||||||
// so the client's names are reserved in the commands package and no command can give
|
|
||||||
// one a value that would be lifted from here. A "--" before the command is consumed, as
|
|
||||||
// fs.Parse would have; one after it belongs to the command line and ends the lifting,
|
|
||||||
// so an operand spelled like a client flag can still be passed.
|
|
||||||
func splitLine(fs *flag.FlagSet, args []string) (own, cmd []string) {
|
|
||||||
seenCommand := false
|
|
||||||
for i := 0; i < len(args); i++ {
|
|
||||||
a := args[i]
|
|
||||||
|
|
||||||
if a == "--" {
|
|
||||||
if seenCommand {
|
|
||||||
return own, append(cmd, args[i:]...)
|
|
||||||
}
|
|
||||||
seenCommand = true
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if !seenCommand {
|
|
||||||
if len(a) < 2 || a[0] != '-' {
|
|
||||||
seenCommand = true
|
|
||||||
cmd = append(cmd, a)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
own = append(own, a)
|
|
||||||
if f, hasValue := commands.LookupArg(fs, a); f != nil && !hasValue && !commands.IsBoolFlag(f) && i+1 < len(args) {
|
|
||||||
i++
|
|
||||||
own = append(own, args[i])
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(a) >= 2 && a[0] == '-' {
|
|
||||||
// The same reading of the argument ParseArgs makes, so a word this lifts as a
|
|
||||||
// client flag's value is one the daemon's parser would have read the same way.
|
|
||||||
if f, hasValue := commands.LookupArg(fs, a); f != nil {
|
|
||||||
own = append(own, a)
|
|
||||||
if !hasValue && !commands.IsBoolFlag(f) && i+1 < len(args) {
|
|
||||||
i++
|
|
||||||
own = append(own, args[i])
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd = append(cmd, a)
|
|
||||||
}
|
|
||||||
|
|
||||||
return own, cmd
|
|
||||||
}
|
|
||||||
|
|
||||||
// resolveSocket decides which socket to talk to. It never searches: the answer is the
|
|
||||||
// socket the operator named, or the one the config implies, and nothing else.
|
|
||||||
//
|
|
||||||
// An explicit flag wins. Otherwise the config is read, the one the operator named or the
|
|
||||||
// one found next to the executable, and the path is the socket that config implies: its
|
|
||||||
// local_api.control.socket if set, else the same derivation the daemon applies.
|
|
||||||
func resolveSocket(socketFlag, configFlag string) (string, error) {
|
|
||||||
if socketFlag != "" {
|
|
||||||
return socketFlag, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathFromConfig(configFlag)
|
|
||||||
}
|
|
||||||
|
|
||||||
// pathFromConfig returns the socket path the daemon would be serving: the one
|
|
||||||
// local_api.control.socket names in the config, so an operator who moved the socket does
|
|
||||||
// not have to repeat themselves on every invocation, else the default.
|
|
||||||
//
|
|
||||||
// A config the operator did not name is a guess: config.DefaultPath looks next to the
|
|
||||||
// executable, and a package that installs a default config there while systemd starts
|
|
||||||
// the daemon with another will make it the wrong guess. It is still the only answer
|
|
||||||
// that involves no searching. A guess that cannot be read is not an error, it is no
|
|
||||||
// guess: a member of the socket's group cannot read a root daemon's config, and is
|
|
||||||
// answered by the default path, where the daemon serves unless that config moved it.
|
|
||||||
// A config the operator named is theirs to make readable.
|
|
||||||
func pathFromConfig(configFlag string) (string, error) {
|
|
||||||
return socketFromConfigFile(configFlag, configFlag != "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func socketFromConfigFile(configPath string, named bool) (string, error) {
|
|
||||||
if !named {
|
|
||||||
p, err := config.DefaultPath()
|
|
||||||
if err != nil {
|
|
||||||
return localapi.DefaultSocketPath, nil
|
|
||||||
}
|
|
||||||
configPath = p
|
|
||||||
}
|
|
||||||
|
|
||||||
// The config is loaded only to find the socket path. Loading logs lines that belong
|
|
||||||
// to the daemon, not to someone running a read only command, and mixing them into
|
|
||||||
// the CLI's output would corrupt a -json result, so they are discarded.
|
|
||||||
c := config.NewC(slog.New(slog.DiscardHandler))
|
|
||||||
if err := c.Load(configPath); err != nil {
|
|
||||||
if !named {
|
|
||||||
return localapi.DefaultSocketPath, nil
|
|
||||||
}
|
|
||||||
// The operating system's error, as it came: permission denied on a root daemon's
|
|
||||||
// config says what to do.
|
|
||||||
return "", fmt.Errorf("nebula: could not read %s: %w", configPath, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A daemon running this config serves no socket; dialing the path would only say
|
|
||||||
// that nothing is there.
|
|
||||||
if !localapi.ControlEnabled(c) {
|
|
||||||
return "", fmt.Errorf("nebula: the control socket is disabled in %s by %s", configPath, localapi.CtlEnabledKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The same call the daemon makes, so the two agree on the path and on what makes a
|
|
||||||
// path unusable.
|
|
||||||
p, err := localapi.SocketPathFromConfig(c)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("nebula: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
@@ -1,294 +0,0 @@
|
|||||||
package ctl
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"flag"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestResolveSocketReportsAnUnreadableConfig: an operator who named a config must hear
|
|
||||||
// that it could not be read, rather than have the command steered anywhere else.
|
|
||||||
func TestResolveSocketReportsAnUnreadableConfig(t *testing.T) {
|
|
||||||
missing := filepath.Join(t.TempDir(), "typo.yml")
|
|
||||||
|
|
||||||
_, err := resolveSocket("", missing)
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.Contains(t, err.Error(), missing)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestResolveSocketGuessedConfigNeedNotBeReadable: a config nobody named is a guess, and
|
|
||||||
// one that cannot be read, a root daemon's config read by a member of the socket's
|
|
||||||
// group, means the default path rather than an error.
|
|
||||||
func TestResolveSocketGuessedConfigNeedNotBeReadable(t *testing.T) {
|
|
||||||
missing := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
|
|
||||||
p, err := socketFromConfigFile(missing, false)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, localapi.DefaultSocketPath, p)
|
|
||||||
|
|
||||||
_, err = socketFromConfigFile(missing, true)
|
|
||||||
require.ErrorContains(t, err, missing)
|
|
||||||
}
|
|
||||||
|
|
||||||
// nowhereSocket is a socket name nothing listens on, spelled the way the platform
|
|
||||||
// requires: a full pipe name on windows, an absolute path elsewhere.
|
|
||||||
var nowhereSocket = map[bool]string{true: `\\.\pipe\nebula-nowhere`, false: "/nowhere/ctl.sock"}[runtime.GOOS == "windows"]
|
|
||||||
|
|
||||||
// namedSocketConfig is a config that names nowhereSocket as the control socket. Single
|
|
||||||
// quotes keep a pipe name's backslashes literal in YAML.
|
|
||||||
var namedSocketConfig = "local_api:\n control:\n socket: '" + nowhereSocket + "'\n"
|
|
||||||
|
|
||||||
// TestResolveSocketTrustsANamedConfig: a config the operator named yields the socket it
|
|
||||||
// implies even when nothing is listening there, so a dial failure names that socket.
|
|
||||||
func TestResolveSocketTrustsANamedConfig(t *testing.T) {
|
|
||||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
require.NoError(t, os.WriteFile(cfg, []byte(namedSocketConfig), 0600))
|
|
||||||
|
|
||||||
p, err := resolveSocket("", cfg)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, nowhereSocket, p)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestResolveSocketSaysTheSocketIsDisabled: a config that turns the control socket off
|
|
||||||
// is answered with that, not with a dial to a path nothing serves. -socket still wins.
|
|
||||||
func TestResolveSocketSaysTheSocketIsDisabled(t *testing.T) {
|
|
||||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
require.NoError(t, os.WriteFile(cfg, []byte("local_api:\n control:\n enabled: false\n"), 0600))
|
|
||||||
|
|
||||||
_, err := resolveSocket("", cfg)
|
|
||||||
require.ErrorContains(t, err, "the control socket is disabled in "+cfg+" by local_api.control.enabled")
|
|
||||||
|
|
||||||
p, err := resolveSocket("/explicit.sock", cfg)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, "/explicit.sock", p)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestResolveSocketUsesTheDefaultWithoutAnOverride: a config that does not name the
|
|
||||||
// socket means the default path, the same one the daemon serves with that config, and
|
|
||||||
// no config at all means the default too, since that is where a daemon started without
|
|
||||||
// an override serves. Nothing is searched for.
|
|
||||||
func TestResolveSocketUsesTheDefaultWithoutAnOverride(t *testing.T) {
|
|
||||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
require.NoError(t, os.WriteFile(cfg, []byte("static_host_map: {}\n"), 0600))
|
|
||||||
|
|
||||||
p, err := resolveSocket("", cfg)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, localapi.DefaultSocketPath, p)
|
|
||||||
|
|
||||||
// The test binary has no config next to it.
|
|
||||||
p, err = resolveSocket("", "")
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, localapi.DefaultSocketPath, p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestResolveSocketFlagWins(t *testing.T) {
|
|
||||||
p, err := resolveSocket("/explicit.sock", "/does/not/matter.yml")
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, "/explicit.sock", p)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParseCommandReportsWhatFlagSaid covers the three ways a flag line goes wrong, which
|
|
||||||
// are different mistakes: an unknown flag, a valid flag with a missing value, and a
|
|
||||||
// valid flag with a value it cannot parse.
|
|
||||||
func TestParseCommandReportsWhatFlagSaid(t *testing.T) {
|
|
||||||
schema := []commands.CommandSchema{{
|
|
||||||
Name: "change-remote",
|
|
||||||
Flags: []commands.FlagSchema{
|
|
||||||
{Name: "address"},
|
|
||||||
{Name: "by-index", Bool: true},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
|
|
||||||
cases := map[string]struct {
|
|
||||||
argv []string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
"missing value": {[]string{"change-remote", "-address"}, "flag needs an argument: -address"},
|
|
||||||
"bad bool": {[]string{"change-remote", "-by-index=maybe"}, "invalid boolean value \"maybe\" for -by-index"},
|
|
||||||
"unknown flag": {[]string{"change-remote", "-nope"}, "flag provided but not defined: -nope"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, tc := range cases {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
_, _, err := parseCommand(schema, tc.argv)
|
|
||||||
require.Error(t, err)
|
|
||||||
require.ErrorContains(t, err, "nebula: change-remote: "+tc.want)
|
|
||||||
require.ErrorContains(t, err, "see 'nebula ctl change-remote -h'")
|
|
||||||
assert.NotContains(t, err.Error(), "does not take")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParseCommandOffPresentationFlagIsNoPreference: the daemon treats -json=false as
|
|
||||||
// no preference, so nebula ctl must too, or the same line renders differently on the
|
|
||||||
// two surfaces. Only a true value asks for JSON, and -pretty implies it.
|
|
||||||
func TestParseCommandOffPresentationFlagIsNoPreference(t *testing.T) {
|
|
||||||
schema := []commands.CommandSchema{{
|
|
||||||
Name: "device-info",
|
|
||||||
Flags: []commands.FlagSchema{
|
|
||||||
{Name: commands.FlagJSON, Bool: true, Default: "false"},
|
|
||||||
{Name: commands.FlagPretty, Bool: true, Default: "false"},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
argv []string
|
|
||||||
want commands.Format
|
|
||||||
wire string
|
|
||||||
}{
|
|
||||||
{[]string{"device-info"}, commands.FormatUnset, "text"},
|
|
||||||
{[]string{"device-info", "-json=false"}, commands.FormatUnset, "text"},
|
|
||||||
{[]string{"device-info", "-json"}, commands.FormatJSON, "json"},
|
|
||||||
{[]string{"device-info", "-pretty"}, commands.FormatPrettyJSON, "json"},
|
|
||||||
} {
|
|
||||||
t.Run(strings.Join(tc.argv[1:], " "), func(t *testing.T) {
|
|
||||||
req, printedHelp, err := parseCommand(schema, tc.argv)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, printedHelp)
|
|
||||||
assert.Equal(t, tc.want, req.Format)
|
|
||||||
assert.Equal(t, tc.wire, wireFormat(req.Format))
|
|
||||||
assert.Nil(t, req.Params, "presentation flags are never sent as parameters")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParseCommandReadsTheLineAsTheDaemonDoes: nebula ctl parses the line with the same
|
|
||||||
// rules as the daemon, so an operand after "--" reaches the command on both and a
|
|
||||||
// negative number before it is the flag it would be at an ssh prompt.
|
|
||||||
func TestParseCommandReadsTheLineAsTheDaemonDoes(t *testing.T) {
|
|
||||||
schema := []commands.CommandSchema{{Name: "set"}}
|
|
||||||
|
|
||||||
req, printedHelp, err := parseCommand(schema, []string{"set", "--", "-1"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, printedHelp)
|
|
||||||
assert.Equal(t, commands.Name("set"), req.name)
|
|
||||||
assert.Nil(t, req.Params)
|
|
||||||
assert.Equal(t, []string{"-1"}, req.Args)
|
|
||||||
|
|
||||||
_, _, err = parseCommand(schema, []string{"set", "-1"})
|
|
||||||
require.ErrorContains(t, err, "flag provided but not defined: -1")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestOutputRendersForTheFormatAsked: what the daemon answered is read by the format the
|
|
||||||
// line asked for, never by sniffing the bytes. A text answer is the command's rendering,
|
|
||||||
// printed as it came; a JSON answer whose value is a string stays quoted, since to the
|
|
||||||
// script reading it that string is the JSON.
|
|
||||||
func TestOutputRendersForTheFormatAsked(t *testing.T) {
|
|
||||||
text := &localapi.Response{Text: []byte("Log level is: info\n")}
|
|
||||||
assert.Equal(t, "Log level is: info\n", output(text, commands.FormatUnset))
|
|
||||||
assert.Equal(t, "Log level is: info\n", output(text, commands.FormatText))
|
|
||||||
|
|
||||||
str := &localapi.Response{Result: json.RawMessage(`"some string"`)}
|
|
||||||
assert.Equal(t, `"some string"`, output(str, commands.FormatJSON))
|
|
||||||
assert.Equal(t, `"some string"`, output(str, commands.FormatPrettyJSON))
|
|
||||||
|
|
||||||
// Keys stay in the order the daemon wrote them and a uint64 past 2^53 is not rounded,
|
|
||||||
// which decoding into `any` and encoding again would do.
|
|
||||||
obj := &localapi.Response{Result: json.RawMessage(`{"z":18446744073709551615,"a":{"y":[1,2],"b":true}}`)}
|
|
||||||
//nolint:testifylint // the layout is what is under test, which JSONEq would not see
|
|
||||||
assert.Equal(t, `{"z":18446744073709551615,"a":{"y":[1,2],"b":true}}`, output(obj, commands.FormatJSON))
|
|
||||||
//nolint:testifylint // as above
|
|
||||||
assert.Equal(t, "{\n \"z\": 18446744073709551615,\n \"a\": {\n \"y\": [\n 1,\n 2\n ],\n \"b\": true\n }\n}", output(obj, commands.FormatPrettyJSON))
|
|
||||||
|
|
||||||
bad := &localapi.Response{Result: json.RawMessage(`{"a":`)}
|
|
||||||
assert.Equal(t, `{"a":`, output(bad, commands.FormatPrettyJSON), "what cannot be indented is printed as it came")
|
|
||||||
|
|
||||||
none := &localapi.Response{}
|
|
||||||
assert.Empty(t, output(none, commands.FormatJSON))
|
|
||||||
assert.Empty(t, output(none, commands.FormatUnset))
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSplitLineLiftsOwnFlagsFromAnywhere: -config and -socket are the client's wherever
|
|
||||||
// they appear, before the command or after it, in either spelling, so the two orders
|
|
||||||
// mean the same line. Everything else after the command word stays in order for the
|
|
||||||
// command's own parse, including flags and operands that happen to look like values.
|
|
||||||
func TestSplitLineLiftsOwnFlagsFromAnywhere(t *testing.T) {
|
|
||||||
newFS := func() *flag.FlagSet {
|
|
||||||
fs := flag.NewFlagSet("nebula ctl", flag.ContinueOnError)
|
|
||||||
fs.String(commands.FlagConfig, "", "")
|
|
||||||
fs.String(commands.FlagSocket, "", "")
|
|
||||||
return fs
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
args []string
|
|
||||||
wantOwn []string
|
|
||||||
wantCmd []string
|
|
||||||
}{
|
|
||||||
{nil, nil, nil},
|
|
||||||
{[]string{"identity"}, nil, []string{"identity"}},
|
|
||||||
{[]string{"-config", "x", "identity"}, []string{"-config", "x"}, []string{"identity"}},
|
|
||||||
{[]string{"identity", "-config", "x"}, []string{"-config", "x"}, []string{"identity"}},
|
|
||||||
{[]string{"identity", "-config=x"}, []string{"-config=x"}, []string{"identity"}},
|
|
||||||
{[]string{"identity", "--socket", "s"}, []string{"--socket", "s"}, []string{"identity"}},
|
|
||||||
{[]string{"-socket", "s", "identity", "-config", "x"}, []string{"-socket", "s", "-config", "x"}, []string{"identity"}},
|
|
||||||
// The command's flags and operands are left where they are, around the lifted ones.
|
|
||||||
{[]string{"print-tunnel", "10.0.0.1", "-config", "x", "-json"}, []string{"-config", "x"}, []string{"print-tunnel", "10.0.0.1", "-json"}},
|
|
||||||
{[]string{"change-remote", "-address", "1.2.3.4:5", "-socket", "s", "10.0.0.1"}, []string{"-socket", "s"}, []string{"change-remote", "-address", "1.2.3.4:5", "10.0.0.1"}},
|
|
||||||
// -h before the command is the client's usage; after it, the command's help.
|
|
||||||
{[]string{"-h"}, []string{"-h"}, nil},
|
|
||||||
{[]string{"identity", "-h"}, nil, []string{"identity", "-h"}},
|
|
||||||
// An unknown flag before the command is the client's to report, and does not
|
|
||||||
// swallow the command word as its value.
|
|
||||||
{[]string{"-nope", "identity"}, []string{"-nope"}, []string{"identity"}},
|
|
||||||
// A -config with nothing after it is left for fs.Parse to report.
|
|
||||||
{[]string{"identity", "-config"}, []string{"-config"}, []string{"identity"}},
|
|
||||||
// "--" before the command is consumed, as fs.Parse consumed it; after the command
|
|
||||||
// it belongs to the line and ends the lifting.
|
|
||||||
{[]string{"--", "identity", "-config", "x"}, []string{"-config", "x"}, []string{"identity"}},
|
|
||||||
{[]string{"identity", "--", "-config", "x"}, nil, []string{"identity", "--", "-config", "x"}},
|
|
||||||
} {
|
|
||||||
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
|
|
||||||
own, cmd := splitLine(newFS(), tc.args)
|
|
||||||
assert.Equal(t, tc.wantOwn, own)
|
|
||||||
assert.Equal(t, tc.wantCmd, cmd)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestTrailingHandlesWordsAfterTheDaemonsFlags: what flag.Parse leaves behind is never
|
|
||||||
// a daemon to start. A leading ctl runs the client on the rest, with the daemon's
|
|
||||||
// -config carried over; anything else is a mistyped subcommand. Only -h is run here,
|
|
||||||
// since the client's help needs no daemon: it proves the words reach Run and that a
|
|
||||||
// carried -config is accepted by it.
|
|
||||||
func TestTrailingHandlesWordsAfterTheDaemonsFlags(t *testing.T) {
|
|
||||||
code, done := Trailing(nil, "")
|
|
||||||
assert.False(t, done)
|
|
||||||
assert.Equal(t, 0, code)
|
|
||||||
|
|
||||||
code, done = Trailing([]string{"clt"}, "")
|
|
||||||
assert.True(t, done)
|
|
||||||
assert.Equal(t, 1, code)
|
|
||||||
|
|
||||||
code, done = Trailing([]string{Word, "-h"}, "")
|
|
||||||
assert.True(t, done)
|
|
||||||
assert.Equal(t, 0, code)
|
|
||||||
|
|
||||||
code, done = Trailing([]string{Word, "-h"}, "/etc/nebula/config.yml")
|
|
||||||
assert.True(t, done)
|
|
||||||
assert.Equal(t, 0, code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSubcommandOnlyReadsTheFirstWord: a flag first means the line is the daemon's to
|
|
||||||
// parse, and whatever follows the flags is Trailing's to judge.
|
|
||||||
func TestSubcommandOnlyReadsTheFirstWord(t *testing.T) {
|
|
||||||
_, done := Subcommand([]string{"nebula", "-config", "x", Word})
|
|
||||||
assert.False(t, done)
|
|
||||||
|
|
||||||
code, done := Subcommand([]string{"nebula", "clt"})
|
|
||||||
assert.True(t, done)
|
|
||||||
assert.Equal(t, 1, code)
|
|
||||||
|
|
||||||
code, done = Subcommand([]string{"nebula", Word, "-h"})
|
|
||||||
assert.True(t, done)
|
|
||||||
assert.Equal(t, 0, code)
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package ctl
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestResolveSocketDiagnosesAnOverlongOverride: the CLI applies the daemon's own rule to
|
|
||||||
// the override, so it says what the daemon's log says rather than dialing a path the
|
|
||||||
// kernel would truncate and reporting the generic failure. The rule is sun_path's, which
|
|
||||||
// a named pipe does not have, so this is a unix test.
|
|
||||||
func TestResolveSocketDiagnosesAnOverlongOverride(t *testing.T) {
|
|
||||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
long := "/" + strings.Repeat("x", 120)
|
|
||||||
require.NoError(t, os.WriteFile(cfg, []byte("local_api:\n control:\n socket: "+long+"\n"), 0600))
|
|
||||||
|
|
||||||
_, err := resolveSocket("", cfg)
|
|
||||||
require.Error(t, err)
|
|
||||||
require.ErrorContains(t, err, "too long for this platform")
|
|
||||||
assert.ErrorContains(t, err, localapi.CtlSocketKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestResolveSocketRefusesARelativeOverride: the CLI applies the daemon's rule here too,
|
|
||||||
// so a relative path in the config is reported as the daemon's log reports it rather
|
|
||||||
// than resolved against wherever nebula ctl happened to be run from.
|
|
||||||
func TestResolveSocketRefusesARelativeOverride(t *testing.T) {
|
|
||||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
require.NoError(t, os.WriteFile(cfg, []byte("local_api:\n control:\n socket: run/ctl.sock\n"), 0600))
|
|
||||||
|
|
||||||
_, err := resolveSocket("", cfg)
|
|
||||||
require.Error(t, err)
|
|
||||||
require.ErrorContains(t, err, "must be an absolute path")
|
|
||||||
assert.ErrorContains(t, err, localapi.CtlSocketKey)
|
|
||||||
}
|
|
||||||
+7
-34
@@ -3,14 +3,11 @@ package main
|
|||||||
import (
|
import (
|
||||||
"crypto/ecdsa"
|
"crypto/ecdsa"
|
||||||
"crypto/elliptic"
|
"crypto/elliptic"
|
||||||
"crypto/fips140"
|
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"errors"
|
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"math"
|
"math"
|
||||||
"math/bits"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -46,28 +43,7 @@ type caFlags struct {
|
|||||||
subnets *string
|
subnets *string
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultCurve() string {
|
|
||||||
if fips140.Enforced() {
|
|
||||||
return "P256"
|
|
||||||
}
|
|
||||||
return "25519"
|
|
||||||
}
|
|
||||||
|
|
||||||
func newCaFlags() *caFlags {
|
func newCaFlags() *caFlags {
|
||||||
// prevent running out of memory on 32-bit systems by defaulting to
|
|
||||||
// RFC9106's recommendation for memory-constrained environments
|
|
||||||
var (
|
|
||||||
defaultArgonMemory uint
|
|
||||||
defaultArgonIterations uint
|
|
||||||
)
|
|
||||||
if bits.UintSize == 32 {
|
|
||||||
defaultArgonMemory = 64 * 1024
|
|
||||||
defaultArgonIterations = 3
|
|
||||||
} else {
|
|
||||||
defaultArgonMemory = 2 * 1024 * 1024
|
|
||||||
defaultArgonIterations = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
cf := caFlags{set: flag.NewFlagSet("ca", flag.ContinueOnError)}
|
cf := caFlags{set: flag.NewFlagSet("ca", flag.ContinueOnError)}
|
||||||
cf.set.Usage = func() {}
|
cf.set.Usage = func() {}
|
||||||
cf.name = cf.set.String("name", "", "Required: name of the certificate authority")
|
cf.name = cf.set.String("name", "", "Required: name of the certificate authority")
|
||||||
@@ -79,11 +55,11 @@ func newCaFlags() *caFlags {
|
|||||||
cf.groups = cf.set.String("groups", "", "Optional: comma separated list of groups. This will limit which groups subordinate certs can use")
|
cf.groups = cf.set.String("groups", "", "Optional: comma separated list of groups. This will limit which groups subordinate certs can use")
|
||||||
cf.networks = cf.set.String("networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in networks")
|
cf.networks = cf.set.String("networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in networks")
|
||||||
cf.unsafeNetworks = cf.set.String("unsafe-networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in unsafe networks")
|
cf.unsafeNetworks = cf.set.String("unsafe-networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in unsafe networks")
|
||||||
cf.argonMemory = cf.set.Uint("argon-memory", defaultArgonMemory, "Optional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase")
|
cf.argonMemory = cf.set.Uint("argon-memory", 2*1024*1024, "Optional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase")
|
||||||
cf.argonParallelism = cf.set.Uint("argon-parallelism", 4, "Optional: Argon2 parallelism parameter used for encrypted private key passphrase")
|
cf.argonParallelism = cf.set.Uint("argon-parallelism", 4, "Optional: Argon2 parallelism parameter used for encrypted private key passphrase")
|
||||||
cf.argonIterations = cf.set.Uint("argon-iterations", defaultArgonIterations, "Optional: Argon2 iterations parameter used for encrypted private key passphrase")
|
cf.argonIterations = cf.set.Uint("argon-iterations", 1, "Optional: Argon2 iterations parameter used for encrypted private key passphrase")
|
||||||
cf.encryption = cf.set.Bool("encrypt", false, "Optional: prompt for passphrase and write out-key in an encrypted format")
|
cf.encryption = cf.set.Bool("encrypt", false, "Optional: prompt for passphrase and write out-key in an encrypted format")
|
||||||
cf.curve = cf.set.String("curve", defaultCurve(), "EdDSA/ECDSA Curve (25519, P256)")
|
cf.curve = cf.set.String("curve", "25519", "EdDSA/ECDSA Curve (25519, P256)")
|
||||||
cf.p11url = p11Flag(cf.set)
|
cf.p11url = p11Flag(cf.set)
|
||||||
|
|
||||||
cf.ips = cf.set.String("ips", "", "Deprecated, see -networks")
|
cf.ips = cf.set.String("ips", "", "Deprecated, see -networks")
|
||||||
@@ -151,7 +127,7 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
|
|
||||||
var groups []string
|
var groups []string
|
||||||
if *cf.groups != "" {
|
if *cf.groups != "" {
|
||||||
for rg := range strings.SplitSeq(*cf.groups, ",") {
|
for _, rg := range strings.Split(*cf.groups, ",") {
|
||||||
g := strings.TrimSpace(rg)
|
g := strings.TrimSpace(rg)
|
||||||
if g != "" {
|
if g != "" {
|
||||||
groups = append(groups, g)
|
groups = append(groups, g)
|
||||||
@@ -171,7 +147,7 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *cf.networks != "" {
|
if *cf.networks != "" {
|
||||||
for rs := range strings.SplitSeq(*cf.networks, ",") {
|
for _, rs := range strings.Split(*cf.networks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -193,7 +169,7 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *cf.unsafeNetworks != "" {
|
if *cf.unsafeNetworks != "" {
|
||||||
for rs := range strings.SplitSeq(*cf.unsafeNetworks, ",") {
|
for _, rs := range strings.Split(*cf.unsafeNetworks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -221,7 +197,7 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
if !isP11 && *cf.encryption {
|
if !isP11 && *cf.encryption {
|
||||||
passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
|
passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
|
||||||
if len(passphrase) == 0 {
|
if len(passphrase) == 0 {
|
||||||
for range 5 {
|
for i := 0; i < 5; i++ {
|
||||||
errOut.Write([]byte("Enter passphrase: "))
|
errOut.Write([]byte("Enter passphrase: "))
|
||||||
passphrase, err = pr.ReadPassword()
|
passphrase, err = pr.ReadPassword()
|
||||||
|
|
||||||
@@ -268,9 +244,6 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
} else {
|
} else {
|
||||||
switch *cf.curve {
|
switch *cf.curve {
|
||||||
case "25519", "X25519", "Curve25519", "CURVE25519":
|
case "25519", "X25519", "Curve25519", "CURVE25519":
|
||||||
if fips140.Enforced() {
|
|
||||||
return errors.New("use of Curve25519 is not allowed in FIPS 140-only mode")
|
|
||||||
}
|
|
||||||
curve = cert.Curve_CURVE25519
|
curve = cert.Curve_CURVE25519
|
||||||
pub, rawPriv, err = ed25519.GenerateKey(rand.Reader)
|
pub, rawPriv, err = ed25519.GenerateKey(rand.Reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build !windows
|
//go:build !windows
|
||||||
|
// +build !windows
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@@ -6,9 +7,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"errors"
|
"errors"
|
||||||
"math/bits"
|
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -23,18 +22,6 @@ func Test_caSummary(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Test_caHelp(t *testing.T) {
|
func Test_caHelp(t *testing.T) {
|
||||||
var (
|
|
||||||
defaultArgonMemory string
|
|
||||||
defaultArgonIterations string
|
|
||||||
)
|
|
||||||
if bits.UintSize == 32 {
|
|
||||||
defaultArgonMemory = strconv.Itoa(64 * 1024)
|
|
||||||
defaultArgonIterations = strconv.Itoa(3)
|
|
||||||
} else {
|
|
||||||
defaultArgonMemory = strconv.Itoa(2 * 1024 * 1024)
|
|
||||||
defaultArgonIterations = strconv.Itoa(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
ob := &bytes.Buffer{}
|
ob := &bytes.Buffer{}
|
||||||
caHelp(ob)
|
caHelp(ob)
|
||||||
assert.Equal(
|
assert.Equal(
|
||||||
@@ -42,9 +29,9 @@ func Test_caHelp(t *testing.T) {
|
|||||||
"Usage of "+os.Args[0]+" ca <flags>: create a self signed certificate authority\n"+
|
"Usage of "+os.Args[0]+" ca <flags>: create a self signed certificate authority\n"+
|
||||||
" Pass \"-\" to any path flag to read from stdin or write to stdout.\n"+
|
" Pass \"-\" to any path flag to read from stdin or write to stdout.\n"+
|
||||||
" -argon-iterations uint\n"+
|
" -argon-iterations uint\n"+
|
||||||
" \tOptional: Argon2 iterations parameter used for encrypted private key passphrase (default "+defaultArgonIterations+")\n"+
|
" \tOptional: Argon2 iterations parameter used for encrypted private key passphrase (default 1)\n"+
|
||||||
" -argon-memory uint\n"+
|
" -argon-memory uint\n"+
|
||||||
" \tOptional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase (default "+defaultArgonMemory+")\n"+
|
" \tOptional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase (default 2097152)\n"+
|
||||||
" -argon-parallelism uint\n"+
|
" -argon-parallelism uint\n"+
|
||||||
" \tOptional: Argon2 parallelism parameter used for encrypted private key passphrase (default 4)\n"+
|
" \tOptional: Argon2 parallelism parameter used for encrypted private key passphrase (default 4)\n"+
|
||||||
" -curve string\n"+
|
" -curve string\n"+
|
||||||
@@ -201,16 +188,10 @@ func Test_ca(t *testing.T) {
|
|||||||
k, _ := pem.Decode(rb)
|
k, _ := pem.Decode(rb)
|
||||||
ned, err := cert.UnmarshalNebulaEncryptedData(k.Bytes)
|
ned, err := cert.UnmarshalNebulaEncryptedData(k.Bytes)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
// we won't know salt in advance, so just check start of string
|
||||||
if bits.UintSize == 32 {
|
assert.Equal(t, uint32(2*1024*1024), ned.EncryptionMetadata.Argon2Parameters.Memory)
|
||||||
assert.Equal(t, uint32(64*1024), ned.EncryptionMetadata.Argon2Parameters.Memory)
|
|
||||||
assert.Equal(t, uint32(3), ned.EncryptionMetadata.Argon2Parameters.Iterations)
|
|
||||||
} else {
|
|
||||||
assert.Equal(t, uint32(2*1024*1024), ned.EncryptionMetadata.Argon2Parameters.Memory)
|
|
||||||
assert.Equal(t, uint32(1), ned.EncryptionMetadata.Argon2Parameters.Iterations)
|
|
||||||
}
|
|
||||||
|
|
||||||
assert.Equal(t, uint8(4), ned.EncryptionMetadata.Argon2Parameters.Parallelism)
|
assert.Equal(t, uint8(4), ned.EncryptionMetadata.Argon2Parameters.Parallelism)
|
||||||
|
assert.Equal(t, uint32(1), ned.EncryptionMetadata.Argon2Parameters.Iterations)
|
||||||
|
|
||||||
// verify the key is valid and decrypt-able
|
// verify the key is valid and decrypt-able
|
||||||
var curve cert.Curve
|
var curve cert.Curve
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
//go:build fips140enforce
|
|
||||||
|
|
||||||
//go:debug fips140=only
|
|
||||||
|
|
||||||
package main
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/fips140"
|
|
||||||
"errors"
|
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -26,7 +24,7 @@ func newKeygenFlags() *keygenFlags {
|
|||||||
cf.set.Usage = func() {}
|
cf.set.Usage = func() {}
|
||||||
cf.outPubPath = cf.set.String("out-pub", "", "Required: path to write the public key to")
|
cf.outPubPath = cf.set.String("out-pub", "", "Required: path to write the public key to")
|
||||||
cf.outKeyPath = cf.set.String("out-key", "", "Required: path to write the private key to")
|
cf.outKeyPath = cf.set.String("out-key", "", "Required: path to write the private key to")
|
||||||
cf.curve = cf.set.String("curve", defaultCurve(), "ECDH Curve (25519, P256)")
|
cf.curve = cf.set.String("curve", "25519", "ECDH Curve (25519, P256)")
|
||||||
cf.p11url = p11Flag(cf.set)
|
cf.p11url = p11Flag(cf.set)
|
||||||
return &cf
|
return &cf
|
||||||
}
|
}
|
||||||
@@ -63,9 +61,6 @@ func keygen(args []string, out io.Writer, errOut io.Writer) error {
|
|||||||
} else {
|
} else {
|
||||||
switch *cf.curve {
|
switch *cf.curve {
|
||||||
case "25519", "X25519", "Curve25519", "CURVE25519":
|
case "25519", "X25519", "Curve25519", "CURVE25519":
|
||||||
if fips140.Enforced() {
|
|
||||||
return errors.New("use of Curve25519 is not allowed in FIPS 140-only mode")
|
|
||||||
}
|
|
||||||
pub, rawPriv = x25519Keypair()
|
pub, rawPriv = x25519Keypair()
|
||||||
curve = cert.Curve_CURVE25519
|
curve = cert.Curve_CURVE25519
|
||||||
case "P256":
|
case "P256":
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/ecdh"
|
"crypto/ecdh"
|
||||||
"crypto/fips140"
|
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
@@ -146,7 +145,7 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
|
passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
|
||||||
if len(passphrase) == 0 {
|
if len(passphrase) == 0 {
|
||||||
// ask for a passphrase until we get one
|
// ask for a passphrase until we get one
|
||||||
for range 5 {
|
for i := 0; i < 5; i++ {
|
||||||
errOut.Write([]byte("Enter passphrase: "))
|
errOut.Write([]byte("Enter passphrase: "))
|
||||||
passphrase, err = pr.ReadPassword()
|
passphrase, err = pr.ReadPassword()
|
||||||
|
|
||||||
@@ -203,7 +202,7 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *sf.networks != "" {
|
if *sf.networks != "" {
|
||||||
for rs := range strings.SplitSeq(*sf.networks, ",") {
|
for _, rs := range strings.Split(*sf.networks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -228,7 +227,7 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *sf.unsafeNetworks != "" {
|
if *sf.unsafeNetworks != "" {
|
||||||
for rs := range strings.SplitSeq(*sf.unsafeNetworks, ",") {
|
for _, rs := range strings.Split(*sf.unsafeNetworks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -247,7 +246,7 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
|
|
||||||
var groups []string
|
var groups []string
|
||||||
if *sf.groups != "" {
|
if *sf.groups != "" {
|
||||||
for rg := range strings.SplitSeq(*sf.groups, ",") {
|
for _, rg := range strings.Split(*sf.groups, ",") {
|
||||||
g := strings.TrimSpace(rg)
|
g := strings.TrimSpace(rg)
|
||||||
if g != "" {
|
if g != "" {
|
||||||
groups = append(groups, g)
|
groups = append(groups, g)
|
||||||
@@ -269,10 +268,6 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
}(p11Client)
|
}(p11Client)
|
||||||
}
|
}
|
||||||
|
|
||||||
if fips140.Enforced() && curve == cert.Curve_CURVE25519 {
|
|
||||||
return errors.New("use of Curve25519 is not allowed in FIPS 140-only mode")
|
|
||||||
}
|
|
||||||
|
|
||||||
if *sf.inPubPath != "" {
|
if *sf.inPubPath != "" {
|
||||||
var pubCurve cert.Curve
|
var pubCurve cert.Curve
|
||||||
rawPub, err := readInput("in-pub", *sf.inPubPath, &claims)
|
rawPub, err := readInput("in-pub", *sf.inPubPath, &claims)
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build !windows
|
//go:build !windows
|
||||||
|
// +build !windows
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
//go:build fips140enforce
|
|
||||||
|
|
||||||
//go:debug fips140=only
|
|
||||||
|
|
||||||
package main
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build !windows
|
//go:build !windows
|
||||||
|
// +build !windows
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/slackhq/nebula"
|
"github.com/slackhq/nebula"
|
||||||
"github.com/slackhq/nebula/cmd/internal/ctl"
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
"github.com/slackhq/nebula/logging"
|
"github.com/slackhq/nebula/logging"
|
||||||
"github.com/slackhq/nebula/util"
|
"github.com/slackhq/nebula/util"
|
||||||
)
|
)
|
||||||
@@ -34,11 +32,6 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// commands are either `nebula ctl ...` or `nebula -<flag> ...`
|
|
||||||
if code, done := ctl.Subcommand(os.Args); done {
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
serviceFlag := flag.String("service", "", "Control the system service.")
|
serviceFlag := flag.String("service", "", "Control the system service.")
|
||||||
configPath := flag.String("config", "", "Path to either a file or directory to load configuration from")
|
configPath := flag.String("config", "", "Path to either a file or directory to load configuration from")
|
||||||
configTest := flag.Bool("test", false, "Test the config and print the end result. Non zero exit indicates a faulty config")
|
configTest := flag.Bool("test", false, "Test the config and print the end result. Non zero exit indicates a faulty config")
|
||||||
@@ -47,12 +40,6 @@ func main() {
|
|||||||
|
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
// A word after the daemon's flags is `ctl` in the other place an operator puts it,
|
|
||||||
// or a mistyped subcommand, and either way not a daemon to start; see Trailing.
|
|
||||||
if code, done := ctl.Trailing(flag.Args(), *configPath); done {
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
if *printVersion {
|
if *printVersion {
|
||||||
fmt.Printf("Version: %s\n", Build)
|
fmt.Printf("Version: %s\n", Build)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
@@ -98,10 +85,9 @@ func main() {
|
|||||||
fmt.Printf("failed to apply logging config: %s", err)
|
fmt.Printf("failed to apply logging config: %s", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C) {
|
||||||
if err := logging.ApplyConfig(l, c); err != nil {
|
if err := logging.ApplyConfig(l, c); err != nil {
|
||||||
l.Error("Failed to reconfigure logger on reload", "error", err)
|
l.Error("Failed to reconfigure logger on reload", "error", err)
|
||||||
r.Failed()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -117,17 +103,9 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
local := localapi.Wire(ctrl.Context(), l, c, ctrl.Commands())
|
|
||||||
|
|
||||||
go ctrl.ShutdownBlock()
|
go ctrl.ShutdownBlock()
|
||||||
|
|
||||||
err := ctrl.Wait()
|
if err := ctrl.Wait(); err != nil {
|
||||||
|
|
||||||
// os.Exit skips deferred calls, so the sockets are removed here, before either
|
|
||||||
// exit below, rather than left to a deferred Stop that would never run.
|
|
||||||
local.Stop()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
l.Error("Nebula stopped due to fatal error", "error", err)
|
l.Error("Nebula stopped due to fatal error", "error", err)
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"github.com/kardianos/service"
|
"github.com/kardianos/service"
|
||||||
"github.com/slackhq/nebula"
|
"github.com/slackhq/nebula"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
"github.com/slackhq/nebula/logging"
|
"github.com/slackhq/nebula/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,7 +17,6 @@ type program struct {
|
|||||||
configPath *string
|
configPath *string
|
||||||
build string
|
build string
|
||||||
control *nebula.Control
|
control *nebula.Control
|
||||||
local *localapi.Endpoints
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *program) Start(s service.Service) error {
|
func (p *program) Start(s service.Service) error {
|
||||||
@@ -36,10 +34,9 @@ func (p *program) Start(s service.Service) error {
|
|||||||
if err := logging.ApplyConfig(l, c); err != nil {
|
if err := logging.ApplyConfig(l, c); err != nil {
|
||||||
return fmt.Errorf("failed to apply logging config: %s", err)
|
return fmt.Errorf("failed to apply logging config: %s", err)
|
||||||
}
|
}
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C) {
|
||||||
if err := logging.ApplyConfig(l, c); err != nil {
|
if err := logging.ApplyConfig(l, c); err != nil {
|
||||||
l.Error("Failed to reconfigure logger on reload", "error", err)
|
l.Error("Failed to reconfigure logger on reload", "error", err)
|
||||||
r.Failed()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -52,16 +49,10 @@ func (p *program) Start(s service.Service) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Now that we're started, stand up the local APIs.
|
|
||||||
p.local = localapi.Wire(p.control.Context(), l, c, p.control.Commands())
|
|
||||||
|
|
||||||
// Nebula can stop itself on a fatal packet reader error, make sure to log it if it happens.
|
// Nebula can stop itself on a fatal packet reader error, make sure to log it if it happens.
|
||||||
go func() {
|
go func() {
|
||||||
if err := p.control.Wait(); err != nil {
|
if err := p.control.Wait(); err != nil {
|
||||||
logger.Error(fmt.Sprintf("Nebula stopped due to fatal error: %v", err))
|
logger.Error(fmt.Sprintf("Nebula stopped due to fatal error: %v", err))
|
||||||
// os.Exit skips deferred calls and races the sockets' own context watchers,
|
|
||||||
// so they are removed here, as cmd/nebula does.
|
|
||||||
p.local.Stop()
|
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@@ -71,11 +62,6 @@ func (p *program) Start(s service.Service) error {
|
|||||||
|
|
||||||
func (p *program) Stop(s service.Service) error {
|
func (p *program) Stop(s service.Service) error {
|
||||||
logger.Info("Nebula service stopping.")
|
logger.Info("Nebula service stopping.")
|
||||||
|
|
||||||
if p.local != nil {
|
|
||||||
p.local.Stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.control == nil {
|
if p.control == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
//go:build fips140enforce
|
|
||||||
|
|
||||||
//go:debug fips140=only
|
|
||||||
|
|
||||||
package main
|
|
||||||
+2
-24
@@ -8,9 +8,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/slackhq/nebula"
|
"github.com/slackhq/nebula"
|
||||||
"github.com/slackhq/nebula/cmd/internal/ctl"
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
"github.com/slackhq/nebula/logging"
|
"github.com/slackhq/nebula/logging"
|
||||||
"github.com/slackhq/nebula/util"
|
"github.com/slackhq/nebula/util"
|
||||||
)
|
)
|
||||||
@@ -34,11 +32,6 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// commands are either `nebula ctl ...` or `nebula -<flag> ...`
|
|
||||||
if code, done := ctl.Subcommand(os.Args); done {
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
configPath := flag.String("config", "", "Path to either a file or directory to load configuration from")
|
configPath := flag.String("config", "", "Path to either a file or directory to load configuration from")
|
||||||
configTest := flag.Bool("test", false, "Test the config and print the end result. Non zero exit indicates a faulty config")
|
configTest := flag.Bool("test", false, "Test the config and print the end result. Non zero exit indicates a faulty config")
|
||||||
printVersion := flag.Bool("version", false, "Print version")
|
printVersion := flag.Bool("version", false, "Print version")
|
||||||
@@ -46,12 +39,6 @@ func main() {
|
|||||||
|
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
// A word after the daemon's flags is `ctl` in the other place an operator puts it,
|
|
||||||
// or a mistyped subcommand, and either way not a daemon to start; see Trailing.
|
|
||||||
if code, done := ctl.Trailing(flag.Args(), *configPath); done {
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
if *printVersion {
|
if *printVersion {
|
||||||
fmt.Printf("Version: %s\n", Build)
|
fmt.Printf("Version: %s\n", Build)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
@@ -84,10 +71,9 @@ func main() {
|
|||||||
fmt.Printf("failed to apply logging config: %s", err)
|
fmt.Printf("failed to apply logging config: %s", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C) {
|
||||||
if err := logging.ApplyConfig(l, c); err != nil {
|
if err := logging.ApplyConfig(l, c); err != nil {
|
||||||
l.Error("Failed to reconfigure logger on reload", "error", err)
|
l.Error("Failed to reconfigure logger on reload", "error", err)
|
||||||
r.Failed()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -103,18 +89,10 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
local := localapi.Wire(ctrl.Context(), l, c, ctrl.Commands())
|
|
||||||
|
|
||||||
go ctrl.ShutdownBlock()
|
go ctrl.ShutdownBlock()
|
||||||
notifyReady(l)
|
notifyReady(l)
|
||||||
|
|
||||||
err := ctrl.Wait()
|
if err := ctrl.Wait(); err != nil {
|
||||||
|
|
||||||
// os.Exit skips deferred calls, so the sockets are removed here, before either
|
|
||||||
// exit below, rather than left to a deferred Stop that would never run.
|
|
||||||
local.Stop()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
l.Error("Nebula stopped due to fatal error", "error", err)
|
l.Error("Nebula stopped due to fatal error", "error", err)
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build !linux
|
//go:build !linux
|
||||||
|
// +build !linux
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
-683
@@ -1,683 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"maps"
|
|
||||||
"net/netip"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/config"
|
|
||||||
"github.com/slackhq/nebula/header"
|
|
||||||
"github.com/slackhq/nebula/logging"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The commands nebula serves. attachCommands builds the one registry every surface
|
|
||||||
// reads; the ssh debug server is a consumer of it, not its owner, which is why this
|
|
||||||
// is not ssh.go. See the commands package for what a Command is.
|
|
||||||
|
|
||||||
type listHostMapFlags struct {
|
|
||||||
ByIndex bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type printCertFlags struct {
|
|
||||||
Raw bool
|
|
||||||
|
|
||||||
// Address is the -address form of the vpn addr, which the info API needs since a
|
|
||||||
// query string has no operands; see identityFlags for why presence is recorded.
|
|
||||||
Address string
|
|
||||||
addressSet bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *printCertFlags) setAddress(v string) error {
|
|
||||||
f.Address = v
|
|
||||||
f.addressSet = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type changeRemoteFlags struct {
|
|
||||||
Address string
|
|
||||||
}
|
|
||||||
|
|
||||||
type closeTunnelFlags struct {
|
|
||||||
LocalOnly bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type createTunnelFlags struct {
|
|
||||||
Address string
|
|
||||||
}
|
|
||||||
|
|
||||||
// lighthouseInfo is one entry of list-lighthouse-addrmap.
|
|
||||||
type lighthouseInfo struct {
|
|
||||||
VpnAddr string `json:"vpnAddr"`
|
|
||||||
Addrs *CacheMap `json:"addrs"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// deviceInfo is the result of device-info.
|
|
||||||
type deviceInfo struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Cidr []netip.Prefix `json:"cidr"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// certPEM is the result of print-cert -raw. The PEM form is a different thing to emit,
|
|
||||||
// not a different formatting of the certificate, so it is its own shape.
|
|
||||||
type certPEM struct {
|
|
||||||
PEM string `json:"pem"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Result shapes for print-relays. Field names are the JSON keys; changing them would
|
|
||||||
// change the output.
|
|
||||||
type relayFor struct {
|
|
||||||
Error string `json:",omitempty"`
|
|
||||||
Type string
|
|
||||||
State string
|
|
||||||
PeerAddr netip.Addr
|
|
||||||
LocalIndex uint32
|
|
||||||
RemoteIndex uint32
|
|
||||||
RelayedThrough []netip.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
type relayOutput struct {
|
|
||||||
NebulaAddr netip.Addr
|
|
||||||
RelayForAddrs []relayFor
|
|
||||||
}
|
|
||||||
|
|
||||||
type relaysOutput struct {
|
|
||||||
Relays []*relayOutput
|
|
||||||
}
|
|
||||||
|
|
||||||
type versionInfo struct {
|
|
||||||
Version string `json:"version"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type logLevelInfo struct {
|
|
||||||
Level string `json:"level"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type logFormatInfo struct {
|
|
||||||
Format string `json:"format"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// defineListHostMapFlags declares the flags list-hostmap and list-pending-hostmap share.
|
|
||||||
func defineListHostMapFlags(fl *flag.FlagSet, s *listHostMapFlags) {
|
|
||||||
fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
|
|
||||||
}
|
|
||||||
|
|
||||||
func attachCommands(l *slog.Logger, c *config.C, reg *commands.Registry, f *Interface) {
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.ListHostmap,
|
|
||||||
ShortDescription: "List all known previously connected hosts",
|
|
||||||
Text: commands.Typed(textListHostMap),
|
|
||||||
}, defineListHostMapFlags, func(s *listHostMapFlags, a []string) (commands.Result, error) {
|
|
||||||
return runListHostMap(f.hostMap, s)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.ListPendingHostmap,
|
|
||||||
ShortDescription: "List all handshaking hosts",
|
|
||||||
Text: commands.Typed(textListHostMap),
|
|
||||||
}, defineListHostMapFlags, func(s *listHostMapFlags, a []string) (commands.Result, error) {
|
|
||||||
return runListHostMap(f.handshakeManager, s)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.ListLighthouseAddrmap,
|
|
||||||
ShortDescription: "List all lighthouse map entries",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return runListLighthouseMap(f.lightHouse)
|
|
||||||
},
|
|
||||||
Text: commands.Typed(textListLighthouseMap),
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.Reload,
|
|
||||||
ShortDescription: "Reloads configuration from disk, same as sending HUP to the process",
|
|
||||||
// The line goes out before the reload: a reload that restarts the ssh server ends
|
|
||||||
// the session that asked, and this is what it sees.
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return commands.Did("Reloading config"), nil
|
|
||||||
},
|
|
||||||
Then: func() commands.Result {
|
|
||||||
return runReload(l, c)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.LogLevel,
|
|
||||||
ShortDescription: "Gets or sets the current log level",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return runLogLevel(l, a)
|
|
||||||
},
|
|
||||||
Text: commands.Typed(textLogLevel),
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.LogFormat,
|
|
||||||
ShortDescription: "Gets or sets the current log format",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return runLogFormat(l, a)
|
|
||||||
},
|
|
||||||
Text: commands.Typed(textLogFormat),
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.Version,
|
|
||||||
ShortDescription: "Prints the currently running version of nebula",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return commands.Value(versionInfo{Version: f.version}), nil
|
|
||||||
},
|
|
||||||
Text: commands.Typed(textVersion),
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.DeviceInfo,
|
|
||||||
ShortDescription: "Prints information about the network device.",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return commands.Value(runDeviceInfo(f)), nil
|
|
||||||
},
|
|
||||||
Text: commands.Typed(textDeviceInfo),
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.PrintCert,
|
|
||||||
ShortDescription: "Prints the current certificate being used or the certificate for the provided vpn addr",
|
|
||||||
Help: "The vpn addr is an operand or -address, which may carry a port so a connection's remote address can be passed through as is. For a peer it is the certificate nebula verified when the tunnel came up; with no address it is this node's own, the v2 certificate when both versions are loaded. -raw prints the PEM.",
|
|
||||||
Identity: true,
|
|
||||||
Text: textPrintCert,
|
|
||||||
}, func(fl *flag.FlagSet, s *printCertFlags) {
|
|
||||||
fl.BoolVar(&s.Raw, "raw", false, "prints the PEM encoded certificate; with -json, an object holding it")
|
|
||||||
fl.Func("address", "The vpn addr to look up, optionally with a port", s.setAddress)
|
|
||||||
}, func(s *printCertFlags, a []string) (commands.Result, error) {
|
|
||||||
return runPrintCert(f, s, a)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.Identity,
|
|
||||||
ShortDescription: "Prints the certificate identity of the host owning the provided vpn addr",
|
|
||||||
Help: "Identity is what the certificate says: name, vpn addrs, networks, groups, fingerprint, issuer and validity. The address may carry a port, so a connection's remote address can be passed through as is. For this node's own identity use whoami.",
|
|
||||||
Identity: true,
|
|
||||||
Text: commands.Typed(textIdentity),
|
|
||||||
}, func(fl *flag.FlagSet, s *identityFlags) {
|
|
||||||
fl.Func("address", "The vpn addr to look up, optionally with a port", s.setAddress)
|
|
||||||
}, func(s *identityFlags, a []string) (commands.Result, error) {
|
|
||||||
return runIdentity(f, s, a)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.Whoami,
|
|
||||||
ShortDescription: "Prints the certificate identity of this node",
|
|
||||||
Help: "The fields identity prints, read from this node's own certificate.",
|
|
||||||
Identity: true,
|
|
||||||
Text: commands.Typed(textIdentity),
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
if len(a) > 0 {
|
|
||||||
return commands.Failed("whoami takes no arguments"), nil
|
|
||||||
}
|
|
||||||
return runWhoami(f)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.PrintTunnel,
|
|
||||||
ShortDescription: "Prints json details about a tunnel for the provided vpn addr",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return runPrintTunnel(f, a)
|
|
||||||
},
|
|
||||||
// No Text on purpose: nothing human readable exists yet, and shipping an interim
|
|
||||||
// form would invite scripts against it. ssh defaults these to JSON; ctl asks.
|
|
||||||
JSONOnly: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.PrintRelays,
|
|
||||||
ShortDescription: "Prints json details about all relay info",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return commands.Value(runPrintRelays(f)), nil
|
|
||||||
},
|
|
||||||
// No Text on purpose; see print-tunnel.
|
|
||||||
JSONOnly: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.ChangeRemote,
|
|
||||||
ShortDescription: "Changes the remote address used in the tunnel for the provided vpn addr",
|
|
||||||
}, func(fl *flag.FlagSet, s *changeRemoteFlags) {
|
|
||||||
fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
|
|
||||||
}, func(s *changeRemoteFlags, a []string) (commands.Result, error) {
|
|
||||||
return runChangeRemote(f, s, a)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.CloseTunnel,
|
|
||||||
ShortDescription: "Closes a tunnel for the provided vpn addr",
|
|
||||||
}, func(fl *flag.FlagSet, s *closeTunnelFlags) {
|
|
||||||
fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
|
|
||||||
}, func(s *closeTunnelFlags, a []string) (commands.Result, error) {
|
|
||||||
return runCloseTunnel(f, s, a)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(commands.Flagged(&commands.Command{
|
|
||||||
Name: commands.CreateTunnel,
|
|
||||||
ShortDescription: "Creates a tunnel for the provided vpn address",
|
|
||||||
Help: "The lighthouses will be queried for real addresses but you can provide one as well.",
|
|
||||||
}, func(fl *flag.FlagSet, s *createTunnelFlags) {
|
|
||||||
fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
|
|
||||||
}, func(s *createTunnelFlags, a []string) (commands.Result, error) {
|
|
||||||
return runCreateTunnel(f, s, a)
|
|
||||||
}))
|
|
||||||
|
|
||||||
reg.Register(&commands.Command{
|
|
||||||
Name: commands.QueryLighthouse,
|
|
||||||
ShortDescription: "Query the lighthouses for the provided vpn address",
|
|
||||||
Help: "This command is asynchronous. Only currently known udp addresses will be printed.",
|
|
||||||
Run: func(fs any, a []string) (commands.Result, error) {
|
|
||||||
return runQueryLighthouse(f, a)
|
|
||||||
},
|
|
||||||
// No Text on purpose; see print-tunnel.
|
|
||||||
JSONOnly: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// runListHostMap computes the hostmap listing. Presentation is Render's job.
|
|
||||||
func runListHostMap(hl controlHostLister, fs *listHostMapFlags) (commands.Result, error) {
|
|
||||||
var hm []ControlHostInfo
|
|
||||||
if fs.ByIndex {
|
|
||||||
hm = listHostMapIndexes(hl)
|
|
||||||
} else {
|
|
||||||
hm = listHostMapHosts(hl)
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Slice(hm, func(i, j int) bool {
|
|
||||||
return hm[i].VpnAddrs[0].Compare(hm[j].VpnAddrs[0]) < 0
|
|
||||||
})
|
|
||||||
|
|
||||||
return commands.Value(hm), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// textListHostMap is the human rendering, shared by every surface.
|
|
||||||
func textListHostMap(hm []ControlHostInfo, w io.Writer) error {
|
|
||||||
for _, h := range hm {
|
|
||||||
if _, err := fmt.Fprintf(w, "%s: %s\n", h.VpnAddrs, h.RemoteAddrs); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runListLighthouseMap(lightHouse *LightHouse) (commands.Result, error) {
|
|
||||||
lightHouse.RLock()
|
|
||||||
addrMap := make([]lighthouseInfo, len(lightHouse.addrMap))
|
|
||||||
x := 0
|
|
||||||
for k, v := range lightHouse.addrMap {
|
|
||||||
addrMap[x] = lighthouseInfo{
|
|
||||||
VpnAddr: k.String(),
|
|
||||||
Addrs: v.CopyCache(),
|
|
||||||
}
|
|
||||||
x++
|
|
||||||
}
|
|
||||||
lightHouse.RUnlock()
|
|
||||||
|
|
||||||
sort.Slice(addrMap, func(i, j int) bool {
|
|
||||||
return strings.Compare(addrMap[i].VpnAddr, addrMap[j].VpnAddr) < 0
|
|
||||||
})
|
|
||||||
|
|
||||||
return commands.Value(addrMap), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func textListLighthouseMap(addrMap []lighthouseInfo, w io.Writer) error {
|
|
||||||
for _, e := range addrMap {
|
|
||||||
b, err := json.Marshal(e.Addrs)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := fmt.Fprintf(w, "%s: %s\n", e.VpnAddr, string(b)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func textVersion(vi versionInfo, w io.Writer) error {
|
|
||||||
_, err := fmt.Fprintf(w, "%s\n", vi.Version)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// vpnAddrOperand parses the vpn address a command takes as its first operand. noun is
|
|
||||||
// how the command's messages name it, "vpn address" or "vpn addr", which the output
|
|
||||||
// golden pins per command. With no operand, or one that does not parse, ok is false and
|
|
||||||
// res is the refusal to return.
|
|
||||||
func vpnAddrOperand(a []string, noun string) (vpnAddr netip.Addr, res commands.Result, ok bool) {
|
|
||||||
if len(a) == 0 {
|
|
||||||
return netip.Addr{}, commands.Failed("No vpn address was provided"), false
|
|
||||||
}
|
|
||||||
|
|
||||||
vpnAddr, err := netip.ParseAddr(a[0])
|
|
||||||
if err != nil {
|
|
||||||
return netip.Addr{}, commands.Failed("The provided %s could not be parsed: %s", noun, a[0]), false
|
|
||||||
}
|
|
||||||
|
|
||||||
return vpnAddr, commands.Result{}, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// tunnelOperand is vpnAddrOperand followed by the lookup of the tunnel it names.
|
|
||||||
func tunnelOperand(ifce *Interface, a []string, noun string) (*HostInfo, commands.Result, bool) {
|
|
||||||
vpnAddr, res, ok := vpnAddrOperand(a, noun)
|
|
||||||
if !ok {
|
|
||||||
return nil, res, false
|
|
||||||
}
|
|
||||||
|
|
||||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
|
||||||
if hostInfo == nil {
|
|
||||||
return nil, commands.Failed("Could not find tunnel for %s: %v", noun, a[0]), false
|
|
||||||
}
|
|
||||||
|
|
||||||
return hostInfo, commands.Result{}, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func runQueryLighthouse(ifce *Interface, a []string) (commands.Result, error) {
|
|
||||||
vpnAddr, res, ok := vpnAddrOperand(a, "vpn address")
|
|
||||||
if !ok {
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var cm *CacheMap
|
|
||||||
rl := ifce.lightHouse.Query(vpnAddr)
|
|
||||||
if rl != nil {
|
|
||||||
cm = rl.CopyCache()
|
|
||||||
}
|
|
||||||
return commands.Value(cm), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runCloseTunnel(ifce *Interface, flags *closeTunnelFlags, a []string) (commands.Result, error) {
|
|
||||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn address")
|
|
||||||
if !ok {
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !flags.LocalOnly {
|
|
||||||
ifce.send(
|
|
||||||
header.CloseTunnel,
|
|
||||||
0,
|
|
||||||
hostInfo.ConnectionState,
|
|
||||||
hostInfo,
|
|
||||||
[]byte{},
|
|
||||||
make([]byte, 12, 12),
|
|
||||||
make([]byte, mtu),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
ifce.closeTunnel(hostInfo)
|
|
||||||
return commands.Did("Closed"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runCreateTunnel(ifce *Interface, flags *createTunnelFlags, a []string) (commands.Result, error) {
|
|
||||||
|
|
||||||
vpnAddr, res, ok := vpnAddrOperand(a, "vpn address")
|
|
||||||
if !ok {
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr); hostInfo != nil {
|
|
||||||
return commands.Failed("Tunnel already exists"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if hostInfo := ifce.handshakeManager.QueryVpnAddr(vpnAddr); hostInfo != nil {
|
|
||||||
return commands.Failed("Tunnel already handshaking"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var addr netip.AddrPort
|
|
||||||
if flags.Address != "" {
|
|
||||||
var err error
|
|
||||||
addr, err = netip.ParseAddrPort(flags.Address)
|
|
||||||
if err != nil {
|
|
||||||
return commands.Failed("Address could not be parsed"), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set the remote from the callback, which StartHandshake runs under the handshake manager lock
|
|
||||||
// before the hostinfo reaches the handshake loop or the static-host trigger, so the address is
|
|
||||||
// in the RemoteList before the first handshake is sent.
|
|
||||||
ifce.handshakeManager.StartHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
|
|
||||||
if addr.IsValid() {
|
|
||||||
hh.hostinfo.SetRemote(addr)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return commands.Did("Created"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runChangeRemote(ifce *Interface, flags *changeRemoteFlags, a []string) (commands.Result, error) {
|
|
||||||
|
|
||||||
if len(a) == 0 {
|
|
||||||
return commands.Failed("No vpn address was provided"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if flags.Address == "" {
|
|
||||||
return commands.Failed("No address was provided"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := netip.ParseAddrPort(flags.Address)
|
|
||||||
if err != nil {
|
|
||||||
return commands.Failed("Address could not be parsed"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn address")
|
|
||||||
if !ok {
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
hostInfo.SetRemote(addr)
|
|
||||||
return commands.Did("Changed"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runLogLevel(l *slog.Logger, a []string) (commands.Result, error) {
|
|
||||||
ctrl, ok := l.Handler().(interface {
|
|
||||||
GetLevel() slog.Level
|
|
||||||
SetLevel(slog.Level)
|
|
||||||
})
|
|
||||||
if !ok {
|
|
||||||
return commands.Failed("Log level is not reconfigurable on this logger"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(a) > 0 {
|
|
||||||
level, err := logging.ParseLevel(strings.ToLower(a[0]))
|
|
||||||
if err != nil {
|
|
||||||
return commands.Failed("Unknown log level %s. Possible log levels: trace, debug, info, warn, error", a), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
ctrl.SetLevel(level)
|
|
||||||
}
|
|
||||||
|
|
||||||
return commands.Value(logLevelInfo{Level: logging.LevelName(ctrl.GetLevel())}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func textLogLevel(li logLevelInfo, w io.Writer) error {
|
|
||||||
_, err := fmt.Fprintf(w, "Log level is: %s\n", li.Level)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func runLogFormat(l *slog.Logger, a []string) (commands.Result, error) {
|
|
||||||
ctrl, ok := l.Handler().(interface {
|
|
||||||
GetFormat() string
|
|
||||||
SetFormat(string) error
|
|
||||||
})
|
|
||||||
if !ok {
|
|
||||||
return commands.Failed("Log format is not reconfigurable on this logger"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(a) > 0 {
|
|
||||||
if err := ctrl.SetFormat(strings.ToLower(a[0])); err != nil {
|
|
||||||
return commands.Failed("Unable to set log format: %s", err), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return commands.Value(logFormatInfo{Format: ctrl.GetFormat()}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func textLogFormat(fi logFormatInfo, w io.Writer) error {
|
|
||||||
_, err := fmt.Fprintf(w, "Log format is: %s\n", fi.Format)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// runPrintCert prints a certificate: this node's own, or the one the host owning a vpn
|
|
||||||
// addr presented. The addr is an operand, as it always was over ssh, or -address, which
|
|
||||||
// is how the info API names it, and an address of our own answers with our own
|
|
||||||
// certificate as identity does. A tunnel still handshaking, or one being torn down, has
|
|
||||||
// no certificate and is reported as not found.
|
|
||||||
func runPrintCert(ifce *Interface, args *printCertFlags, a []string) (commands.Result, error) {
|
|
||||||
if len(a) > 0 && args.addressSet {
|
|
||||||
return commands.Failed("print-cert takes one vpn addr, as -address or as an operand, not both"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
cs := ifce.pki.getCertState()
|
|
||||||
var c cert.Certificate
|
|
||||||
switch {
|
|
||||||
case len(a) > 0:
|
|
||||||
vpnAddr, res, ok := vpnAddrOperand(a, "vpn addr")
|
|
||||||
if !ok {
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
if c, _ = findCertificateForVpnAddr(cs, ifce.hostMap, vpnAddr); c == nil {
|
|
||||||
return commands.NotFound("Could not find tunnel for vpn addr: %v", a[0]), nil
|
|
||||||
}
|
|
||||||
case args.addressSet:
|
|
||||||
vpnAddr, err := parseVpnAddrWithOptionalPort(args.Address)
|
|
||||||
if err != nil {
|
|
||||||
return commands.Failed("The provided vpn addr could not be parsed: %s", args.Address), nil
|
|
||||||
}
|
|
||||||
if c, _ = findCertificateForVpnAddr(cs, ifce.hostMap, vpnAddr); c == nil {
|
|
||||||
return commands.NotFound("Could not find tunnel for vpn addr: %v", args.Address), nil
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if c = ownCertificate(cs); c == nil {
|
|
||||||
return commands.Failed("No certificate is loaded"), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if args.Raw {
|
|
||||||
b, err := c.MarshalPEM()
|
|
||||||
if err != nil {
|
|
||||||
return commands.Failed("Unable to marshal the certificate: %s", err), nil
|
|
||||||
}
|
|
||||||
return commands.Value(certPEM{PEM: string(b)}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return commands.Value(c), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// textPrintCert takes the value untyped: print-cert returns a certificate or, with -raw,
|
|
||||||
// its PEM, and those are two things to emit rather than two renderings of one.
|
|
||||||
func textPrintCert(v any, w io.Writer) error {
|
|
||||||
switch c := v.(type) {
|
|
||||||
case certPEM:
|
|
||||||
_, err := io.WriteString(w, c.PEM)
|
|
||||||
return err
|
|
||||||
case cert.Certificate:
|
|
||||||
_, err := io.WriteString(w, c.String()+"\n")
|
|
||||||
return err
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("expected a certificate, got %T", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func runPrintRelays(ifce *Interface) any {
|
|
||||||
ifce.hostMap.RLock()
|
|
||||||
relays := maps.Clone(ifce.hostMap.Relays)
|
|
||||||
ifce.hostMap.RUnlock()
|
|
||||||
|
|
||||||
co := relaysOutput{}
|
|
||||||
|
|
||||||
for k, v := range relays {
|
|
||||||
ro := relayOutput{NebulaAddr: v.vpnAddrs[0]}
|
|
||||||
co.Relays = append(co.Relays, &ro)
|
|
||||||
relayHI := ifce.hostMap.QueryVpnAddr(v.vpnAddrs[0])
|
|
||||||
if relayHI == nil {
|
|
||||||
ro.RelayForAddrs = append(ro.RelayForAddrs, relayFor{Error: "could not find hostinfo"})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, vpnAddr := range relayHI.relayState.CopyRelayForIps() {
|
|
||||||
rf := relayFor{}
|
|
||||||
r, ok := relayHI.relayState.GetRelayForByAddr(vpnAddr)
|
|
||||||
if ok {
|
|
||||||
t := ""
|
|
||||||
switch r.Type {
|
|
||||||
case ForwardingType:
|
|
||||||
t = "forwarding"
|
|
||||||
case TerminalType:
|
|
||||||
t = "terminal"
|
|
||||||
default:
|
|
||||||
t = "unknown"
|
|
||||||
}
|
|
||||||
|
|
||||||
st := ""
|
|
||||||
switch r.State {
|
|
||||||
case Requested:
|
|
||||||
st = "requested"
|
|
||||||
case Established:
|
|
||||||
st = "established"
|
|
||||||
default:
|
|
||||||
st = "unknown"
|
|
||||||
}
|
|
||||||
|
|
||||||
rf.LocalIndex = r.LocalIndex
|
|
||||||
rf.RemoteIndex = r.RemoteIndex
|
|
||||||
rf.PeerAddr = r.PeerAddr
|
|
||||||
rf.Type = t
|
|
||||||
rf.State = st
|
|
||||||
if rf.LocalIndex != k {
|
|
||||||
rf.Error = fmt.Sprintf("hostmap LocalIndex '%v' does not match RelayState LocalIndex", k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
relayedHI := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
|
||||||
if relayedHI != nil {
|
|
||||||
rf.RelayedThrough = append(rf.RelayedThrough, relayedHI.relayState.CopyRelayIps()...)
|
|
||||||
}
|
|
||||||
|
|
||||||
ro.RelayForAddrs = append(ro.RelayForAddrs, rf)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return co
|
|
||||||
}
|
|
||||||
|
|
||||||
func runPrintTunnel(ifce *Interface, a []string) (commands.Result, error) {
|
|
||||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn addr")
|
|
||||||
if !ok {
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return commands.Value(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges())), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runDeviceInfo(ifce *Interface) deviceInfo {
|
|
||||||
d := deviceInfo{
|
|
||||||
Name: ifce.inside.Name(),
|
|
||||||
Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
|
|
||||||
}
|
|
||||||
copy(d.Cidr, ifce.inside.Networks())
|
|
||||||
return d
|
|
||||||
}
|
|
||||||
|
|
||||||
func textDeviceInfo(d deviceInfo, w io.Writer) error {
|
|
||||||
_, err := fmt.Fprintf(w, "name=%v cidr=%v\n", d.Name, d.Cidr)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// runReload reloads the config and reports how it went. A reload that failed is a
|
|
||||||
// refusal, exit 1 over ssh; one that merely needs a restart is not.
|
|
||||||
func runReload(l *slog.Logger, c *config.C) commands.Result {
|
|
||||||
res := c.ReloadConfig()
|
|
||||||
res.Log(l)
|
|
||||||
if res.Err != nil || res.Failed {
|
|
||||||
return commands.Failed("%s", res.String())
|
|
||||||
}
|
|
||||||
return commands.Did("%s", res.String())
|
|
||||||
}
|
|
||||||
@@ -1,303 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CommandFlags is called before help or command execution to parse command line flags.
|
|
||||||
// It should return a flag.FlagSet instance and a pointer to the struct that will contain parsed flags
|
|
||||||
//
|
|
||||||
// Every call must build a fresh FlagSet and a fresh struct. Nothing may be shared between
|
|
||||||
// calls: a command runs on more than one surface and on more than one goroutine.
|
|
||||||
type CommandFlags func() (*flag.FlagSet, any)
|
|
||||||
|
|
||||||
// RunFunc computes a command's Result.
|
|
||||||
//
|
|
||||||
// fs is the pointer returned by Command.Flags, if there was one; -h, -help, -json and
|
|
||||||
// -pretty are reserved and handled before Run is called. a is the operands: whatever
|
|
||||||
// was not consumed as a flag. The Result is rendered by whichever surface asked: Value
|
|
||||||
// for a command that reports, Did or Failed for one that acts, Nothing for one with
|
|
||||||
// nothing to say. An error is for a failure of the command itself; a bad argument is
|
|
||||||
// Failed, so the caller hears why in its own format.
|
|
||||||
type RunFunc func(fs any, a []string) (Result, error)
|
|
||||||
|
|
||||||
// TextFunc renders a Result's Value for a person. See Typed for declaring one against
|
|
||||||
// the type the command actually returns.
|
|
||||||
type TextFunc func(v any, w io.Writer) error
|
|
||||||
|
|
||||||
type Command struct {
|
|
||||||
Name Name
|
|
||||||
ShortDescription string
|
|
||||||
Help string
|
|
||||||
|
|
||||||
// Identity indicates this command should be made available via the info socket.
|
|
||||||
Identity bool
|
|
||||||
|
|
||||||
Flags CommandFlags
|
|
||||||
|
|
||||||
// Run produces the command's Result, leaving presentation to Render.
|
|
||||||
Run RunFunc
|
|
||||||
|
|
||||||
// Text renders a Result's Value for a person. Both surfaces call it, so a command
|
|
||||||
// reads the same over ssh as it does through the control socket. It never sees an
|
|
||||||
// outcome: Render prints those itself, the same way for every command. Leaving it
|
|
||||||
// nil declares that no human rendering of the Value exists yet, which JSONOnly says
|
|
||||||
// up front; Render then refuses text rather than inventing an interim form for
|
|
||||||
// people to script against.
|
|
||||||
Text TextFunc
|
|
||||||
|
|
||||||
// JSONOnly declares that the command's Value has no human rendering yet, so a surface
|
|
||||||
// whose default is text asks for JSON instead, and the schema says so to a client. It
|
|
||||||
// is a statement that no such form exists, not a fallback. A refusal is still
|
|
||||||
// rendered as a sentence, since that always has a human form.
|
|
||||||
JSONOnly bool
|
|
||||||
|
|
||||||
// Then, when set, is the second half of a command that acts: Run says what is about
|
|
||||||
// to happen and Then does it and says how it went, with its Result rendered after
|
|
||||||
// Run's and deciding the outcome. A Run that refused is the outcome, and Then does
|
|
||||||
// not run. It exists for a command whose action can cut off
|
|
||||||
// its own reply: reload restarts the ssh server when the sshd keys changed, which
|
|
||||||
// ends the session that asked, so Run's line has to be on the wire before the reload
|
|
||||||
// begins. A surface that answers in one piece, the control socket, runs Then before
|
|
||||||
// it answers and carries both.
|
|
||||||
Then func() Result
|
|
||||||
}
|
|
||||||
|
|
||||||
// Failure is the error a surface gets for a refusal the person has already been shown:
|
|
||||||
// a Run that returned Failed, a command that is not there, a line that would not parse.
|
|
||||||
// The message it rendered is the whole story, so the surface reports the failure, exit
|
|
||||||
// status 1 over ssh, and does not log it.
|
|
||||||
type Failure struct {
|
|
||||||
Msg string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Failure) Error() string {
|
|
||||||
return f.Msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// commandFlags returns the FlagSet a command is driven through, on any surface: the
|
|
||||||
// command's own flags, if it declares any, with the two presentation flags added. own
|
|
||||||
// reports whether the command declared any of its own, which is what tells a caller
|
|
||||||
// whether to say a parameter is unknown or that the command takes none at all.
|
|
||||||
//
|
|
||||||
// The presentation flags are defined here rather than by each command, because how a
|
|
||||||
// result is displayed is not a property of the command that produced it. This is also
|
|
||||||
// the one definition of them: the ssh line parses into it, nebula ctl parses its line
|
|
||||||
// against the schema derived from it, and help renders from that schema. They are
|
|
||||||
// command line flags only: a socket request chooses its rendering with the envelope's
|
|
||||||
// format field, and Invoke refuses them as parameters.
|
|
||||||
func commandFlags(c *Command) (fl *flag.FlagSet, fs any, own bool) {
|
|
||||||
if c.Flags != nil {
|
|
||||||
fl, fs = c.Flags()
|
|
||||||
}
|
|
||||||
own = fl != nil
|
|
||||||
if fl == nil {
|
|
||||||
fl = flag.NewFlagSet(string(c.Name), flag.ContinueOnError)
|
|
||||||
}
|
|
||||||
|
|
||||||
addPresentationFlags(fl)
|
|
||||||
|
|
||||||
// What Parse prints after a bad flag, and for -h: the command's usage as help renders
|
|
||||||
// it, so a line that went wrong is answered with the same text as `help <command>`.
|
|
||||||
fl.Usage = func() { _ = WriteCommandHelp(schemaOf(c, fl), fl.Output()) }
|
|
||||||
|
|
||||||
return fl, fs, own
|
|
||||||
}
|
|
||||||
|
|
||||||
// addPresentationFlags defines the two presentation flags on fl.
|
|
||||||
func addPresentationFlags(fl *flag.FlagSet) {
|
|
||||||
fl.Bool(FlagJSON, false, "outputs as json")
|
|
||||||
fl.Bool(FlagPretty, false, "pretty prints json, assumes -json")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flagged fills in c's Flags and Run as a pair: define declares the flags on a fresh F,
|
|
||||||
// and run is handed that F. The struct the flags fill is the struct Run reads by
|
|
||||||
// construction, so no Run has to assert the type it was given or decide what to do
|
|
||||||
// when the assertion fails.
|
|
||||||
func Flagged[F any](c *Command, define func(*flag.FlagSet, *F), run func(*F, []string) (Result, error)) *Command {
|
|
||||||
c.Flags = func() (*flag.FlagSet, any) {
|
|
||||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
|
||||||
s := new(F)
|
|
||||||
define(fl, s)
|
|
||||||
return fl, s
|
|
||||||
}
|
|
||||||
c.Run = func(fs any, a []string) (Result, error) {
|
|
||||||
s, ok := fs.(*F)
|
|
||||||
if !ok {
|
|
||||||
return Result{}, fmt.Errorf("%s was handed %T for its flags, not %T", c.Name, fs, s)
|
|
||||||
}
|
|
||||||
return run(s, a)
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// isPresentationFlag reports whether name is one of the two flags commandFlags adds.
|
|
||||||
func isPresentationFlag(name string) bool {
|
|
||||||
return name == FlagJSON || name == FlagPretty
|
|
||||||
}
|
|
||||||
|
|
||||||
// execLine runs an ssh command line against c, reporting problems to w. The line is
|
|
||||||
// parsed into the command's own FlagSet and Run reads it directly, so a flag.Value whose
|
|
||||||
// String does not re-parse, flag.Func above all, arrives as the line said. Invoke fills
|
|
||||||
// the same FlagSet through Set.
|
|
||||||
func (r *Registry) execLine(c *Command, args []string, w Output) error {
|
|
||||||
fl, fs, _ := commandFlags(c)
|
|
||||||
|
|
||||||
// Parse reports a bad flag to this writer, with the command's usage after it. -h,
|
|
||||||
// -help and --help take the same path with nothing wrong: the usage is the whole
|
|
||||||
// answer, and Parse says so with ErrHelp. A -h that is a flag's value or follows --
|
|
||||||
// is read as the operand it is, since ParseArgs is the one reading of the line.
|
|
||||||
fl.SetOutput(w.Err)
|
|
||||||
operands, err := ParseArgs(fl, args)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, flag.ErrHelp) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
format := presentationFormat(fl)
|
|
||||||
|
|
||||||
// An error from Run is something the command could not do rather than a refusal it
|
|
||||||
// chose, but the person at the prompt still hears it; the surface logs it too.
|
|
||||||
res, err := c.Run(fs, operands)
|
|
||||||
if err != nil {
|
|
||||||
_, _ = fmt.Fprintln(w.Err, err.Error())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run's reply goes out first, and then the action, if the command has one and Run
|
|
||||||
// did not refuse, whose Result is the outcome. In JSON only the outcome travels:
|
|
||||||
// the promise is for a person to read, and a program expects one document.
|
|
||||||
if c.Then == nil || !res.OK || r.formatFor(c, res, format) == FormatText {
|
|
||||||
if err := r.renderLine(c, res, format, w); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if c.Then != nil && res.OK {
|
|
||||||
res = c.Then()
|
|
||||||
if err := r.renderLine(c, res, format, w); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !res.OK {
|
|
||||||
return &Failure{Msg: res.Reason}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// formatFor is the format a Result is rendered in. The line wins when it asked for one;
|
|
||||||
// otherwise the surface that owns the registry decides, from the command and its
|
|
||||||
// Result, so each surface can keep its own default.
|
|
||||||
func (r *Registry) formatFor(c *Command, res Result, format Format) Format {
|
|
||||||
if format == FormatUnset {
|
|
||||||
return r.defaultFormatFor(c, res)
|
|
||||||
}
|
|
||||||
return format
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderLine writes one Result of a command line to w; see formatFor. An empty Result
|
|
||||||
// writes nothing.
|
|
||||||
func (r *Registry) renderLine(c *Command, res Result, format Format, w Output) error {
|
|
||||||
if res.Empty() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := Render(c, res, r.formatFor(c, res, format), w.Out); err != nil {
|
|
||||||
if errors.Is(err, ErrNoTextRendering) {
|
|
||||||
_, _ = fmt.Fprintln(w.Err, err.Error())
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseArgs parses args with fl and returns the operands.
|
|
||||||
//
|
|
||||||
// It differs from fl.Parse in two ways, and both surfaces parse through here so a line
|
|
||||||
// means the same typed at an ssh prompt or to nebula ctl.
|
|
||||||
//
|
|
||||||
// Flags and operands may come in any order, which is the one way it differs from
|
|
||||||
// fl.Parse. Parse stops at the first operand, so `print-tunnel 10.0.0.1 -json` would
|
|
||||||
// reach the command with "-json" as a second operand and the flag silently dropped. Here
|
|
||||||
// an operand ends nothing: parsing resumes after it, and only "--" ends the flags, with
|
|
||||||
// everything after it an operand. What counts as a flag is Parse's rule: every argument
|
|
||||||
// that starts with "-", a negative number included, so one that is meant as an operand
|
|
||||||
// goes after "--".
|
|
||||||
func ParseArgs(fl *flag.FlagSet, args []string) ([]string, error) {
|
|
||||||
operands := make([]string, 0, len(args))
|
|
||||||
|
|
||||||
for len(args) > 0 {
|
|
||||||
// Walk the flags the way Parse will, to the first argument it would not read as a
|
|
||||||
// flag: an operand or the terminator. Everything before it is Parse's.
|
|
||||||
end := len(args)
|
|
||||||
for i := 0; i < len(args); {
|
|
||||||
a := args[i]
|
|
||||||
if a == "--" {
|
|
||||||
if err := fl.Parse(args[:i]); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return append(operands, args[i+1:]...), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(a) < 2 || a[0] != '-' {
|
|
||||||
end = i
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
f, hasValue := LookupArg(fl, a)
|
|
||||||
if f == nil {
|
|
||||||
// An undefined flag: leave it for Parse to report.
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if hasValue || IsBoolFlag(f) {
|
|
||||||
i++
|
|
||||||
} else {
|
|
||||||
// The flag's value is the next argument, whatever it looks like.
|
|
||||||
i += 2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := fl.Parse(args[:end]); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if end == len(args) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
operands = append(operands, args[end])
|
|
||||||
args = args[end+1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
return operands, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LookupArg reads arg the way Parse does: one or two leading dashes, the flag's name, and
|
|
||||||
// an optional "=value". f is the flag of fl by that name, nil when fl has none, and
|
|
||||||
// hasValue reports that the value came with the argument rather than in the one after it.
|
|
||||||
// It is the one reading of an argument's shape: ParseArgs walks a line with it, and
|
|
||||||
// nebula ctl lifts its own flags out of a line with it, so the two cannot disagree about
|
|
||||||
// which word is a flag's value.
|
|
||||||
func LookupArg(fl *flag.FlagSet, arg string) (f *flag.Flag, hasValue bool) {
|
|
||||||
name := strings.TrimPrefix(strings.TrimPrefix(arg, "-"), "-")
|
|
||||||
if eq := strings.IndexByte(name, '='); eq >= 0 {
|
|
||||||
name, hasValue = name[:eq], true
|
|
||||||
}
|
|
||||||
return fl.Lookup(name), hasValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsBoolFlag reports whether f is satisfied by its presence alone and never reads the
|
|
||||||
// argument after it as its value. The flag package marks these with an unexported
|
|
||||||
// interface, which is the only way to tell.
|
|
||||||
func IsBoolFlag(f *flag.Flag) bool {
|
|
||||||
bf, ok := f.Value.(interface{ IsBoolFlag() bool })
|
|
||||||
return ok && bf.IsBoolFlag()
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"flag"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestParseArgsAllowsFlagsAfterOperands pins the one way ParseArgs departs from fl.Parse,
|
|
||||||
// that a flag may follow an operand, and that it departs in no other: a negative number
|
|
||||||
// is a flag, as Parse reads it, and goes after "--" when it is meant as an operand.
|
|
||||||
func TestParseArgsAllowsFlagsAfterOperands(t *testing.T) {
|
|
||||||
cases := map[string]struct {
|
|
||||||
args []string
|
|
||||||
wantOps []string
|
|
||||||
wantN string
|
|
||||||
wantV bool
|
|
||||||
wantJSON bool
|
|
||||||
wantErr string
|
|
||||||
}{
|
|
||||||
"flag after operand": {args: []string{"x", "-json"}, wantOps: []string{"x"}, wantJSON: true},
|
|
||||||
"flags around": {args: []string{"-v", "x", "-n", "1", "y"}, wantOps: []string{"x", "y"}, wantV: true, wantN: "1"},
|
|
||||||
"value after operand": {args: []string{"x", "-n", "-1"}, wantOps: []string{"x"}, wantN: "-1"},
|
|
||||||
"equals value": {args: []string{"-n=-1", "x"}, wantOps: []string{"x"}, wantN: "-1"},
|
|
||||||
"terminator after": {args: []string{"x", "--", "-json", "-1"}, wantOps: []string{"x", "-json", "-1"}},
|
|
||||||
"terminator": {args: []string{"--", "-json"}, wantOps: []string{"-json"}},
|
|
||||||
"defined numeric": {args: []string{"-2", "x"}, wantOps: []string{"x"}, wantV: true},
|
|
||||||
"negative number": {args: []string{"-1"}, wantErr: "flag provided but not defined: -1"},
|
|
||||||
"bad flag after": {args: []string{"x", "-nope"}, wantErr: "flag provided but not defined: -nope"},
|
|
||||||
"undefined flag": {args: []string{"-nope", "x"}, wantErr: "flag provided but not defined: -nope"},
|
|
||||||
"missing value": {args: []string{"-n"}, wantErr: "flag needs an argument: -n"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, tc := range cases {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
fl := flag.NewFlagSet("t", flag.ContinueOnError)
|
|
||||||
fl.SetOutput(&bytes.Buffer{})
|
|
||||||
n := fl.String("n", "", "")
|
|
||||||
v := fl.Bool("v", false, "")
|
|
||||||
two := fl.Bool("2", false, "a flag that happens to be a number")
|
|
||||||
asJSON := fl.Bool(FlagJSON, false, "")
|
|
||||||
|
|
||||||
ops, err := ParseArgs(fl, tc.args)
|
|
||||||
if tc.wantErr != "" {
|
|
||||||
require.ErrorContains(t, err, tc.wantErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, tc.wantOps, ops)
|
|
||||||
assert.Equal(t, tc.wantN, *n)
|
|
||||||
assert.Equal(t, tc.wantV, *v || *two)
|
|
||||||
assert.Equal(t, tc.wantJSON, *asJSON)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDispatchFlagAfterOperand: the same through a registered command with no Flags of
|
|
||||||
// its own, which only has the presentation flags to find.
|
|
||||||
func TestDispatchFlagAfterOperand(t *testing.T) {
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, testRegistry().DispatchArgs([]string{"served", "x", "-json"}, MergedOutput(out)))
|
|
||||||
assert.Equal(t, "\"read x\"\n", out.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLookupArg pins the reading of an argument's shape that ParseArgs and nebula ctl
|
|
||||||
// share.
|
|
||||||
func TestLookupArg(t *testing.T) {
|
|
||||||
fl := flag.NewFlagSet("t", flag.ContinueOnError)
|
|
||||||
fl.String("n", "", "")
|
|
||||||
fl.Bool("v", false, "")
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
arg string
|
|
||||||
name string
|
|
||||||
hasValue bool
|
|
||||||
}{
|
|
||||||
{"-n", "n", false},
|
|
||||||
{"--n", "n", false},
|
|
||||||
{"-n=1", "n", true},
|
|
||||||
{"--n=", "n", true},
|
|
||||||
{"-v", "v", false},
|
|
||||||
{"-nope", "", false},
|
|
||||||
{"-1", "", false},
|
|
||||||
} {
|
|
||||||
f, hasValue := LookupArg(fl, tc.arg)
|
|
||||||
if tc.name == "" {
|
|
||||||
assert.Nil(t, f, tc.arg)
|
|
||||||
} else {
|
|
||||||
require.NotNil(t, f, tc.arg)
|
|
||||||
assert.Equal(t, tc.name, f.Name, tc.arg)
|
|
||||||
}
|
|
||||||
assert.Equal(t, tc.hasValue, hasValue, tc.arg)
|
|
||||||
}
|
|
||||||
|
|
||||||
assert.True(t, IsBoolFlag(fl.Lookup("v")))
|
|
||||||
assert.False(t, IsBoolFlag(fl.Lookup("n")))
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
// Name identifies a command. Every command nebula serves is a constant here, so a
|
|
||||||
// surface, a client and a test spell it the same way and are told at compile time when
|
|
||||||
// they do not. It is a string rather than an integer so a test can register a throwaway
|
|
||||||
// command without adding it here, and so the wire carries the name as the string it has
|
|
||||||
// always been.
|
|
||||||
type Name string
|
|
||||||
|
|
||||||
const (
|
|
||||||
ChangeRemote Name = "change-remote"
|
|
||||||
CloseTunnel Name = "close-tunnel"
|
|
||||||
CreateTunnel Name = "create-tunnel"
|
|
||||||
DeviceInfo Name = "device-info"
|
|
||||||
Help Name = "help"
|
|
||||||
Identity Name = "identity"
|
|
||||||
ListHostmap Name = "list-hostmap"
|
|
||||||
ListLighthouseAddrmap Name = "list-lighthouse-addrmap"
|
|
||||||
ListPendingHostmap Name = "list-pending-hostmap"
|
|
||||||
LogFormat Name = "log-format"
|
|
||||||
LogLevel Name = "log-level"
|
|
||||||
Logout Name = "logout"
|
|
||||||
PrintCert Name = "print-cert"
|
|
||||||
PrintRelays Name = "print-relays"
|
|
||||||
PrintTunnel Name = "print-tunnel"
|
|
||||||
QueryLighthouse Name = "query-lighthouse"
|
|
||||||
Reload Name = "reload"
|
|
||||||
Version Name = "version"
|
|
||||||
Whoami Name = "whoami"
|
|
||||||
)
|
|
||||||
@@ -1,456 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"cmp"
|
|
||||||
"errors"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"maps"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/anmitsu/go-shlex"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Registry holds a set of commands.
|
|
||||||
//
|
|
||||||
// It is safe for concurrent use: the ssh server clones it per session and the control
|
|
||||||
// socket serves it as it is, while the daemon fills it once at startup.
|
|
||||||
type Registry struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
commands map[Name]*Command
|
|
||||||
|
|
||||||
// full is set on a filtered registry and points at the registry it was filtered
|
|
||||||
// from, so a command that's filtered can be reported as such.
|
|
||||||
full *Registry
|
|
||||||
|
|
||||||
// reason explains, in the terms an operator cares about, why this registry withholds
|
|
||||||
// a command they can name. It is supplied by whoever built the filter, because why a
|
|
||||||
// surface declines a command is that surface's business, not the registry's.
|
|
||||||
reason string
|
|
||||||
|
|
||||||
// DefaultFormat decides how a result is rendered when the command line named no
|
|
||||||
// format. It sees the command and its Result, and applies to values and refusals
|
|
||||||
// alike: the registry does not special-case either. The renderer is shared between
|
|
||||||
// surfaces; what each asks for by default is not, so the surface that owns this
|
|
||||||
// registry sets it. Nil means text.
|
|
||||||
DefaultFormat func(c *Command, r Result) Format
|
|
||||||
}
|
|
||||||
|
|
||||||
// defaultFormatFor resolves the surface's default for c's Result.
|
|
||||||
func (r *Registry) defaultFormatFor(c *Command, res Result) Format {
|
|
||||||
if r.DefaultFormat == nil {
|
|
||||||
return FormatText
|
|
||||||
}
|
|
||||||
return r.DefaultFormat(c, res)
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns an empty Registry with only `help` available.
|
|
||||||
func New() *Registry {
|
|
||||||
r := &Registry{commands: map[Name]*Command{}}
|
|
||||||
r.registerHelp()
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) registerHelp() {
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: Help,
|
|
||||||
ShortDescription: "prints available commands or help <command> for specific usage info",
|
|
||||||
Run: func(a any, args []string) (Result, error) {
|
|
||||||
if len(args) == 0 {
|
|
||||||
return Value(r.Schema()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err := r.Resolve(Name(args[0]))
|
|
||||||
if err != nil {
|
|
||||||
var withheld *WithheldError
|
|
||||||
if errors.As(err, &withheld) {
|
|
||||||
return Failed("%s", err), nil
|
|
||||||
}
|
|
||||||
return Failed("Command not available %s", args[0]), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return Value(r.SchemaFor(c)), nil
|
|
||||||
},
|
|
||||||
Text: renderHelp,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderHelp is help's human rendering: the command list, or one command's usage.
|
|
||||||
func renderHelp(v any, w io.Writer) error {
|
|
||||||
switch h := v.(type) {
|
|
||||||
case []CommandSchema:
|
|
||||||
return writeCommandList(h, w)
|
|
||||||
case CommandSchema:
|
|
||||||
return WriteCommandHelp(h, w)
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("expected a command schema, got %T", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeCommandList(cmds []CommandSchema, w io.Writer) error {
|
|
||||||
if _, err := io.WriteString(w, "Available commands:\n"); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// In the order the schema came, which is the display order; see Registry.All.
|
|
||||||
lines := make([]string, 0, len(cmds))
|
|
||||||
for _, c := range cmds {
|
|
||||||
lines = append(lines, fmt.Sprintf("%s - %s", c.Name, c.Short))
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := io.WriteString(w, strings.Join(lines, "\n")+"\n\n")
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteCommandHelp renders one command's usage. It is the single rendering of a
|
|
||||||
// CommandSchema for a person: the daemon uses it for `help <command>` on both surfaces,
|
|
||||||
// and a client that already holds the schema uses it for `-h`, so the two cannot drift.
|
|
||||||
func WriteCommandHelp(c CommandSchema, w io.Writer) error {
|
|
||||||
if _, err := fmt.Fprintf(w, "%s - %s\n", c.Name, c.Short); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Help != "" {
|
|
||||||
if _, err := fmt.Fprintf(w, " %s\n", c.Help); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Same layout as flag.PrintDefaults, including its habit of leaving out a default
|
|
||||||
// that is the zero value.
|
|
||||||
for _, f := range c.Flags {
|
|
||||||
kind := ""
|
|
||||||
if !f.Bool {
|
|
||||||
kind = " string"
|
|
||||||
}
|
|
||||||
def := ""
|
|
||||||
if f.Default != "" && f.Default != "false" {
|
|
||||||
def = fmt.Sprintf(" (default %s)", f.Default)
|
|
||||||
}
|
|
||||||
if _, err := fmt.Fprintf(w, " -%s%s\n \t%s%s\n", f.Name, kind, f.Usage, def); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Register adds a command that can be run by a user.
|
|
||||||
//
|
|
||||||
// It panics if the command declares a reserved flag. That is a programming error, and
|
|
||||||
// surfacing it here, at startup, is better than at the moment an operator first types
|
|
||||||
// the command.
|
|
||||||
func (r *Registry) Register(c *Command) {
|
|
||||||
if c.Run == nil {
|
|
||||||
panic(fmt.Sprintf("commands: %s has no Run", c.Name))
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Flags != nil {
|
|
||||||
if fl, _ := c.Flags(); fl != nil {
|
|
||||||
for _, name := range reservedFlags {
|
|
||||||
if fl.Lookup(name) != nil {
|
|
||||||
panic(fmt.Sprintf("commands: %s declares reserved flag -%s", c.Name, name))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
r.insert(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// insert adds c without the reserved flag check, for commands that have already passed
|
|
||||||
// it on another registry.
|
|
||||||
func (r *Registry) insert(c *Command) {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
r.commands[c.Name] = c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns the command registered under name, or nil if there is no such command.
|
|
||||||
func (r *Registry) Get(name Name) *Command {
|
|
||||||
r.mu.RLock()
|
|
||||||
defer r.mu.RUnlock()
|
|
||||||
return r.commands[name]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Match returns the names of every command starting with prefix, sorted, as strings for
|
|
||||||
// a prompt to complete and print.
|
|
||||||
func (r *Registry) Match(prefix string) []string {
|
|
||||||
cmds := make([]string, 0)
|
|
||||||
r.mu.RLock()
|
|
||||||
for n := range r.commands {
|
|
||||||
if strings.HasPrefix(string(n), prefix) {
|
|
||||||
cmds = append(cmds, string(n))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
r.mu.RUnlock()
|
|
||||||
slices.Sort(cmds)
|
|
||||||
return cmds
|
|
||||||
}
|
|
||||||
|
|
||||||
// All returns every registered command sorted by name, which is the order help lists
|
|
||||||
// them and the schema describes them.
|
|
||||||
func (r *Registry) All() []*Command {
|
|
||||||
r.mu.RLock()
|
|
||||||
defer r.mu.RUnlock()
|
|
||||||
|
|
||||||
cmds := slices.Collect(maps.Values(r.commands))
|
|
||||||
slices.SortFunc(cmds, func(a, b *Command) int { return cmp.Compare(a.Name, b.Name) })
|
|
||||||
return cmds
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clone returns a copy holding the same commands.
|
|
||||||
//
|
|
||||||
// help is re-registered on the copy rather than carried over, because the source's help
|
|
||||||
// is bound to the source and would list its commands, not the copy's, once a caller
|
|
||||||
// registers something on the copy.
|
|
||||||
func (r *Registry) Clone() *Registry {
|
|
||||||
r.mu.RLock()
|
|
||||||
out := &Registry{
|
|
||||||
commands: maps.Clone(r.commands),
|
|
||||||
full: r.full,
|
|
||||||
reason: r.reason,
|
|
||||||
DefaultFormat: r.DefaultFormat,
|
|
||||||
}
|
|
||||||
r.mu.RUnlock()
|
|
||||||
|
|
||||||
out.registerHelp()
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter returns a filtered copy of the registry.
|
|
||||||
//
|
|
||||||
// Keep should return true for commands that should be included in the copy. reason
|
|
||||||
// says, to an operator who names a command the copy left out, why this surface does
|
|
||||||
// not serve it; "" leaves the registry to say only that it does not.
|
|
||||||
func (r *Registry) Filter(keep func(*Command) bool, reason string) *Registry {
|
|
||||||
out := &Registry{commands: map[Name]*Command{}, full: r, reason: reason, DefaultFormat: r.DefaultFormat}
|
|
||||||
|
|
||||||
for _, cmd := range r.All() {
|
|
||||||
if keep(cmd) {
|
|
||||||
out.insert(cmd)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bind help to the filtered set so it only advertises what this surface serves.
|
|
||||||
out.registerHelp()
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dispatch parses a command line and runs it, reporting problems to w. The error is for
|
|
||||||
// the caller to log, not to show; see RunFunc and Failure.
|
|
||||||
func (r *Registry) Dispatch(line string, w Output) error {
|
|
||||||
// A line shlex cannot split, an unbalanced quote. Reported on Err so the output
|
|
||||||
// stream stays parseable.
|
|
||||||
args, err := shlex.Split(line, true)
|
|
||||||
if err != nil {
|
|
||||||
msg := "could not parse the command line: " + err.Error()
|
|
||||||
if _, err := fmt.Fprintln(w.Err, msg); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return &Failure{Msg: msg}
|
|
||||||
}
|
|
||||||
|
|
||||||
return r.DispatchArgs(args, w)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DispatchArgs runs an already tokenized command line. The error is as for Dispatch.
|
|
||||||
//
|
|
||||||
// An empty line and an unknown command both end up running `help`, the first with the
|
|
||||||
// arguments help itself would take; `<command> -h` is answered by the command's own
|
|
||||||
// FlagSet, with the same rendering, in execLine.
|
|
||||||
func (r *Registry) DispatchArgs(args []string, w Output) error {
|
|
||||||
if len(args) == 0 {
|
|
||||||
args = []string{"help"}
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err := r.Resolve(Name(args[0]))
|
|
||||||
if err != nil {
|
|
||||||
var withheld *WithheldError
|
|
||||||
if errors.As(err, &withheld) {
|
|
||||||
// Saying why, rather than "did not understand", keeps the rule legible and
|
|
||||||
// points at a surface that will actually run the command.
|
|
||||||
_, _ = fmt.Fprintln(w.Err, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only the first word was looked up, so only it is named.
|
|
||||||
msg := fmt.Sprintf("did not understand: %s", args[0])
|
|
||||||
if _, err := fmt.Fprintln(w.Out, msg); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := r.DispatchArgs([]string{"help"}, w); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return &Failure{Msg: msg}
|
|
||||||
}
|
|
||||||
|
|
||||||
return r.execLine(c, args[1:], w)
|
|
||||||
}
|
|
||||||
|
|
||||||
// unavailable explains why name cannot be run here when this registry was filtered from
|
|
||||||
// one that holds it: the command exists, and this surface withholds it, for the reason
|
|
||||||
// whoever built the filter gave. It is nil when name is simply unknown, so the two cases
|
|
||||||
// read differently to an operator.
|
|
||||||
func (r *Registry) unavailable(name Name) error {
|
|
||||||
if r.full == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
c := r.full.Get(name)
|
|
||||||
if c == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
reason := r.reason
|
|
||||||
if reason == "" {
|
|
||||||
reason = "this surface does not serve it"
|
|
||||||
}
|
|
||||||
|
|
||||||
return &WithheldError{msg: fmt.Sprintf("%s is not available on this surface: %s", c.Name, reason)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithheldError indicates that the command is supported by Nebula, but not via this path.
|
|
||||||
type WithheldError struct {
|
|
||||||
msg string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *WithheldError) Error() string { return e.msg }
|
|
||||||
|
|
||||||
// Resolve returns the command registered under name, or says why there is none: a
|
|
||||||
// WithheldError with the filter's reason, or unknown for a name that does not exist.
|
|
||||||
func (r *Registry) Resolve(name Name) (*Command, error) {
|
|
||||||
if c := r.Get(name); c != nil {
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := r.unavailable(name); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("unknown command %q", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParamError is what Invoke returns for a parameter the command would not take: one it
|
|
||||||
// does not have, or a value its flag would not parse. It is the caller's mistake rather
|
|
||||||
// than the command's failure, and a surface with status codes tells the two apart by
|
|
||||||
// it; every other error from Invoke came out of Run.
|
|
||||||
type ParamError struct {
|
|
||||||
msg string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *ParamError) Error() string { return e.msg }
|
|
||||||
|
|
||||||
func paramErrorf(format string, args ...any) error {
|
|
||||||
return &ParamError{msg: fmt.Sprintf(format, args...)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// setParams sets each named parameter on fl, in the order of names, and stops at the
|
|
||||||
// first that is unknown or does not parse. own says whether the command declared flags
|
|
||||||
// of its own, which decides between "takes no parameters" and "has no parameter".
|
|
||||||
//
|
|
||||||
// The presentation flags are on fl, since commandFlags put them there, but they are not
|
|
||||||
// parameters: a request has one place to choose its rendering, the envelope's format
|
|
||||||
// field, and a client that sends them here is told where that is rather than having a
|
|
||||||
// second, weaker way to say the same thing.
|
|
||||||
func setParams(fl *flag.FlagSet, name string, names []string, params map[string]string, own bool) error {
|
|
||||||
for _, k := range names {
|
|
||||||
if isPresentationFlag(k) {
|
|
||||||
return paramErrorf("%s is a command line flag, not a parameter; choose the rendering with the request's format field", k)
|
|
||||||
}
|
|
||||||
|
|
||||||
f := fl.Lookup(k)
|
|
||||||
if f == nil {
|
|
||||||
if !own {
|
|
||||||
return paramErrorf("%s takes no parameters", name)
|
|
||||||
}
|
|
||||||
return paramErrorf("%s has no parameter %q", name, k)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := setFlag(fl, f, params[k]); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// setFlag applies one value to f, reporting a refusal as a ParamError in words that
|
|
||||||
// name the value: the flag package's own words for a bad boolean are "parse error".
|
|
||||||
func setFlag(fl *flag.FlagSet, f *flag.Flag, v string) error {
|
|
||||||
if err := fl.Set(f.Name, v); err != nil {
|
|
||||||
if IsBoolFlag(f) {
|
|
||||||
return paramErrorf("%s: expected a boolean, got %q", f.Name, v)
|
|
||||||
}
|
|
||||||
return paramErrorf("%s: %v", f.Name, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Schema describes every command in the registry, so a client can offer them without
|
|
||||||
// having been built against this daemon.
|
|
||||||
func (r *Registry) Schema() []CommandSchema {
|
|
||||||
all := r.All()
|
|
||||||
out := make([]CommandSchema, 0, len(all))
|
|
||||||
for _, c := range all {
|
|
||||||
out = append(out, r.SchemaFor(c))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaFor describes one command. It is the one derivation, for the whole schema and
|
|
||||||
// for `help <command>` alike.
|
|
||||||
func (r *Registry) SchemaFor(c *Command) CommandSchema {
|
|
||||||
fl, _, _ := commandFlags(c)
|
|
||||||
return schemaOf(c, fl)
|
|
||||||
}
|
|
||||||
|
|
||||||
// schemaOf describes c as driven through fl, the FlagSet commandFlags built for it. The
|
|
||||||
// presentation flags are included because a command line client parses its line
|
|
||||||
// against this and help renders from it; they are listed after the command's own,
|
|
||||||
// which is where readers expect them. Invoke refuses them as parameters.
|
|
||||||
func schemaOf(c *Command, fl *flag.FlagSet) CommandSchema {
|
|
||||||
cs := CommandSchema{Name: c.Name, Short: c.ShortDescription, Help: c.Help}
|
|
||||||
|
|
||||||
var own, shared []FlagSchema
|
|
||||||
fl.VisitAll(func(f *flag.Flag) {
|
|
||||||
fs := FlagSchema{
|
|
||||||
Name: f.Name,
|
|
||||||
Bool: IsBoolFlag(f),
|
|
||||||
Default: f.DefValue,
|
|
||||||
Usage: f.Usage,
|
|
||||||
}
|
|
||||||
if isPresentationFlag(f.Name) {
|
|
||||||
shared = append(shared, fs)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
own = append(own, fs)
|
|
||||||
})
|
|
||||||
cs.Flags = append(own, shared...)
|
|
||||||
|
|
||||||
return cs
|
|
||||||
}
|
|
||||||
|
|
||||||
// CommandSchema describes one command well enough for a client to offer it.
|
|
||||||
type CommandSchema struct {
|
|
||||||
Name Name `json:"name"`
|
|
||||||
Short string `json:"short,omitempty"`
|
|
||||||
Help string `json:"help,omitempty"`
|
|
||||||
Flags []FlagSchema `json:"flags,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// FlagSchema describes one of a command's named parameters.
|
|
||||||
type FlagSchema struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
|
|
||||||
// Bool reports a parameter that takes no value, which is what tells a command line
|
|
||||||
// client whether `-pretty` swallows the word after it.
|
|
||||||
Bool bool `json:"bool,omitempty"`
|
|
||||||
|
|
||||||
Default string `json:"default,omitempty"`
|
|
||||||
Usage string `json:"usage,omitempty"`
|
|
||||||
}
|
|
||||||
@@ -1,481 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
"flag"
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// notWithheld is a stand in for a surface's own policy, which the registry knows nothing
|
|
||||||
// of; see Command.Identity for the one the info API applies.
|
|
||||||
func notWithheld(c *Command) bool { return c.Name != "withheld" }
|
|
||||||
|
|
||||||
const testReason = "this surface does not run commands that write"
|
|
||||||
|
|
||||||
// textLine is a Text renderer for test commands whose result is one string.
|
|
||||||
func textLine(v any, w io.Writer) error {
|
|
||||||
_, err := io.WriteString(w, v.(string)+"\n")
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func testRegistry() *Registry {
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "served",
|
|
||||||
ShortDescription: "a command this surface serves",
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
return Value("read " + strings.Join(a, ",")), nil
|
|
||||||
},
|
|
||||||
Text: textLine,
|
|
||||||
})
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "withheld",
|
|
||||||
ShortDescription: "a command this surface withholds",
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
return Value("wrote"), nil
|
|
||||||
},
|
|
||||||
Text: textLine,
|
|
||||||
})
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFilterKeepsWhatKeepSays: the copy holds the commands keep accepted, and help.
|
|
||||||
func TestFilterKeepsWhatKeepSays(t *testing.T) {
|
|
||||||
ro := testRegistry().Filter(notWithheld, testReason)
|
|
||||||
|
|
||||||
names := make([]string, 0)
|
|
||||||
for _, c := range ro.All() {
|
|
||||||
names = append(names, string(c.Name))
|
|
||||||
}
|
|
||||||
|
|
||||||
assert.ElementsMatch(t, []string{"help", "served"}, names)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRefusesWithheldByName covers a client that knows a command exists and asks for it
|
|
||||||
// anyway. The filter lives on the serving side, so the answer must not depend on what
|
|
||||||
// the client was told was available.
|
|
||||||
func TestRefusesWithheldByName(t *testing.T) {
|
|
||||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
|
||||||
w := Output{Out: out, Err: errOut}
|
|
||||||
|
|
||||||
err := testRegistry().Filter(notWithheld, testReason).DispatchArgs([]string{"withheld"}, w)
|
|
||||||
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.Contains(t, err.Error(), "withheld is not available on this surface")
|
|
||||||
assert.Empty(t, out.String(), "a withheld command must produce no output")
|
|
||||||
assert.Contains(t, errOut.String(), "withheld is not available on this surface")
|
|
||||||
assert.Contains(t, errOut.String(), testReason,
|
|
||||||
"the registry should render the explanation the filter supplied, not one of its own")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestWithheldIsNotReportedAsUnknown keeps the two cases distinct: an operator who
|
|
||||||
// mistypes and one who asked for a real command should not get the same answer.
|
|
||||||
func TestWithheldIsNotReportedAsUnknown(t *testing.T) {
|
|
||||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
|
||||||
err := testRegistry().Filter(notWithheld, testReason).DispatchArgs([]string{"no-such-command"}, Output{Out: out, Err: errOut})
|
|
||||||
|
|
||||||
var f *Failure
|
|
||||||
require.ErrorAs(t, err, &f, "an unknown command is a failure to the surface")
|
|
||||||
assert.Contains(t, out.String(), "did not understand: no-such-command")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestResolveTellsUnknownFromWithheld: the two cases read differently to an operator,
|
|
||||||
// and a surface with status codes tells them apart by the error's type, never by asking
|
|
||||||
// the unfiltered registry, which is the one thing a filtered surface must not consult.
|
|
||||||
func TestResolveTellsUnknownFromWithheld(t *testing.T) {
|
|
||||||
r := testRegistry().Filter(notWithheld, testReason)
|
|
||||||
|
|
||||||
c, err := r.Resolve("served")
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, Name("served"), c.Name)
|
|
||||||
|
|
||||||
_, err = r.Resolve("withheld")
|
|
||||||
var withheld *WithheldError
|
|
||||||
require.ErrorAs(t, err, &withheld)
|
|
||||||
require.ErrorContains(t, err, "withheld is not available on this surface")
|
|
||||||
require.ErrorContains(t, err, testReason)
|
|
||||||
|
|
||||||
_, err = r.Resolve("no-such-command")
|
|
||||||
require.ErrorContains(t, err, `unknown command "no-such-command"`)
|
|
||||||
assert.NotErrorAs(t, err, &withheld, "an unknown name is not a withheld one")
|
|
||||||
}
|
|
||||||
|
|
||||||
// paramRegistry holds one command with a bool flag and a duration flag, and reports what
|
|
||||||
// the command saw when it ran.
|
|
||||||
func paramRegistry(t *testing.T) (*Registry, *[]paramsSeen) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var seen []paramsSeen
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "set",
|
|
||||||
ShortDescription: "sets things",
|
|
||||||
Flags: func() (*flag.FlagSet, any) {
|
|
||||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
|
||||||
s := paramsSeen{}
|
|
||||||
fl.BoolVar(&s.Verbose, "verbose", false, "say more")
|
|
||||||
fl.DurationVar(&s.Wait, "wait", 0, "how long")
|
|
||||||
return fl, &s
|
|
||||||
},
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
seen = append(seen, *fs.(*paramsSeen))
|
|
||||||
return Value("ok"), nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return r, &seen
|
|
||||||
}
|
|
||||||
|
|
||||||
type paramsSeen struct {
|
|
||||||
Verbose bool
|
|
||||||
Wait time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestInvokeReportsParametersInNameOrder: parameters arrive as an unordered object, so
|
|
||||||
// with two bad ones the error must not depend on map iteration. Name order decides.
|
|
||||||
func TestInvokeReportsParametersInNameOrder(t *testing.T) {
|
|
||||||
r, _ := paramRegistry(t)
|
|
||||||
|
|
||||||
cases := map[string]struct {
|
|
||||||
params map[string]string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
"two unknown": {map[string]string{"zed": "1", "alpha": "1"}, `set has no parameter "alpha"`},
|
|
||||||
"unknown before bad bool": {map[string]string{"aaa": "1", "verbose": "maybe"}, `set has no parameter "aaa"`},
|
|
||||||
"bad bool before unknown": {map[string]string{"verbose": "maybe", "zzz": "1"}, `verbose: expected a boolean, got "maybe"`},
|
|
||||||
"bad value before bad bool": {map[string]string{"wait": "soon", "verbose": "maybe"}, `verbose: expected a boolean`},
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, tc := range cases {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
// Enough runs that a map-order dependence would show.
|
|
||||||
for i := 0; i < 50; i++ {
|
|
||||||
_, err := Invoke(Request{Command: r.Get("set"), Params: tc.params})
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.ErrorContains(t, err, tc.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestInvokeWithABadParameterSetsNothing: a request with any bad parameter must not run
|
|
||||||
// the command, and must leave nothing behind for the next request to see. The good
|
|
||||||
// parameter sorts before the bad one, so a one-pass Invoke would have applied it.
|
|
||||||
func TestInvokeWithABadParameterSetsNothing(t *testing.T) {
|
|
||||||
r, seen := paramRegistry(t)
|
|
||||||
|
|
||||||
_, err := Invoke(Request{Command: r.Get("set"), Params: map[string]string{"verbose": "true", "wait": "soon"}})
|
|
||||||
require.ErrorContains(t, err, "wait:")
|
|
||||||
assert.Empty(t, *seen, "the command must not run with a partial parameter set")
|
|
||||||
|
|
||||||
v, err := Invoke(Request{Command: r.Get("set")})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, "ok", v.Value)
|
|
||||||
require.Len(t, *seen, 1)
|
|
||||||
assert.Equal(t, paramsSeen{}, (*seen)[0], "nothing from the failed request carried over")
|
|
||||||
|
|
||||||
_, err = Invoke(Request{Command: r.Get("set"), Params: map[string]string{"verbose": "true", "wait": "2s"}})
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, *seen, 2)
|
|
||||||
assert.Equal(t, paramsSeen{Verbose: true, Wait: 2 * time.Second}, (*seen)[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHelpListsOnlyServedCommands(t *testing.T) {
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, testRegistry().Filter(notWithheld, testReason).DispatchArgs(nil, MergedOutput(out)))
|
|
||||||
|
|
||||||
assert.Contains(t, out.String(), "served")
|
|
||||||
assert.NotContains(t, out.String(), "withheld")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDispatchReportsUnparseableLine pins that a line shlex rejects says so on Err rather
|
|
||||||
// than coming back silent, so an operator with an unbalanced quote learns the quote is the
|
|
||||||
// problem instead of assuming the command is broken.
|
|
||||||
func TestDispatchReportsUnparseableLine(t *testing.T) {
|
|
||||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
|
||||||
testRegistry().Dispatch(`served "unterminated`, Output{Out: out, Err: errOut})
|
|
||||||
assert.Empty(t, out.String())
|
|
||||||
assert.Contains(t, errOut.String(), "could not parse the command line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRegisterRejectsReservedFlags: a command that declares a reserved flag is refused
|
|
||||||
// at Register rather than when an operator first runs it; see reservedFlags.
|
|
||||||
func TestRegisterRejectsReservedFlags(t *testing.T) {
|
|
||||||
for _, name := range []string{"json", "pretty", "h", "help", "config", "socket"} {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
r := New()
|
|
||||||
assert.PanicsWithValue(t, "commands: clash declares reserved flag -"+name, func() {
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "clash",
|
|
||||||
Flags: func() (*flag.FlagSet, any) {
|
|
||||||
fl := flag.NewFlagSet("clash", flag.ContinueOnError)
|
|
||||||
fl.Bool(name, false, "")
|
|
||||||
return fl, nil
|
|
||||||
},
|
|
||||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRegistryIsSafeForConcurrentUse runs the operations the surfaces perform, filtering
|
|
||||||
// and cloning per request or session, against a stream of registrations. It exists to
|
|
||||||
// be run under the race detector: the map underneath is not goroutine safe.
|
|
||||||
func TestRegistryIsSafeForConcurrentUse(t *testing.T) {
|
|
||||||
r := testRegistry()
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < 8; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func(i int) {
|
|
||||||
defer wg.Done()
|
|
||||||
for j := 0; j < 50; j++ {
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: Name("late-" + strings.Repeat("a", i) + "-" + strings.Repeat("b", j)),
|
|
||||||
ShortDescription: "registered after the surfaces started",
|
|
||||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}(i)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < 8; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
for j := 0; j < 50; j++ {
|
|
||||||
f := r.Filter(notWithheld, testReason)
|
|
||||||
_ = f.Get("served")
|
|
||||||
_ = f.Schema()
|
|
||||||
_ = r.Clone().Match("late-")
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
f := r.Filter(notWithheld, testReason)
|
|
||||||
assert.Len(t, f.Match("late-"), 8*50, "every late registration is visible once the writers finish")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestCloneHelpSeesCloneCommands: the ssh session registers logout on its clone, and
|
|
||||||
// the source does not learn of it. Help on the clone answers for the clone, and -h on a
|
|
||||||
// command prints what `help <name>` does, on a clone as on the source: both render
|
|
||||||
// through WriteCommandHelp, and Clone rebinds help to the copy.
|
|
||||||
func TestCloneHelpSeesCloneCommands(t *testing.T) {
|
|
||||||
r := testRegistry()
|
|
||||||
c := r.Clone()
|
|
||||||
c.Register(&Command{
|
|
||||||
Name: Logout,
|
|
||||||
ShortDescription: "ends the session",
|
|
||||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
|
||||||
})
|
|
||||||
assert.Nil(t, r.Get(Logout), "the source is not affected")
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, c.DispatchArgs([]string{"help"}, MergedOutput(out)))
|
|
||||||
assert.Contains(t, out.String(), "logout")
|
|
||||||
|
|
||||||
for _, name := range []string{"logout", "served"} {
|
|
||||||
flag := &bytes.Buffer{}
|
|
||||||
c.Dispatch(name+" -h", MergedOutput(flag))
|
|
||||||
cmd := &bytes.Buffer{}
|
|
||||||
c.Dispatch("help "+name, MergedOutput(cmd))
|
|
||||||
assert.Equal(t, cmd.String(), flag.String(), name)
|
|
||||||
assert.Contains(t, flag.String(), name+" - ", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestThenRunsAfterTheReply pins the order Then exists for: Run's line is on the writer
|
|
||||||
// before the action begins, Then's Result follows it, and Then's outcome is the
|
|
||||||
// command's.
|
|
||||||
func TestThenRunsAfterTheReply(t *testing.T) {
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
seen := "never ran"
|
|
||||||
outcome := Did("acted")
|
|
||||||
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "act",
|
|
||||||
ShortDescription: "replies, then acts",
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
return Did("about to act"), nil
|
|
||||||
},
|
|
||||||
Then: func() Result {
|
|
||||||
seen = out.String()
|
|
||||||
return outcome
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
require.NoError(t, r.DispatchArgs([]string{"act"}, MergedOutput(out)))
|
|
||||||
assert.Equal(t, "about to act\n", seen, "the line was written before the action")
|
|
||||||
assert.Equal(t, "about to act\nacted\n", out.String())
|
|
||||||
|
|
||||||
out.Reset()
|
|
||||||
outcome = Failed("could not act")
|
|
||||||
var f *Failure
|
|
||||||
require.ErrorAs(t, r.DispatchArgs([]string{"act"}, MergedOutput(out)), &f)
|
|
||||||
assert.Equal(t, "about to act\ncould not act\n", out.String())
|
|
||||||
|
|
||||||
// In JSON only the outcome travels: one document for the program that asked.
|
|
||||||
out.Reset()
|
|
||||||
require.ErrorAs(t, r.DispatchArgs([]string{"act", "-json"}, MergedOutput(out)), &f)
|
|
||||||
assert.JSONEq(t, `{"ok":false,"reason":"could not act"}`, out.String())
|
|
||||||
|
|
||||||
// A Run that refused is the outcome; the action does not happen.
|
|
||||||
ran := false
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "refuse",
|
|
||||||
ShortDescription: "refuses, so never acts",
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
return Failed("not like that"), nil
|
|
||||||
},
|
|
||||||
Then: func() Result {
|
|
||||||
ran = true
|
|
||||||
return Did("acted anyway")
|
|
||||||
},
|
|
||||||
})
|
|
||||||
out.Reset()
|
|
||||||
require.ErrorAs(t, r.DispatchArgs([]string{"refuse"}, MergedOutput(out)), &f)
|
|
||||||
assert.Equal(t, "not like that\n", out.String())
|
|
||||||
assert.False(t, ran)
|
|
||||||
out.Reset()
|
|
||||||
require.ErrorAs(t, r.DispatchArgs([]string{"refuse", "-json"}, MergedOutput(out)), &f)
|
|
||||||
assert.JSONEq(t, `{"ok":false,"reason":"not like that"}`, out.String())
|
|
||||||
assert.False(t, ran)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestWriteCommandHelpIsTheOneRendering pins the layout both `help <command>` on the
|
|
||||||
// daemon and `-h` in the client print, so the two cannot drift apart again.
|
|
||||||
func TestWriteCommandHelpIsTheOneRendering(t *testing.T) {
|
|
||||||
cs := CommandSchema{
|
|
||||||
Name: "change-remote",
|
|
||||||
Short: "changes a remote",
|
|
||||||
Help: "Give it an address.",
|
|
||||||
Flags: []FlagSchema{
|
|
||||||
{Name: "address", Usage: "the new remote", Default: "1.2.3.4:4242"},
|
|
||||||
{Name: "by-index", Bool: true, Usage: "match by index"},
|
|
||||||
{Name: "json", Bool: true, Usage: "outputs as json"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, WriteCommandHelp(cs, out))
|
|
||||||
|
|
||||||
assert.Equal(t, "change-remote - changes a remote\n"+
|
|
||||||
" Give it an address.\n"+
|
|
||||||
" -address string\n \tthe new remote (default 1.2.3.4:4242)\n"+
|
|
||||||
" -by-index\n \tmatch by index\n"+
|
|
||||||
" -json\n \toutputs as json\n", out.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// addrFlags is the flag struct of a test command that takes -address.
|
|
||||||
type addrFlags struct{ Address string }
|
|
||||||
|
|
||||||
// TestHelpFlagIsReadWhereParseReadsIt: -h asks for help only where the line's parser
|
|
||||||
// reads it as a flag. As a flag's value or after -- it reaches the command as the
|
|
||||||
// operand it is, and help is rendered by the same function `help <command>` uses.
|
|
||||||
func TestHelpFlagIsReadWhereParseReadsIt(t *testing.T) {
|
|
||||||
var seen []string
|
|
||||||
r := New()
|
|
||||||
r.Register(Flagged(&Command{Name: "x", ShortDescription: "takes an address"},
|
|
||||||
func(fl *flag.FlagSet, s *addrFlags) { fl.StringVar(&s.Address, "address", "", "an address") },
|
|
||||||
func(s *addrFlags, a []string) (Result, error) {
|
|
||||||
seen = append(seen, s.Address+"|"+strings.Join(a, ","))
|
|
||||||
return Nothing(), nil
|
|
||||||
}))
|
|
||||||
|
|
||||||
for _, line := range []string{"x -h", "x -help", "x --help", "x 10.0.0.1 -h", "x -address=1 -h"} {
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
r.Dispatch(line, MergedOutput(out))
|
|
||||||
assert.Contains(t, out.String(), "x - takes an address\n", line)
|
|
||||||
assert.Contains(t, out.String(), "-address string", line)
|
|
||||||
}
|
|
||||||
assert.Empty(t, seen, "asking for help must not run the command")
|
|
||||||
|
|
||||||
for _, line := range []string{"x -address -h", "x -- -h"} {
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
r.Dispatch(line, MergedOutput(out))
|
|
||||||
assert.Empty(t, out.String(), line)
|
|
||||||
}
|
|
||||||
assert.Equal(t, []string{"-h|", "|-h"}, seen)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestBadFlagIsAnsweredWithTheCommandsHelp: a flag the command does not have is reported
|
|
||||||
// on the error stream followed by the command's usage, in the rendering help uses.
|
|
||||||
func TestBadFlagIsAnsweredWithTheCommandsHelp(t *testing.T) {
|
|
||||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{Name: "x", ShortDescription: "has no flags", Run: func(fs any, a []string) (Result, error) { return Nothing(), nil }})
|
|
||||||
|
|
||||||
require.Error(t, r.DispatchArgs([]string{"x", "-nope"}, Output{Out: out, Err: errOut}))
|
|
||||||
assert.Empty(t, out.String())
|
|
||||||
assert.Equal(t, "flag provided but not defined: -nope\nx - has no flags\n -json\n \toutputs as json\n -pretty\n \tpretty prints json, assumes -json\n", errOut.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParameterMistakesAreParamErrors: a surface with status codes needs to tell a
|
|
||||||
// parameter the caller got wrong from a command that failed, and Invoke says which by
|
|
||||||
// the error's type rather than its words.
|
|
||||||
func TestParameterMistakesAreParamErrors(t *testing.T) {
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "flagged",
|
|
||||||
Flags: func() (*flag.FlagSet, any) {
|
|
||||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
|
||||||
s := struct{ N int }{}
|
|
||||||
fl.IntVar(&s.N, "n", 0, "")
|
|
||||||
return fl, &s
|
|
||||||
},
|
|
||||||
Run: func(fs any, a []string) (Result, error) { return Result{}, errors.New("ran and failed") },
|
|
||||||
})
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "bare",
|
|
||||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
|
||||||
})
|
|
||||||
|
|
||||||
var pe *ParamError
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
params map[string]string
|
|
||||||
}{
|
|
||||||
{"flagged", map[string]string{"nope": "1"}},
|
|
||||||
{"flagged", map[string]string{"n": "x"}},
|
|
||||||
{"flagged", map[string]string{FlagJSON: "true"}},
|
|
||||||
{"bare", map[string]string{"n": "1"}},
|
|
||||||
} {
|
|
||||||
_, err := Invoke(Request{Command: r.Get(Name(tc.name)), Params: tc.params})
|
|
||||||
require.Error(t, err, "%s %v", tc.name, tc.params)
|
|
||||||
require.ErrorAs(t, err, &pe, "%s %v: %v", tc.name, tc.params, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := Invoke(Request{Command: r.Get("flagged"), Params: map[string]string{"n": "1"}})
|
|
||||||
require.EqualError(t, err, "ran and failed")
|
|
||||||
assert.NotErrorAs(t, err, &pe, "a Run error is the command's, not the caller's")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRunErrorIsShown: an error Run returns reaches the person at the prompt on the
|
|
||||||
// error stream, as well as the surface that logs it.
|
|
||||||
func TestRunErrorIsShown(t *testing.T) {
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "broken",
|
|
||||||
ShortDescription: "cannot do what it is asked",
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
return Result{}, errors.New("no certificate is loaded")
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
|
||||||
require.EqualError(t, r.DispatchArgs([]string{"broken"}, Output{Out: out, Err: errOut}), "no certificate is loaded")
|
|
||||||
assert.Empty(t, out.String())
|
|
||||||
assert.Equal(t, "no certificate is loaded\n", errOut.String())
|
|
||||||
}
|
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrNoTextRendering is returned by Render when a command's Value has no human rendering
|
|
||||||
// and text was asked for anyway. A command declares this by leaving Text nil and saying
|
|
||||||
// so with JSONOnly; it is not a fallback situation but a statement that no such form
|
|
||||||
// exists yet, so nobody builds a script around an interim one. Each surface's default
|
|
||||||
// policy avoids ever asking.
|
|
||||||
var ErrNoTextRendering = errors.New("no human readable output yet; pass -json or -pretty")
|
|
||||||
|
|
||||||
// Format is how a result should be presented.
|
|
||||||
type Format int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// FormatUnset is a request that expressed no preference. A surface resolves it with
|
|
||||||
// its own default before rendering; Render itself treats it as FormatText.
|
|
||||||
FormatUnset Format = iota
|
|
||||||
|
|
||||||
// FormatText renders for a person. It is what an operator gets by default on every
|
|
||||||
// surface with a human at the other end.
|
|
||||||
FormatText
|
|
||||||
|
|
||||||
// FormatJSON renders the result as compact JSON.
|
|
||||||
FormatJSON
|
|
||||||
|
|
||||||
// FormatPrettyJSON renders the result as indented JSON.
|
|
||||||
FormatPrettyJSON
|
|
||||||
)
|
|
||||||
|
|
||||||
// Flag names for the two presentation flags. They are offered on every command rather
|
|
||||||
// than declared by each one, because how a result is displayed is not a property of the
|
|
||||||
// command that produced it.
|
|
||||||
const (
|
|
||||||
FlagJSON = "json"
|
|
||||||
FlagPretty = "pretty"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Flag names nebula ctl takes for itself, anywhere on its line, to say which daemon to
|
|
||||||
// talk to; see reservedFlags.
|
|
||||||
const (
|
|
||||||
FlagConfig = "config"
|
|
||||||
FlagSocket = "socket"
|
|
||||||
)
|
|
||||||
|
|
||||||
// reservedFlags are handled before a command's Run is called, so a command may not
|
|
||||||
// declare them itself. -h and -help are intercepted as a request for usage; -json and
|
|
||||||
// -pretty are added to every command's FlagSet by commandFlags, on every surface, so a
|
|
||||||
// command that defined either would make that definition panic with "flag redefined"
|
|
||||||
// on whichever goroutine ran the command; and -config and -socket are nebula ctl's own,
|
|
||||||
// taken off the line before the client knows which command it names, so a command
|
|
||||||
// that declared either would never receive it there.
|
|
||||||
var reservedFlags = []string{"h", "help", FlagJSON, FlagPretty, FlagConfig, FlagSocket}
|
|
||||||
|
|
||||||
// Render writes r in the requested format. Every surface calls it, so a hostmap looks
|
|
||||||
// the same over ssh as it does through the control socket, and a change to either
|
|
||||||
// rendering happens once.
|
|
||||||
func Render(c *Command, r Result, f Format, w io.Writer) error {
|
|
||||||
switch f {
|
|
||||||
case FormatJSON:
|
|
||||||
return renderJSON(r.Payload(), w, false)
|
|
||||||
|
|
||||||
case FormatPrettyJSON:
|
|
||||||
return renderJSON(r.Payload(), w, true)
|
|
||||||
|
|
||||||
default:
|
|
||||||
// An outcome reads the same for every command: its reason, as a sentence. Only a
|
|
||||||
// Value needs the command's own rendering, so Text never sees anything else.
|
|
||||||
if r.Value == nil {
|
|
||||||
_, err := io.WriteString(w, r.Reason+"\n")
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if c != nil && c.Text != nil {
|
|
||||||
return c.Text(r.Value, w)
|
|
||||||
}
|
|
||||||
|
|
||||||
name := "this command"
|
|
||||||
if c != nil {
|
|
||||||
name = string(c.Name)
|
|
||||||
}
|
|
||||||
return fmt.Errorf("%s has %w", name, ErrNoTextRendering)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func renderJSON(v any, w io.Writer, indent bool) error {
|
|
||||||
enc := json.NewEncoder(w)
|
|
||||||
if indent {
|
|
||||||
enc.SetIndent("", " ")
|
|
||||||
}
|
|
||||||
|
|
||||||
return enc.Encode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Result is what every Run returns: whether the command worked, a sentence saying so,
|
|
||||||
// and, for a command that reports rather than acts, the value it produced.
|
|
||||||
//
|
|
||||||
// Value and Reason are alternatives. A command that reports returns Value(v), and the
|
|
||||||
// surfaces render v, as JSON or through the command's Text. A command that acts, or any
|
|
||||||
// command refusing its arguments, returns Did or Failed, and the surfaces render the
|
|
||||||
// Outcome: its Reason is the sentence these commands have always printed. Nothing is for
|
|
||||||
// a command with nothing to say.
|
|
||||||
//
|
|
||||||
// The envelope itself never reaches a caller. Payload is what JSON carries, and Render
|
|
||||||
// hands Text only the Value, so a command's renderer sees the one type it returns on
|
|
||||||
// success and is never asked to recognise an Outcome.
|
|
||||||
type Result struct {
|
|
||||||
Outcome
|
|
||||||
Value any
|
|
||||||
|
|
||||||
// NotFound marks a refusal that is about the thing asked for rather than the asking:
|
|
||||||
// a vpn address with no tunnel behind it, as opposed to one that would not parse. It
|
|
||||||
// renders exactly as any other refusal, and never reaches the wire; the distinction
|
|
||||||
// is for a surface whose protocol has a word for it, so an HTTP client is told 404
|
|
||||||
// rather than 400 and never has to parse the sentence.
|
|
||||||
NotFound bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// Outcome is the part of a Result that says whether the command worked and, in words a
|
|
||||||
// caller can show someone, why. It is what a program receives from a command that acts
|
|
||||||
// rather than reports: closing a tunnel, changing a remote, reloading config.
|
|
||||||
//
|
|
||||||
// One shape serves all of them. Designing a payload per outcome would be work without a
|
|
||||||
// reader. Reason is set either way, so a success says what it did rather than leaving
|
|
||||||
// the caller to infer it from a bare true.
|
|
||||||
type Outcome struct {
|
|
||||||
OK bool `json:"ok"`
|
|
||||||
Reason string `json:"reason"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Value is the Result of a command that reports: v is what it has to show, and it must
|
|
||||||
// marshal to JSON.
|
|
||||||
func Value(v any) Result {
|
|
||||||
return Result{Outcome: Outcome{OK: true}, Value: v}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Failed is a convenience for the common "it did not work, here is why" case.
|
|
||||||
func Failed(format string, args ...any) Result {
|
|
||||||
return Result{Outcome: Outcome{Reason: fmt.Sprintf(format, args...)}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NotFound is Failed for a command asked about something that does not exist. See
|
|
||||||
// Result.NotFound.
|
|
||||||
func NotFound(format string, args ...any) Result {
|
|
||||||
r := Failed(format, args...)
|
|
||||||
r.NotFound = true
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// Did is a convenience for the common "it worked, here is what happened" case.
|
|
||||||
func Did(format string, args ...any) Result {
|
|
||||||
return Result{Outcome: Outcome{OK: true, Reason: fmt.Sprintf(format, args...)}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing is the Result of a command with nothing to say: it did its work, and the
|
|
||||||
// surface sends an empty, successful reply without rendering anything.
|
|
||||||
func Nothing() Result {
|
|
||||||
return Result{Outcome: Outcome{OK: true}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Empty reports a Result with nothing to render: no Value and no Reason. The zero Result
|
|
||||||
// counts, so a Run that returns Result{} says nothing rather than failing silently.
|
|
||||||
func (r Result) Empty() bool {
|
|
||||||
return r.Value == nil && r.Reason == ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Payload is what a program receives: the Value when there is one, otherwise the
|
|
||||||
// Outcome. No surface sends the envelope itself, so print-tunnel -json emits the tunnel
|
|
||||||
// and close-tunnel -json emits {ok, reason}.
|
|
||||||
func (r Result) Payload() any {
|
|
||||||
if r.Value != nil {
|
|
||||||
return r.Value
|
|
||||||
}
|
|
||||||
return r.Outcome
|
|
||||||
}
|
|
||||||
|
|
||||||
// Typed adapts a renderer for one result type to the TextFunc a Command declares. The
|
|
||||||
// value Render passes is the command's own, see Result, so all that is left is to name
|
|
||||||
// its type once here instead of asserting it at the top of every renderer. A renderer
|
|
||||||
// paired with a command that returns something else fails here, saying what arrived.
|
|
||||||
func Typed[T any](render func(T, io.Writer) error) TextFunc {
|
|
||||||
return func(v any, w io.Writer) error {
|
|
||||||
t, ok := v.(T)
|
|
||||||
if !ok {
|
|
||||||
return fmt.Errorf("expected %T, got %T", t, v)
|
|
||||||
}
|
|
||||||
return render(t, w)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"io"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestRenderPrintsAnOutcomeWithoutText: a command that acts declares no Text. Its
|
|
||||||
// outcome renders as the reason, the same for every command, and as {ok, reason} in
|
|
||||||
// JSON, which is the shape these commands have always emitted.
|
|
||||||
func TestRenderPrintsAnOutcomeWithoutText(t *testing.T) {
|
|
||||||
c := &Command{Name: "act"}
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, Render(c, Did("Closed"), FormatText, out))
|
|
||||||
assert.Equal(t, "Closed\n", out.String())
|
|
||||||
|
|
||||||
out.Reset()
|
|
||||||
require.NoError(t, Render(c, Failed("No vpn address was provided"), FormatText, out))
|
|
||||||
assert.Equal(t, "No vpn address was provided\n", out.String())
|
|
||||||
|
|
||||||
out.Reset()
|
|
||||||
require.NoError(t, Render(c, Failed("nope"), FormatJSON, out))
|
|
||||||
assert.JSONEq(t, `{"ok":false,"reason":"nope"}`, out.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRenderHandsTextOnlyTheValue pins the guarantee Result exists for: a command's
|
|
||||||
// renderer sees the type it returns on success and never the envelope or an outcome, so
|
|
||||||
// a report command that refuses its arguments needs nothing in its Text to cope.
|
|
||||||
func TestRenderHandsTextOnlyTheValue(t *testing.T) {
|
|
||||||
var got any
|
|
||||||
c := &Command{
|
|
||||||
Name: "report",
|
|
||||||
Text: func(v any, w io.Writer) error {
|
|
||||||
got = v
|
|
||||||
_, err := io.WriteString(w, "rendered\n")
|
|
||||||
return err
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, Render(c, Value("data"), FormatText, out))
|
|
||||||
assert.Equal(t, "data", got)
|
|
||||||
assert.Equal(t, "rendered\n", out.String())
|
|
||||||
|
|
||||||
got, out = nil, &bytes.Buffer{}
|
|
||||||
require.NoError(t, Render(c, Failed("refused"), FormatText, out))
|
|
||||||
assert.Nil(t, got, "Text must not be called for an outcome")
|
|
||||||
assert.Equal(t, "refused\n", out.String())
|
|
||||||
|
|
||||||
out.Reset()
|
|
||||||
require.NoError(t, Render(c, Value("data"), FormatJSON, out))
|
|
||||||
assert.JSONEq(t, `"data"`, out.String(), "JSON carries the value, never the envelope")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRenderRefusesTextForAValueWithoutText: leaving Text nil is a statement that no
|
|
||||||
// human form of the value exists yet, and asking for one is an error that says so.
|
|
||||||
func TestRenderRefusesTextForAValueWithoutText(t *testing.T) {
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
err := Render(&Command{Name: "print-tunnel"}, Value(map[string]int{"index": 7}), FormatText, out)
|
|
||||||
require.ErrorIs(t, err, ErrNoTextRendering)
|
|
||||||
require.ErrorContains(t, err, "print-tunnel has no human readable output yet")
|
|
||||||
assert.Empty(t, out.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestTypedNamesTheTypeOnce: Typed replaces the assertion at the top of every renderer.
|
|
||||||
// The right type reaches the renderer; the wrong one is reported, naming both.
|
|
||||||
func TestTypedNamesTheTypeOnce(t *testing.T) {
|
|
||||||
type info struct{ Name string }
|
|
||||||
render := Typed(func(i info, w io.Writer) error {
|
|
||||||
_, err := io.WriteString(w, i.Name+"\n")
|
|
||||||
return err
|
|
||||||
})
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, render(info{Name: "tun0"}, out))
|
|
||||||
assert.Equal(t, "tun0\n", out.String())
|
|
||||||
|
|
||||||
err := render("not an info", out)
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.ErrorContains(t, err, "expected commands.info, got string")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestResultShapes pins what each constructor means to a surface: Empty is the one that
|
|
||||||
// renders nothing, Payload is what a program receives, and OK is set wherever a reason
|
|
||||||
// or value says the command worked.
|
|
||||||
func TestResultShapes(t *testing.T) {
|
|
||||||
assert.True(t, Nothing().Empty())
|
|
||||||
assert.True(t, Result{}.Empty(), "the zero Result says nothing rather than failing silently")
|
|
||||||
assert.False(t, Did("done").Empty())
|
|
||||||
assert.False(t, Failed("no").Empty())
|
|
||||||
assert.False(t, Value("x").Empty())
|
|
||||||
|
|
||||||
assert.True(t, Value("x").OK)
|
|
||||||
assert.True(t, Did("done").OK)
|
|
||||||
assert.False(t, Failed("no").OK)
|
|
||||||
|
|
||||||
assert.Equal(t, "x", Value("x").Payload())
|
|
||||||
assert.Equal(t, Outcome{OK: true, Reason: "done"}, Did("done").Payload())
|
|
||||||
assert.Equal(t, Outcome{Reason: "no"}, Failed("no").Payload())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestNotFoundIsARefusalLikeAnyOther: NotFound renders and marshals exactly as Failed
|
|
||||||
// does, so no surface's output changes by a command adopting it. The mark is on the
|
|
||||||
// Result alone, for a surface whose protocol has a word for it.
|
|
||||||
func TestNotFoundIsARefusalLikeAnyOther(t *testing.T) {
|
|
||||||
r := NotFound("No active tunnel for vpn addr: %s", "10.0.0.5")
|
|
||||||
assert.False(t, r.OK)
|
|
||||||
assert.True(t, r.NotFound)
|
|
||||||
assert.False(t, Failed("nope").NotFound)
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, Render(&Command{Name: "look"}, r, FormatText, out))
|
|
||||||
assert.Equal(t, "No active tunnel for vpn addr: 10.0.0.5\n", out.String())
|
|
||||||
|
|
||||||
out.Reset()
|
|
||||||
require.NoError(t, Render(&Command{Name: "look"}, r, FormatJSON, out))
|
|
||||||
assert.JSONEq(t, `{"ok":false,"reason":"No active tunnel for vpn addr: 10.0.0.5"}`, out.String(), "the mark never reaches the wire")
|
|
||||||
}
|
|
||||||
@@ -1,143 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"maps"
|
|
||||||
"slices"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Request is one command to run, as every surface hands it to Invoke: the command, its
|
|
||||||
// options by name in the form their flags parse, its operands, and the rendering the
|
|
||||||
// line asked for, if any.
|
|
||||||
//
|
|
||||||
// nebula ctl builds one with ParseLine and it travels as a JSON object to the control
|
|
||||||
// socket. An ssh line never becomes one: it is parsed straight into the command's own
|
|
||||||
// FlagSet; see execLine.
|
|
||||||
type Request struct {
|
|
||||||
// Command is the command to run, resolved by the surface at its edge. See
|
|
||||||
// Registry.Resolve for the one that tells an unknown name from a withheld one.
|
|
||||||
Command *Command
|
|
||||||
|
|
||||||
// Params carries the options the line set, by flag name, each in the form its flag
|
|
||||||
// parses from. An option left alone is absent, so the command's default applies.
|
|
||||||
Params map[string]string
|
|
||||||
|
|
||||||
// Args carries the operands: whatever the line did not consume as a flag.
|
|
||||||
Args []string
|
|
||||||
|
|
||||||
// Format is the rendering the line asked for with -json or -pretty, or FormatUnset
|
|
||||||
// when it expressed no preference. It is ParseLine's reading of the line for the
|
|
||||||
// client that sends the Request; Invoke does not read it, since the surface that
|
|
||||||
// runs a Request renders with the format it agreed with its caller.
|
|
||||||
Format Format
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseLine reads a FlagSet that ParseArgs has filled, and the operands it returned,
|
|
||||||
// into a Request to send over the wire. Command is left for the caller to set.
|
|
||||||
//
|
|
||||||
// Every flag the line set other than the presentation flags travels by name, as its
|
|
||||||
// flag's String, which is what the daemon's Set parses. That round trip is exact for
|
|
||||||
// the bool and string flags a client builds from the schema; it is the client's to make,
|
|
||||||
// and the ssh path does not make it, since it runs the FlagSet it parsed.
|
|
||||||
func ParseLine(fl *flag.FlagSet, operands []string) Request {
|
|
||||||
req := Request{Args: operands, Format: presentationFormat(fl)}
|
|
||||||
|
|
||||||
fl.Visit(func(f *flag.Flag) {
|
|
||||||
if isPresentationFlag(f.Name) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if req.Params == nil {
|
|
||||||
req.Params = map[string]string{}
|
|
||||||
}
|
|
||||||
req.Params[f.Name] = f.Value.String()
|
|
||||||
})
|
|
||||||
|
|
||||||
return req
|
|
||||||
}
|
|
||||||
|
|
||||||
// presentationFormat is the one reading of -json and -pretty from a parsed line, so a
|
|
||||||
// line means the same on every surface: only a flag set to true asks for JSON, since one
|
|
||||||
// set to false expresses no preference, and -pretty implies -json. FormatUnset means the
|
|
||||||
// line expressed no preference and the surface's own default applies.
|
|
||||||
func presentationFormat(fl *flag.FlagSet) Format {
|
|
||||||
var asJSON, pretty bool
|
|
||||||
fl.Visit(func(f *flag.Flag) {
|
|
||||||
switch f.Name {
|
|
||||||
case FlagJSON:
|
|
||||||
asJSON = flagIsTrue(f)
|
|
||||||
case FlagPretty:
|
|
||||||
pretty = flagIsTrue(f)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case pretty:
|
|
||||||
return FormatPrettyJSON
|
|
||||||
case asJSON:
|
|
||||||
return FormatJSON
|
|
||||||
default:
|
|
||||||
return FormatUnset
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PresentationFormat is presentationFormat for a surface that takes a command's options
|
|
||||||
// by name rather than from a line: the info API's query string. Only the two presentation
|
|
||||||
// flags are read from params; the command's own parameters are the caller's to pass to
|
|
||||||
// Invoke, which refuses these two among them. A flag given with no value counts as set,
|
|
||||||
// as -pretty does on a line, and one that is not a boolean is a ParamError.
|
|
||||||
func PresentationFormat(params map[string]string) (Format, error) {
|
|
||||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
|
||||||
addPresentationFlags(fl)
|
|
||||||
|
|
||||||
for _, k := range []string{FlagJSON, FlagPretty} {
|
|
||||||
v, ok := params[k]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if v == "" {
|
|
||||||
v = "true"
|
|
||||||
}
|
|
||||||
if err := setFlag(fl, fl.Lookup(k), v); err != nil {
|
|
||||||
return FormatUnset, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return presentationFormat(fl), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// flagIsTrue reports whether a bool flag was set to true. The flag package's bool value
|
|
||||||
// is a flag.Getter whose Get returns the bool, so this never falls back to parsing text.
|
|
||||||
func flagIsTrue(f *flag.Flag) bool {
|
|
||||||
g, ok := f.Value.(flag.Getter)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
b, _ := g.Get().(bool)
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invoke runs one Request and returns the command's Result, unrendered.
|
|
||||||
//
|
|
||||||
// The parameters are applied by flag name, in name order: a request from the wire is a
|
|
||||||
// JSON object with no order of its own, and which of two bad parameters is reported must
|
|
||||||
// not change from one request to the next. An unknown parameter is an error rather than
|
|
||||||
// something quietly ignored, because a caller that misspells one deserves to hear about
|
|
||||||
// it instead of getting a default. A bad parameter means Run is never called, and the
|
|
||||||
// FlagSet is fresh for this call, so nothing set before it is seen by anyone.
|
|
||||||
//
|
|
||||||
// Nothing here writes anywhere and nothing here renders. What a surface does with the
|
|
||||||
// Result, marshal its Payload or run the command's own text rendering through Render,
|
|
||||||
// is the surface's decision, and keeping that out of here is what lets a caller tell a
|
|
||||||
// refusal from a success after the text has been produced. The presentation flags are
|
|
||||||
// not parameters: a Request says how it wants rendering in Format, and sending them as
|
|
||||||
// parameters is refused rather than read as a preference.
|
|
||||||
func Invoke(req Request) (Result, error) {
|
|
||||||
c := req.Command
|
|
||||||
|
|
||||||
fl, fs, own := commandFlags(c)
|
|
||||||
if err := setParams(fl, string(c.Name), slices.Sorted(maps.Keys(req.Params)), req.Params, own); err != nil {
|
|
||||||
return Result{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Run(fs, req.Args)
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func lineFlags() *flag.FlagSet {
|
|
||||||
fl := flag.NewFlagSet("set", flag.ContinueOnError)
|
|
||||||
fl.Bool("verbose", false, "")
|
|
||||||
fl.Duration("wait", 0, "")
|
|
||||||
fl.String("label", "none", "")
|
|
||||||
fl.Bool(FlagJSON, false, "")
|
|
||||||
fl.Bool(FlagPretty, false, "")
|
|
||||||
return fl
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParseLineReadsThePresentationFlagsOnce: presentationFormat is the one reading of
|
|
||||||
// -json and -pretty, for every surface, and ParseLine carries its answer. A flag set to
|
|
||||||
// false expresses no preference, and neither flag ever travels as a parameter.
|
|
||||||
func TestParseLineReadsThePresentationFlagsOnce(t *testing.T) {
|
|
||||||
for _, tc := range []struct {
|
|
||||||
args []string
|
|
||||||
want Format
|
|
||||||
}{
|
|
||||||
{nil, FormatUnset},
|
|
||||||
{[]string{"-json=false"}, FormatUnset},
|
|
||||||
{[]string{"-pretty=false"}, FormatUnset},
|
|
||||||
{[]string{"-json"}, FormatJSON},
|
|
||||||
{[]string{"-pretty"}, FormatPrettyJSON},
|
|
||||||
{[]string{"-pretty", "-json=false"}, FormatPrettyJSON},
|
|
||||||
} {
|
|
||||||
fl := lineFlags()
|
|
||||||
operands, err := ParseArgs(fl, tc.args)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
req := ParseLine(fl, operands)
|
|
||||||
assert.Equal(t, tc.want, req.Format, "%v", tc.args)
|
|
||||||
assert.Nil(t, req.Params, "%v: presentation flags are not parameters", tc.args)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParseLineCarriesWhatWasSetInParseableForm: only the flags the line set travel,
|
|
||||||
// each as the string its flag parses from, so the daemon's Invoke can apply them to a
|
|
||||||
// fresh FlagSet and get the same values back. Operands come through untouched, those
|
|
||||||
// after "--" included.
|
|
||||||
func TestParseLineCarriesWhatWasSetInParseableForm(t *testing.T) {
|
|
||||||
fl := lineFlags()
|
|
||||||
operands, err := ParseArgs(fl, []string{"-verbose", "-wait", "2s", "x", "--", "-1"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
req := ParseLine(fl, operands)
|
|
||||||
assert.Equal(t, map[string]string{"verbose": "true", "wait": "2s"}, req.Params, "label was left alone and must be absent")
|
|
||||||
assert.Equal(t, []string{"x", "-1"}, req.Args)
|
|
||||||
assert.Equal(t, FormatUnset, req.Format)
|
|
||||||
|
|
||||||
// The round trip a client makes: what ParseLine produced is what Invoke applies.
|
|
||||||
r, seen := paramRegistry(t)
|
|
||||||
req.Command = r.Get("set")
|
|
||||||
_, err = Invoke(req)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, *seen, 1)
|
|
||||||
assert.Equal(t, paramsSeen{Verbose: true, Wait: 2 * time.Second}, (*seen)[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLineRunsTheFlagSetItParsed: the ssh path hands Run the FlagSet the line was parsed
|
|
||||||
// into, with no trip through a Request. A flag.Func has no String worth re-parsing, so a
|
|
||||||
// round trip would hand Run an empty value and no error; the line's value must arrive.
|
|
||||||
func TestLineRunsTheFlagSetItParsed(t *testing.T) {
|
|
||||||
var seen []string
|
|
||||||
r := New()
|
|
||||||
r.Register(&Command{
|
|
||||||
Name: "mode",
|
|
||||||
Flags: func() (*flag.FlagSet, any) {
|
|
||||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
|
||||||
s := new(string)
|
|
||||||
fl.Func("mode", "the mode", func(v string) error {
|
|
||||||
*s = "set:" + v
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
return fl, s
|
|
||||||
},
|
|
||||||
Run: func(fs any, a []string) (Result, error) {
|
|
||||||
seen = append(seen, *fs.(*string))
|
|
||||||
return Value("ok"), nil
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
var out, errw strings.Builder
|
|
||||||
r.Dispatch("mode -json -mode fast", Output{Out: &out, Err: &errw})
|
|
||||||
require.Equal(t, []string{"set:fast"}, seen)
|
|
||||||
assert.Empty(t, errw.String())
|
|
||||||
assert.Equal(t, "\"ok\"\n", out.String(), "-json was read from the same FlagSet")
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package commands
|
|
||||||
|
|
||||||
import "io"
|
|
||||||
|
|
||||||
// Output is where a command line surface's text goes.
|
|
||||||
//
|
|
||||||
// Out and Err are distinct so a command's primary output can stay machine readable on
|
|
||||||
// a surface that separates the two. The ssh surface points both at the same channel and
|
|
||||||
// sees a single merged stream. The local
|
|
||||||
// control socket does not use one at all: it invokes by named parameter and carries the
|
|
||||||
// returned value, so there is no stream for a command to write to.
|
|
||||||
type Output struct {
|
|
||||||
// Out receives what a command produces.
|
|
||||||
Out io.Writer
|
|
||||||
|
|
||||||
// Err receives usage text, refusals and errors.
|
|
||||||
Err io.Writer
|
|
||||||
}
|
|
||||||
|
|
||||||
// MergedOutput sends output and errors to the same writer.
|
|
||||||
func MergedOutput(w io.Writer) Output {
|
|
||||||
return Output{Out: w, Err: w}
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/netip"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/cert_test"
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/logging"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestLogFormatRefusalIsShown: a format the logger does not know is a refusal the user
|
|
||||||
// sees, rather than a bare error, which over ssh was silence.
|
|
||||||
func TestLogFormatRefusalIsShown(t *testing.T) {
|
|
||||||
l := logging.NewLogger(io.Discard)
|
|
||||||
|
|
||||||
res, err := runLogFormat(l, []string{"bogus"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, res.OK)
|
|
||||||
assert.Equal(t, "Unable to set log format: unknown log format `bogus`. possible formats: [text json]", res.Reason)
|
|
||||||
|
|
||||||
res, err = runLogFormat(l, []string{"JSON"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, commands.Typed(textLogFormat)(res.Value, out))
|
|
||||||
assert.Equal(t, "Log format is: json\n", out.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPrintRelaysReportsErrorsAsText: the Error field was an error value, which encodes
|
|
||||||
// as {} and lost the message. It is the message now, and absent when there is none.
|
|
||||||
func TestPrintRelaysReportsErrorsAsText(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
hm := newHostMap(l)
|
|
||||||
relay := netip.MustParseAddr("10.0.0.1")
|
|
||||||
peer := netip.MustParseAddr("10.0.0.2")
|
|
||||||
|
|
||||||
// A relay host that is in Relays but not in Hosts, so its hostinfo cannot be found.
|
|
||||||
hm.Relays[1] = &HostInfo{vpnAddrs: []netip.Addr{relay}}
|
|
||||||
ifce := &Interface{hostMap: hm}
|
|
||||||
|
|
||||||
marshal := func() string {
|
|
||||||
b, err := json.Marshal(runPrintRelays(ifce))
|
|
||||||
require.NoError(t, err)
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
assert.JSONEq(t, `{"Relays":[{"NebulaAddr":"10.0.0.1","RelayForAddrs":[{"Error":"could not find hostinfo","Type":"","State":"","PeerAddr":"","LocalIndex":0,"RemoteIndex":0,"RelayedThrough":null}]}]}`, marshal())
|
|
||||||
|
|
||||||
// The same relay host, found, relaying for a peer whose index matches: no Error key.
|
|
||||||
hi := hm.Relays[1]
|
|
||||||
r := &Relay{Type: ForwardingType, State: Established, PeerAddr: peer, LocalIndex: 1, RemoteIndex: 2}
|
|
||||||
hi.relayState = RelayState{
|
|
||||||
relayForByAddr: map[netip.Addr]*Relay{peer: r},
|
|
||||||
relayForByIdx: map[uint32]*Relay{r.LocalIndex: r},
|
|
||||||
}
|
|
||||||
hm.Hosts[relay] = hi
|
|
||||||
assert.JSONEq(t, `{"Relays":[{"NebulaAddr":"10.0.0.1","RelayForAddrs":[{"Type":"forwarding","State":"established","PeerAddr":"10.0.0.2","LocalIndex":1,"RemoteIndex":2,"RelayedThrough":null}]}]}`, marshal())
|
|
||||||
|
|
||||||
// And an index mismatch names it.
|
|
||||||
hm.Relays[7] = hi
|
|
||||||
delete(hm.Relays, 1)
|
|
||||||
assert.Contains(t, marshal(), `"Error":"hostmap LocalIndex '7' does not match RelayState LocalIndex"`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPrintCertOfATunnelWithoutACertificate: a tunnel still handshaking, or one being
|
|
||||||
// torn down, has no certificate, and print-cert refuses rather than panicking.
|
|
||||||
func TestPrintCertOfATunnelWithoutACertificate(t *testing.T) {
|
|
||||||
f, _ := identityFixture(t)
|
|
||||||
|
|
||||||
r, err := runPrintCert(f, &printCertFlags{}, []string{"10.0.0.3"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, r.OK)
|
|
||||||
assert.Equal(t, "Could not find tunnel for vpn addr: 10.0.0.3", r.Reason)
|
|
||||||
|
|
||||||
r, err = runPrintCert(f, &printCertFlags{}, []string{"10.0.0.2"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.True(t, r.OK, "a tunnel with a certificate is printed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPrintCertByAddressFlag: -address is the info API's spelling of the operand, takes a
|
|
||||||
// port and a 4in6 form the way identity does, answers our own address with our own
|
|
||||||
// certificate, and is refused together with an operand.
|
|
||||||
func TestPrintCertByAddressFlag(t *testing.T) {
|
|
||||||
f, peerCert := identityFixture(t)
|
|
||||||
|
|
||||||
for _, addr := range []string{"10.0.0.2", "10.0.0.2:4242", "[::ffff:10.0.0.2]:4242"} {
|
|
||||||
fl := &printCertFlags{}
|
|
||||||
require.NoError(t, fl.setAddress(addr))
|
|
||||||
r, err := runPrintCert(f, fl, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.True(t, r.OK, addr)
|
|
||||||
assert.Equal(t, peerCert, r.Value, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
fl := &printCertFlags{}
|
|
||||||
require.NoError(t, fl.setAddress("10.0.0.1"))
|
|
||||||
r, err := runPrintCert(f, fl, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.True(t, r.OK)
|
|
||||||
assert.Equal(t, ownCertificate(f.pki.getCertState()), r.Value, "our own address is our own certificate")
|
|
||||||
|
|
||||||
fl = &printCertFlags{}
|
|
||||||
require.NoError(t, fl.setAddress("10.0.0.3"))
|
|
||||||
r, err = runPrintCert(f, fl, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, r.OK)
|
|
||||||
assert.True(t, r.NotFound)
|
|
||||||
|
|
||||||
fl = &printCertFlags{}
|
|
||||||
require.NoError(t, fl.setAddress("not-an-address"))
|
|
||||||
r, err = runPrintCert(f, fl, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, "The provided vpn addr could not be parsed: not-an-address", r.Reason)
|
|
||||||
|
|
||||||
fl = &printCertFlags{}
|
|
||||||
require.NoError(t, fl.setAddress("10.0.0.2"))
|
|
||||||
r, err = runPrintCert(f, fl, []string{"10.0.0.2"})
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, "print-cert takes one vpn addr, as -address or as an operand, not both", r.Reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPrintCertPrefersOwnV2: with no address print-cert reports the certificate whoami
|
|
||||||
// does, the v2 when both versions are loaded, rather than the one handshakes start with.
|
|
||||||
func TestPrintCertPrefersOwnV2(t *testing.T) {
|
|
||||||
v4 := netip.MustParsePrefix("10.0.0.1/24")
|
|
||||||
ca1, _, caKey1, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
v1, _, _, _ := cert_test.NewTestCert(cert.Version1, cert.Curve_CURVE25519, ca1, caKey1, "me", time.Time{}, time.Time{}, []netip.Prefix{v4}, nil, nil)
|
|
||||||
ca2, _, caKey2, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
v2, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca2, caKey2, "me", time.Time{}, time.Time{}, []netip.Prefix{v4}, nil, nil)
|
|
||||||
|
|
||||||
f := &Interface{pki: &PKI{}, hostMap: newHostMap(test.NewLogger())}
|
|
||||||
f.pki.cs.Store(&CertState{v1Cert: v1, v2Cert: v2, initiatingVersion: cert.Version1})
|
|
||||||
|
|
||||||
r, err := runPrintCert(f, &printCertFlags{}, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.True(t, r.OK)
|
|
||||||
assert.Equal(t, v2, r.Value)
|
|
||||||
}
|
|
||||||
+33
-72
@@ -5,7 +5,6 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"maps"
|
|
||||||
"math"
|
"math"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
@@ -26,17 +25,9 @@ type C struct {
|
|||||||
files []string
|
files []string
|
||||||
Settings map[string]any
|
Settings map[string]any
|
||||||
oldSettings map[string]any
|
oldSettings map[string]any
|
||||||
callbacks []func(*C, *Reload)
|
callbacks []func(*C)
|
||||||
l *slog.Logger
|
l *slog.Logger
|
||||||
reloadLock sync.Mutex
|
reloadLock sync.Mutex
|
||||||
|
|
||||||
// Set by the first reload that needs a restart and never cleared. Guarded by reloadLock
|
|
||||||
needsRestart bool
|
|
||||||
|
|
||||||
// callbackLock guards callbacks. Registration is not confined to startup: CatchHUP is
|
|
||||||
// running from inside Main, and anything wired up after Main returns registers while
|
|
||||||
// a HUP could already be reloading, so append and iteration have to be serialized.
|
|
||||||
callbackLock sync.Mutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewC(l *slog.Logger) *C {
|
func NewC(l *slog.Logger) *C {
|
||||||
@@ -80,45 +71,16 @@ func (c *C) LoadString(raw string) error {
|
|||||||
// RegisterReloadCallback stores a function to be called when a config reload is triggered. The functions registered
|
// RegisterReloadCallback stores a function to be called when a config reload is triggered. The functions registered
|
||||||
// here should decide if they need to make a change to the current process before making the change. HasChanged can be
|
// here should decide if they need to make a change to the current process before making the change. HasChanged can be
|
||||||
// used to help decide if a change is necessary.
|
// used to help decide if a change is necessary.
|
||||||
// These functions should return quickly or spawn their own go routine if they will take a while.
|
// These functions should return quickly or spawn their own go routine if they will take a while
|
||||||
// Use r to report anything that failed or needs a restart to apply.
|
func (c *C) RegisterReloadCallback(f func(*C)) {
|
||||||
func (c *C) RegisterReloadCallback(f func(c *C, r *Reload)) {
|
|
||||||
c.callbackLock.Lock()
|
|
||||||
defer c.callbackLock.Unlock()
|
|
||||||
c.callbacks = append(c.callbacks, f)
|
c.callbacks = append(c.callbacks, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
// reloadCallbacks returns a snapshot of the registered callbacks. Reloads iterate the
|
|
||||||
// snapshot rather than the live slice, so a registration from another goroutine cannot
|
|
||||||
// race the loop; a callback registered while a reload is in progress runs from the next
|
|
||||||
// reload on. callbackLock is not held during the calls themselves, so a callback that
|
|
||||||
// registers another callback does not deadlock.
|
|
||||||
func (c *C) reloadCallbacks() []func(*C, *Reload) {
|
|
||||||
c.callbackLock.Lock()
|
|
||||||
defer c.callbackLock.Unlock()
|
|
||||||
return append(make([]func(*C, *Reload), 0, len(c.callbacks)), c.callbacks...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// InitialLoad returns true if this is the first load of the config, and ReloadConfig has not been called yet.
|
// InitialLoad returns true if this is the first load of the config, and ReloadConfig has not been called yet.
|
||||||
func (c *C) InitialLoad() bool {
|
func (c *C) InitialLoad() bool {
|
||||||
return c.oldSettings == nil
|
return c.oldSettings == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render returns keys and their values as yaml, for a subsystem to remember what it applied. Empty means they couldn't
|
|
||||||
// be rendered and should never match.
|
|
||||||
func (c *C) Render(keys ...string) string {
|
|
||||||
m := make(map[string]any, len(keys))
|
|
||||||
for _, k := range keys {
|
|
||||||
m[k] = c.Get(k)
|
|
||||||
}
|
|
||||||
b, err := yaml.Marshal(m)
|
|
||||||
if err != nil {
|
|
||||||
c.l.Debug("Failed to render config", "keys", keys, "error", err)
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
|
// HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
|
||||||
// k in both the old and new settings will be serialized, the result of the string comparison is returned.
|
// k in both the old and new settings will be serialized, the result of the string comparison is returned.
|
||||||
// If k is an empty string the entire config is tested.
|
// If k is an empty string the entire config is tested.
|
||||||
@@ -181,55 +143,54 @@ func (c *C) CatchHUP(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ch:
|
case <-ch:
|
||||||
c.l.Info("Caught HUP, reloading config")
|
c.l.Info("Caught HUP, reloading config")
|
||||||
c.ReloadConfig().Log(c.l)
|
c.ReloadConfig()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReloadConfig reloads the config from the path provided to Load and runs every registered callback. A config that
|
func (c *C) ReloadConfig() {
|
||||||
// fails to load is logged here, like any other failure, and the result carries the error for the summary.
|
|
||||||
func (c *C) ReloadConfig() ReloadResult {
|
|
||||||
c.reloadLock.Lock()
|
c.reloadLock.Lock()
|
||||||
defer c.reloadLock.Unlock()
|
defer c.reloadLock.Unlock()
|
||||||
|
|
||||||
c.oldSettings = make(map[string]any)
|
c.oldSettings = make(map[string]any)
|
||||||
maps.Copy(c.oldSettings, c.Settings)
|
for k, v := range c.Settings {
|
||||||
|
c.oldSettings[k] = v
|
||||||
if err := c.Load(c.path); err != nil {
|
|
||||||
c.l.Error("Error occurred while reloading config", "config_path", c.path, "error", err)
|
|
||||||
return ReloadResult{Err: err, RestartRequired: c.needsRestart}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.runCallbacks()
|
err := c.Load(c.path)
|
||||||
|
if err != nil {
|
||||||
|
c.l.Error("Error occurred while reloading config",
|
||||||
|
"config_path", c.path,
|
||||||
|
"error", err,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, v := range c.callbacks {
|
||||||
|
v(c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReloadConfigString is ReloadConfig for a config held in memory rather than on disk.
|
func (c *C) ReloadConfigString(raw string) error {
|
||||||
func (c *C) ReloadConfigString(raw string) ReloadResult {
|
|
||||||
c.reloadLock.Lock()
|
c.reloadLock.Lock()
|
||||||
defer c.reloadLock.Unlock()
|
defer c.reloadLock.Unlock()
|
||||||
|
|
||||||
c.oldSettings = make(map[string]any)
|
c.oldSettings = make(map[string]any)
|
||||||
maps.Copy(c.oldSettings, c.Settings)
|
for k, v := range c.Settings {
|
||||||
|
c.oldSettings[k] = v
|
||||||
if err := c.LoadString(raw); err != nil {
|
|
||||||
c.l.Error("Error occurred while reloading config", "error", err)
|
|
||||||
return ReloadResult{Err: err, RestartRequired: c.needsRestart}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.runCallbacks()
|
err := c.LoadString(raw)
|
||||||
}
|
if err != nil {
|
||||||
|
return err
|
||||||
func (c *C) runCallbacks() ReloadResult {
|
|
||||||
r := &Reload{c: c}
|
|
||||||
for _, v := range c.reloadCallbacks() {
|
|
||||||
v(c, r)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.restart {
|
for _, v := range c.callbacks {
|
||||||
c.needsRestart = true
|
v(c)
|
||||||
}
|
}
|
||||||
return ReloadResult{Failed: r.failed, RestartRequired: c.needsRestart, RestartKeys: r.keys}
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetString will get the string for k or return the default d if not found or invalid
|
// GetString will get the string for k or return the default d if not found or invalid
|
||||||
@@ -255,7 +216,7 @@ func (c *C) GetStringSlice(k string, d []string) []string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
v := make([]string, len(rv))
|
v := make([]string, len(rv))
|
||||||
for i := range v {
|
for i := 0; i < len(v); i++ {
|
||||||
v[i] = fmt.Sprintf("%v", rv[i])
|
v[i] = fmt.Sprintf("%v", rv[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,8 +310,8 @@ func (c *C) IsSet(k string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *C) get(k string, v any) any {
|
func (c *C) get(k string, v any) any {
|
||||||
parts := strings.SplitSeq(k, ".")
|
parts := strings.Split(k, ".")
|
||||||
for p := range parts {
|
for _, p := range parts {
|
||||||
m, ok := v.(map[string]any)
|
m, ok := v.(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil
|
return nil
|
||||||
@@ -433,7 +394,7 @@ func (c *C) parse() error {
|
|||||||
var nm map[string]any
|
var nm map[string]any
|
||||||
err = yaml.Unmarshal(b, &nm)
|
err = yaml.Unmarshal(b, &nm)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("%s: %w", path, err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// We need to use WithAppendSlice so that firewall rules in separate
|
// We need to use WithAppendSlice so that firewall rules in separate
|
||||||
|
|||||||
+2
-41
@@ -3,7 +3,6 @@ package config
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -20,7 +19,7 @@ func TestConfig_Load(t *testing.T) {
|
|||||||
// invalid yaml
|
// invalid yaml
|
||||||
c := NewC(l)
|
c := NewC(l)
|
||||||
os.WriteFile(filepath.Join(dir, "01.yaml"), []byte(" invalid yaml"), 0644)
|
os.WriteFile(filepath.Join(dir, "01.yaml"), []byte(" invalid yaml"), 0644)
|
||||||
require.EqualError(t, c.Load(dir), filepath.Join(dir, "01.yaml")+": yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `invalid...` into map[string]interface {}")
|
require.EqualError(t, c.Load(dir), "yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `invalid...` into map[string]interface {}")
|
||||||
|
|
||||||
// simple multi config merge
|
// simple multi config merge
|
||||||
c = NewC(l)
|
c = NewC(l)
|
||||||
@@ -130,7 +129,7 @@ func TestConfig_ReloadConfig(t *testing.T) {
|
|||||||
|
|
||||||
os.WriteFile(filepath.Join(dir, "01.yaml"), []byte("outer:\n inner: ho"), 0644)
|
os.WriteFile(filepath.Join(dir, "01.yaml"), []byte("outer:\n inner: ho"), 0644)
|
||||||
|
|
||||||
c.RegisterReloadCallback(func(c *C, _ *Reload) {
|
c.RegisterReloadCallback(func(c *C) {
|
||||||
done <- true
|
done <- true
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -221,41 +220,3 @@ firewall:
|
|||||||
}
|
}
|
||||||
assert.Equal(t, expected, m)
|
assert.Equal(t, expected, m)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRegisterReloadCallbackDuringReload: registration is not confined to startup. The
|
|
||||||
// HUP handler runs from inside nebula.Main, and anything wired after Main returns
|
|
||||||
// registers while a reload may already be iterating the callbacks. Under -race this is
|
|
||||||
// the data race on the slice; without it, it checks a callback registered mid-reload is
|
|
||||||
// picked up by the next one.
|
|
||||||
func TestRegisterReloadCallbackDuringReload(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
c := NewC(l)
|
|
||||||
require.NoError(t, c.LoadString("a: 1"))
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
wg.Add(2)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
for i := 0; i < 200; i++ {
|
|
||||||
c.RegisterReloadCallback(func(*C, *Reload) {})
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
for i := 0; i < 200; i++ {
|
|
||||||
assert.NoError(t, c.ReloadConfigString("a: 1").Err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
// A callback that registers another callback must not deadlock, and the new one
|
|
||||||
// runs from the following reload on.
|
|
||||||
var ran int
|
|
||||||
c.RegisterReloadCallback(func(c *C, _ *Reload) {
|
|
||||||
c.RegisterReloadCallback(func(*C, *Reload) { ran++ })
|
|
||||||
})
|
|
||||||
require.NoError(t, c.ReloadConfigString("a: 1").Err)
|
|
||||||
assert.Equal(t, 0, ran, "registered during this reload, so not run by it")
|
|
||||||
require.NoError(t, c.ReloadConfigString("a: 1").Err)
|
|
||||||
assert.Equal(t, 1, ran, "and run by the next")
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
"slices"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ReloadResult describes how a reload went. Problems are logged where they happen, Log writes a one line summary.
|
|
||||||
type ReloadResult struct {
|
|
||||||
// Err is set when the new config could not be read or parsed, no callbacks ran
|
|
||||||
Err error
|
|
||||||
// Failed is true when a callback could not apply part of the new config
|
|
||||||
Failed bool
|
|
||||||
// RestartRequired is true once any reload has needed a restart, and stays true until the process restarts
|
|
||||||
RestartRequired bool
|
|
||||||
// RestartKeys are the keys this reload changed that only apply on a restart
|
|
||||||
RestartKeys []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Summary returns a one line summary of the reload and the level to log it at.
|
|
||||||
func (r ReloadResult) Summary() (slog.Level, string) {
|
|
||||||
switch {
|
|
||||||
case r.Err != nil && r.RestartRequired:
|
|
||||||
return slog.LevelError, "Config reload failed, the new config did not load and a restart is still required"
|
|
||||||
case r.Err != nil:
|
|
||||||
return slog.LevelError, "Config reload failed, the new config did not load"
|
|
||||||
case r.Failed && r.RestartRequired:
|
|
||||||
return slog.LevelError, "Config reload completed with errors and requires a restart to fully apply, review the logs"
|
|
||||||
case r.Failed:
|
|
||||||
return slog.LevelError, "Config reload completed with errors, review the logs"
|
|
||||||
case r.RestartRequired:
|
|
||||||
return slog.LevelWarn, "Config reload was completed but requires a restart to fully apply"
|
|
||||||
default:
|
|
||||||
return slog.LevelInfo, "Config reload complete"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// String is the summary with Err and RestartKeys included, for output other than the log.
|
|
||||||
func (r ReloadResult) String() string {
|
|
||||||
_, msg := r.Summary()
|
|
||||||
if r.Err != nil {
|
|
||||||
msg = fmt.Sprintf("%s: %v", msg, r.Err)
|
|
||||||
}
|
|
||||||
if len(r.RestartKeys) > 0 {
|
|
||||||
msg = fmt.Sprintf("%s, keys %v", msg, r.RestartKeys)
|
|
||||||
}
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// Log writes Summary to l.
|
|
||||||
func (r ReloadResult) Log(l *slog.Logger) {
|
|
||||||
level, msg := r.Summary()
|
|
||||||
if len(r.RestartKeys) > 0 {
|
|
||||||
l.Log(context.Background(), level, msg, "keys", r.RestartKeys)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l.Log(context.Background(), level, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reload is passed to each reload callback to report how applying the new config went.
|
|
||||||
type Reload struct {
|
|
||||||
c *C
|
|
||||||
failed bool
|
|
||||||
restart bool
|
|
||||||
// Changed keys that only apply on a restart, from every callback
|
|
||||||
keys []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Failed marks the reload as failed, the caller logs why. Safe to call on a nil Reload, which is what the initial load
|
|
||||||
// passes.
|
|
||||||
func (r *Reload) Failed() {
|
|
||||||
if r != nil {
|
|
||||||
r.failed = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RestartRequired marks the reload as needing a restart, the caller logs why. Safe to call on a nil Reload.
|
|
||||||
func (r *Reload) RestartRequired() {
|
|
||||||
if r != nil {
|
|
||||||
r.restart = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RestartRequiredIfChanged marks the reload as needing a restart if any of keys changed, and adds them to RestartKeys.
|
|
||||||
// Use it for keys that are only read at startup. Safe to call on a nil Reload.
|
|
||||||
func (r *Reload) RestartRequiredIfChanged(keys ...string) {
|
|
||||||
if r == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, k := range keys {
|
|
||||||
if r.c.HasChanged(k) && !slices.Contains(r.keys, k) {
|
|
||||||
r.keys = append(r.keys, k)
|
|
||||||
r.restart = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"log/slog"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestReloadConfigString(t *testing.T) {
|
|
||||||
c := NewC(test.NewLogger())
|
|
||||||
require.NoError(t, c.LoadString("a: 1"))
|
|
||||||
fail := false
|
|
||||||
ran := 0
|
|
||||||
c.RegisterReloadCallback(func(c *C, r *Reload) {
|
|
||||||
ran++
|
|
||||||
if fail {
|
|
||||||
r.Failed()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
assert.Equal(t, ReloadResult{}, c.ReloadConfigString("a: 2"))
|
|
||||||
fail = true
|
|
||||||
assert.Equal(t, ReloadResult{Failed: true}, c.ReloadConfigString("a: 3"))
|
|
||||||
assert.Equal(t, 2, ran)
|
|
||||||
|
|
||||||
// A config that fails to load runs no callbacks and returns the error
|
|
||||||
res := c.ReloadConfigString("a: [")
|
|
||||||
require.Error(t, res.Err)
|
|
||||||
assert.False(t, res.Failed)
|
|
||||||
assert.Equal(t, 2, ran)
|
|
||||||
assert.Equal(t, 3, c.GetInt("a", 0))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReloadRestartRequiredLatches(t *testing.T) {
|
|
||||||
c := NewC(test.NewLogger())
|
|
||||||
require.NoError(t, c.LoadString("a: 1\nb: 1"))
|
|
||||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequiredIfChanged("a", "b") })
|
|
||||||
|
|
||||||
// Nothing that needs a restart changed
|
|
||||||
assert.Equal(t, ReloadResult{}, c.ReloadConfigString("a: 1\nb: 1\nc: 1"))
|
|
||||||
assert.Equal(t, ReloadResult{RestartRequired: true, RestartKeys: []string{"a"}}, c.ReloadConfigString("a: 2\nb: 1\nc: 1"))
|
|
||||||
|
|
||||||
// The restart sticks through a reload with no changes, reverting the key and a config that fails to load. Only the
|
|
||||||
// reload that changed the key lists it
|
|
||||||
assert.Equal(t, ReloadResult{RestartRequired: true}, c.ReloadConfigString("a: 2\nb: 1\nc: 1"))
|
|
||||||
assert.Equal(t, ReloadResult{RestartRequired: true, RestartKeys: []string{"a"}}, c.ReloadConfigString("a: 1\nb: 1\nc: 1"))
|
|
||||||
|
|
||||||
res := c.ReloadConfigString("a: [")
|
|
||||||
require.Error(t, res.Err)
|
|
||||||
assert.True(t, res.RestartRequired)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A key reported by more than one callback is listed once
|
|
||||||
func TestReloadRestartKeysDeduped(t *testing.T) {
|
|
||||||
c := NewC(test.NewLogger())
|
|
||||||
require.NoError(t, c.LoadString("a: 1\nb: 1"))
|
|
||||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequiredIfChanged("a") })
|
|
||||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequiredIfChanged("a", "b") })
|
|
||||||
|
|
||||||
assert.Equal(t, []string{"a", "b"}, c.ReloadConfigString("a: 2\nb: 2").RestartKeys)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A callback can require a restart without a key changing, a file the config points at may have
|
|
||||||
func TestReloadRestartRequiredWithoutAChange(t *testing.T) {
|
|
||||||
c := NewC(test.NewLogger())
|
|
||||||
require.NoError(t, c.LoadString("a: 1"))
|
|
||||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequired() })
|
|
||||||
|
|
||||||
assert.Equal(t, ReloadResult{RestartRequired: true}, c.ReloadConfigString("a: 1"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReloadResultSummary(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
res ReloadResult
|
|
||||||
level slog.Level
|
|
||||||
msg string
|
|
||||||
}{
|
|
||||||
{ReloadResult{}, slog.LevelInfo, "Config reload complete"},
|
|
||||||
{ReloadResult{RestartRequired: true}, slog.LevelWarn, "Config reload was completed but requires a restart to fully apply"},
|
|
||||||
{ReloadResult{Failed: true}, slog.LevelError, "Config reload completed with errors, review the logs"},
|
|
||||||
{ReloadResult{Failed: true, RestartRequired: true}, slog.LevelError, "Config reload completed with errors and requires a restart to fully apply, review the logs"},
|
|
||||||
{ReloadResult{Err: errors.New("bad yaml")}, slog.LevelError, "Config reload failed, the new config did not load"},
|
|
||||||
{ReloadResult{Err: errors.New("bad yaml"), RestartRequired: true}, slog.LevelError, "Config reload failed, the new config did not load and a restart is still required"},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
level, msg := tc.res.Summary()
|
|
||||||
assert.Equal(t, tc.level, level, tc.msg)
|
|
||||||
assert.Equal(t, tc.msg, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
res := ReloadResult{RestartRequired: true, RestartKeys: []string{"a", "b"}}
|
|
||||||
assert.Equal(t, "Config reload was completed but requires a restart to fully apply, keys [a b]", res.String())
|
|
||||||
|
|
||||||
// String includes the error
|
|
||||||
assert.Equal(t, "Config reload failed, the new config did not load: bad yaml", ReloadResult{Err: errors.New("bad yaml")}.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// The initial load passes a nil Reload
|
|
||||||
func TestReloadNilIsSafe(t *testing.T) {
|
|
||||||
var r *Reload
|
|
||||||
r.Failed()
|
|
||||||
r.RestartRequired()
|
|
||||||
r.RestartRequiredIfChanged("a")
|
|
||||||
}
|
|
||||||
+6
-31
@@ -57,8 +57,7 @@ func newConnectionManagerFromConfig(l *slog.Logger, c *config.C, hm *HostMap, p
|
|||||||
}
|
}
|
||||||
|
|
||||||
cm.reload(c, true)
|
cm.reload(c, true)
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C) {
|
||||||
r.RestartRequiredIfChanged("timers.connection_alive_interval", "timers.pending_deletion_interval")
|
|
||||||
cm.reload(c, false)
|
cm.reload(c, false)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -109,13 +108,7 @@ func (cm *connectionManager) In(h *HostInfo) {
|
|||||||
h.markIn()
|
h.markIn()
|
||||||
}
|
}
|
||||||
|
|
||||||
// OutNoRebind records outbound traffic without consuming the rebind epoch, for relayed sends: the direct path
|
// Out records outbound traffic and reports whether the local network changed since this tunnel last sent.
|
||||||
// to the relay consumes the edge, the via send must not.
|
|
||||||
func (cm *connectionManager) OutNoRebind(h *HostInfo) {
|
|
||||||
h.markOutOnly()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Out records outbound traffic and reports whether we rebound since this tunnel last sent
|
|
||||||
func (cm *connectionManager) Out(h *HostInfo) bool {
|
func (cm *connectionManager) Out(h *HostInfo) bool {
|
||||||
return h.markOut(cm.intf.rebindEpoch.Load())
|
return h.markOut(cm.intf.rebindEpoch.Load())
|
||||||
}
|
}
|
||||||
@@ -175,8 +168,10 @@ func (cm *connectionManager) doTrafficCheck(localIndex uint32, p, nb, out []byte
|
|||||||
|
|
||||||
switch decision {
|
switch decision {
|
||||||
case deleteTunnel:
|
case deleteTunnel:
|
||||||
// Local delete only, clearing the lighthouse cache if this was the last hostinfo for the vpn addr
|
if cm.hostMap.DeleteHostInfo(hostinfo) {
|
||||||
cm.intf.closeTunnel(hostinfo)
|
// Only clearing the lighthouse cache if this is the last hostinfo for this vpn ip in the hostmap
|
||||||
|
cm.intf.lightHouse.DeleteVpnAddrs(hostinfo.vpnAddrs)
|
||||||
|
}
|
||||||
|
|
||||||
case closeTunnel:
|
case closeTunnel:
|
||||||
cm.intf.sendCloseTunnel(hostinfo)
|
cm.intf.sendCloseTunnel(hostinfo)
|
||||||
@@ -328,12 +323,6 @@ func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Tim
|
|||||||
return closeTunnel, hostinfo, nil
|
return closeTunnel, hostinfo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if hostinfo.ConnectionState != nil && hostinfo.ConnectionState.messageCounter.Load() >= RejectAfterMessages {
|
|
||||||
// Send path can't encrypt a CloseTunnel notify, so just delete locally; the peer recovers via recv_error.
|
|
||||||
hostinfo.logger(cm.l).Error("Dropping tunnel, message counter is exhausted")
|
|
||||||
return deleteTunnel, hostinfo, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
primary := cm.hostMap.Hosts[hostinfo.vpnAddrs[0]]
|
primary := cm.hostMap.Hosts[hostinfo.vpnAddrs[0]]
|
||||||
mainHostInfo := true
|
mainHostInfo := true
|
||||||
if primary != nil && primary != hostinfo {
|
if primary != nil && primary != hostinfo {
|
||||||
@@ -459,11 +448,6 @@ func (cm *connectionManager) shouldSwapPrimary(current *HostInfo) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if current.ConnectionState.messageCounter.Load() >= RehandshakeAfterMessages {
|
|
||||||
// This tunnel is being rolled for counter exhaustion, never swap back onto its spent key.
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
crt := cm.intf.pki.getCertState().getCertificate(current.ConnectionState.myCert.Version())
|
crt := cm.intf.pki.getCertState().getCertificate(current.ConnectionState.myCert.Version())
|
||||||
if crt == nil {
|
if crt == nil {
|
||||||
//my cert was reloaded away. We should definitely swap from this tunnel
|
//my cert was reloaded away. We should definitely swap from this tunnel
|
||||||
@@ -560,15 +544,6 @@ func (cm *connectionManager) tryRehandshake(hostinfo *HostInfo) {
|
|||||||
"reason", "current cert version < pki.initiatingVersion",
|
"reason", "current cert version < pki.initiatingVersion",
|
||||||
)
|
)
|
||||||
|
|
||||||
cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if hostinfo.ConnectionState.messageCounter.Load() >= RehandshakeAfterMessages {
|
|
||||||
cm.l.Info("Re-handshaking with remote",
|
|
||||||
"vpnAddrs", hostinfo.vpnAddrs,
|
|
||||||
"reason", "message counter rehandshake threshold reached",
|
|
||||||
)
|
|
||||||
|
|
||||||
cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
|
cm.intf.handshakeManager.StartHandshake(hostinfo.vpnAddrs[0], nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/overlay/overlaytest"
|
"github.com/slackhq/nebula/overlay/overlaytest"
|
||||||
@@ -22,8 +21,6 @@ func newTestLighthouse() *LightHouse {
|
|||||||
l: test.NewLogger(),
|
l: test.NewLogger(),
|
||||||
addrMap: map[netip.Addr]*RemoteList{},
|
addrMap: map[netip.Addr]*RemoteList{},
|
||||||
queryChan: make(chan netip.Addr, 10),
|
queryChan: make(chan netip.Addr, 10),
|
||||||
// Nothing drains queryChan here, so an 11th query is dropped.
|
|
||||||
queryDropped: metrics.NilCounter{},
|
|
||||||
}
|
}
|
||||||
lighthouses := []netip.Addr{}
|
lighthouses := []netip.Addr{}
|
||||||
staticList := map[netip.Addr]struct{}{}
|
staticList := map[netip.Addr]struct{}{}
|
||||||
@@ -202,79 +199,6 @@ func Test_NewConnectionManagerTest2(t *testing.T) {
|
|||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_NewConnectionManager_CounterLimits(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
localrange := netip.MustParsePrefix("10.1.1.1/24")
|
|
||||||
vpnIp := netip.MustParseAddr("172.1.1.2")
|
|
||||||
preferredRanges := []netip.Prefix{localrange}
|
|
||||||
|
|
||||||
// Very incomplete mock objects
|
|
||||||
hostMap := newHostMap(l)
|
|
||||||
hostMap.preferredRanges.Store(&preferredRanges)
|
|
||||||
|
|
||||||
cs := &CertState{
|
|
||||||
initiatingVersion: cert.Version1,
|
|
||||||
privateKey: []byte{},
|
|
||||||
v1Cert: &dummyCert{version: cert.Version1},
|
|
||||||
v1Credential: nil,
|
|
||||||
}
|
|
||||||
|
|
||||||
lh := newTestLighthouse()
|
|
||||||
ifce := &Interface{
|
|
||||||
hostMap: hostMap,
|
|
||||||
inside: &overlaytest.NoopTun{},
|
|
||||||
outside: &udp.NoopConn{},
|
|
||||||
firewall: &Firewall{},
|
|
||||||
lightHouse: lh,
|
|
||||||
pki: &PKI{},
|
|
||||||
myVpnAddrs: []netip.Addr{netip.MustParseAddr("172.1.1.1")}, // sorts below vpnIp so shouldSwapPrimary can proceed
|
|
||||||
handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
|
|
||||||
l: l,
|
|
||||||
}
|
|
||||||
ifce.pki.cs.Store(cs)
|
|
||||||
|
|
||||||
conf := config.NewC(test.NewLogger())
|
|
||||||
punchy := NewPunchyFromConfig(test.NewLogger(), conf, nil)
|
|
||||||
nc := newConnectionManagerFromConfig(test.NewLogger(), conf, hostMap, punchy)
|
|
||||||
nc.intf = ifce
|
|
||||||
|
|
||||||
hostinfo := &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{vpnIp},
|
|
||||||
localIndexId: 1099,
|
|
||||||
remoteIndexId: 9901,
|
|
||||||
}
|
|
||||||
hostinfo.ConnectionState = &ConnectionState{
|
|
||||||
myCert: &dummyCert{version: cert.Version1},
|
|
||||||
}
|
|
||||||
nc.hostMap.unlockedAddHostInfo(hostinfo, ifce)
|
|
||||||
|
|
||||||
// Below the rehandshake threshold, no handshake is started
|
|
||||||
hostinfo.ConnectionState.messageCounter.Store(RehandshakeAfterMessages - 1)
|
|
||||||
nc.tryRehandshake(hostinfo)
|
|
||||||
assert.Nil(t, ifce.handshakeManager.QueryVpnAddr(vpnIp))
|
|
||||||
|
|
||||||
// A tunnel on its current cert would normally swap to primary
|
|
||||||
assert.True(t, nc.shouldSwapPrimary(hostinfo))
|
|
||||||
|
|
||||||
// At the rehandshake threshold, a new handshake is started
|
|
||||||
hostinfo.ConnectionState.messageCounter.Store(RehandshakeAfterMessages)
|
|
||||||
nc.tryRehandshake(hostinfo)
|
|
||||||
assert.NotNil(t, ifce.handshakeManager.QueryVpnAddr(vpnIp))
|
|
||||||
|
|
||||||
// An exhausted tunnel being rolled must never swap back to primary onto its spent key
|
|
||||||
assert.False(t, nc.shouldSwapPrimary(hostinfo))
|
|
||||||
|
|
||||||
// Still below the reject limit, the tunnel stays up
|
|
||||||
nc.In(hostinfo)
|
|
||||||
decision, _, _ := nc.makeTrafficDecision(hostinfo.localIndexId, time.Now())
|
|
||||||
assert.Equal(t, tryRehandshake, decision)
|
|
||||||
|
|
||||||
// At the reject limit, the tunnel is deleted locally without a doomed CloseTunnel notify
|
|
||||||
hostinfo.ConnectionState.messageCounter.Store(RejectAfterMessages)
|
|
||||||
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, time.Now())
|
|
||||||
assert.Equal(t, deleteTunnel, decision)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_NewConnectionManager_DisconnectInactive(t *testing.T) {
|
func Test_NewConnectionManager_DisconnectInactive(t *testing.T) {
|
||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
localrange := netip.MustParsePrefix("10.1.1.1/24")
|
localrange := netip.MustParsePrefix("10.1.1.1/24")
|
||||||
|
|||||||
+8
-48
@@ -2,7 +2,6 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -13,26 +12,7 @@ import (
|
|||||||
"github.com/slackhq/nebula/noiseutil"
|
"github.com/slackhq/nebula/noiseutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const ReplayWindow = 1024
|
||||||
ReplayWindow = 8192
|
|
||||||
|
|
||||||
// RehandshakeAfterMessages rolls keys inside the AES-GCM data-volume margin (~2^-36 advantage at 64KB frames).
|
|
||||||
RehandshakeAfterMessages = uint64(1) << 34
|
|
||||||
|
|
||||||
// RejectAfterMessages is the nonce ceiling enforced by noiseutil; a tunnel here is deleted locally, not notified.
|
|
||||||
RejectAfterMessages = noiseutil.RejectAfterMessages
|
|
||||||
)
|
|
||||||
|
|
||||||
// RehandshakeAfterMessages must stay below RejectAfterMessages so tunnels roll before the hard send stop.
|
|
||||||
const _ = RejectAfterMessages - RehandshakeAfterMessages
|
|
||||||
|
|
||||||
// sessionEpoch hands out a receiver-local ordinal to every ConnectionState at creation. The RX
|
|
||||||
// staging sort (overlay/batch) orders packets by (epoch, message counter). A re-handshake never
|
|
||||||
// rekeys an existing tunnel; it brings up a new hostinfo and ConnectionState with a counter space
|
|
||||||
// starting near zero, while the old tunnel keeps decrypting until torn down. During that cutover
|
|
||||||
// one flush batch can hold packets from both tunnels, and the epoch keeps the old tunnel's
|
|
||||||
// packets sorted first.
|
|
||||||
var sessionEpoch atomic.Uint64
|
|
||||||
|
|
||||||
type ConnectionState struct {
|
type ConnectionState struct {
|
||||||
eKey noiseutil.CipherState
|
eKey noiseutil.CipherState
|
||||||
@@ -44,20 +24,13 @@ type ConnectionState struct {
|
|||||||
window *Bits
|
window *Bits
|
||||||
decryptLock sync.Mutex
|
decryptLock sync.Mutex
|
||||||
writeLock sync.Mutex
|
writeLock sync.Mutex
|
||||||
// epoch is this session's sessionEpoch ordinal. Immutable after creation.
|
|
||||||
epoch uint64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// newConnectionStateFromResult builds a fully-populated ConnectionState from a
|
// newConnectionStateFromResult builds a fully-populated ConnectionState from a
|
||||||
// completed handshake.Result. It seeds messageCounter and the replay window so
|
// completed handshake.Result. It seeds messageCounter and the replay window so
|
||||||
// that the post-handshake message indices already used on the wire don't count
|
// that the post-handshake message indices already used on the wire don't count
|
||||||
// as missed traffic in the data plane.
|
// as missed traffic in the data plane.
|
||||||
func newConnectionStateFromResult(r *handshake.Result) (*ConnectionState, error) {
|
func newConnectionStateFromResult(r *handshake.Result) *ConnectionState {
|
||||||
// Refuse a MessageIndex too big for the replay window: it can only be a bug, and would spin the seed loop below.
|
|
||||||
if r.MessageIndex >= ReplayWindow {
|
|
||||||
return nil, fmt.Errorf("handshake message index %d exceeds replay window", r.MessageIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
ci := &ConnectionState{
|
ci := &ConnectionState{
|
||||||
myCert: r.MyCert,
|
myCert: r.MyCert,
|
||||||
initiator: r.Initiator,
|
initiator: r.Initiator,
|
||||||
@@ -65,13 +38,12 @@ func newConnectionStateFromResult(r *handshake.Result) (*ConnectionState, error)
|
|||||||
eKey: noiseutil.NewCipherState(r.EKey, r.Cipher),
|
eKey: noiseutil.NewCipherState(r.EKey, r.Cipher),
|
||||||
dKey: noiseutil.NewCipherState(r.DKey, r.Cipher),
|
dKey: noiseutil.NewCipherState(r.DKey, r.Cipher),
|
||||||
window: NewBits(ReplayWindow),
|
window: NewBits(ReplayWindow),
|
||||||
epoch: sessionEpoch.Add(1),
|
|
||||||
}
|
}
|
||||||
ci.messageCounter.Add(r.MessageIndex)
|
ci.messageCounter.Add(r.MessageIndex)
|
||||||
for i := uint64(1); i <= r.MessageIndex; i++ {
|
for i := uint64(1); i <= r.MessageIndex; i++ {
|
||||||
ci.window.Update(nil, i)
|
ci.window.Update(nil, i)
|
||||||
}
|
}
|
||||||
return ci, nil
|
return ci
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
|
func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
|
||||||
@@ -82,21 +54,12 @@ func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// NextMessageCounter reserves the next 1-based counter; RejectAfterMessages is the first we refuse, pinned to not wrap.
|
|
||||||
func (cs *ConnectionState) NextMessageCounter() (uint64, bool) {
|
|
||||||
c := cs.messageCounter.Add(1)
|
|
||||||
if c >= RejectAfterMessages {
|
|
||||||
cs.messageCounter.Store(RejectAfterMessages)
|
|
||||||
return c, false
|
|
||||||
}
|
|
||||||
return c, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cs *ConnectionState) Curve() cert.Curve {
|
func (cs *ConnectionState) Curve() cert.Curve {
|
||||||
return cs.myCert.Curve()
|
return cs.myCert.Curve()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *ConnectionState) Decrypt(l *slog.Logger, messageCounter uint64, packet []byte, nb []byte) ([]byte, error) {
|
func (cs *ConnectionState) Decrypt(l *slog.Logger, messageCounter uint64, out []byte, packet []byte, nb []byte) ([]byte, error) {
|
||||||
|
var err error
|
||||||
cs.decryptLock.Lock()
|
cs.decryptLock.Lock()
|
||||||
result := cs.window.Check(l, messageCounter)
|
result := cs.window.Check(l, messageCounter)
|
||||||
cs.decryptLock.Unlock()
|
cs.decryptLock.Unlock()
|
||||||
@@ -104,7 +67,7 @@ func (cs *ConnectionState) Decrypt(l *slog.Logger, messageCounter uint64, packet
|
|||||||
return nil, ErrAlreadySeen
|
return nil, ErrAlreadySeen
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := cs.dKey.DecryptDanger(packet[header.Len:header.Len], packet[:header.Len], packet[header.Len:], messageCounter, nb)
|
out, err = cs.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -118,6 +81,7 @@ func (cs *ConnectionState) Decrypt(l *slog.Logger, messageCounter uint64, packet
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// VerifyRelay verifies AEAD protected (but not encrypted) relay frames. packet must be length-checked by the caller.
|
||||||
func (cs *ConnectionState) VerifyRelay(l *slog.Logger, messageCounter uint64, packet []byte, nb []byte) error {
|
func (cs *ConnectionState) VerifyRelay(l *slog.Logger, messageCounter uint64, packet []byte, nb []byte) error {
|
||||||
cs.decryptLock.Lock()
|
cs.decryptLock.Lock()
|
||||||
result := cs.window.Check(l, messageCounter)
|
result := cs.window.Check(l, messageCounter)
|
||||||
@@ -126,11 +90,6 @@ func (cs *ConnectionState) VerifyRelay(l *slog.Logger, messageCounter uint64, pa
|
|||||||
return ErrAlreadySeen
|
return ErrAlreadySeen
|
||||||
}
|
}
|
||||||
|
|
||||||
// The entire body is sent as AD, not encrypted.
|
|
||||||
// The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
|
|
||||||
// The packet is guaranteed to be at least 16 bytes at this point, b/c it got past the h.Parse() call above. If it's
|
|
||||||
// otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
|
|
||||||
// which will gracefully fail in the DecryptDanger call.
|
|
||||||
signedPayload := packet[:len(packet)-cs.dKey.Overhead()]
|
signedPayload := packet[:len(packet)-cs.dKey.Overhead()]
|
||||||
signatureValue := packet[len(packet)-cs.dKey.Overhead():]
|
signatureValue := packet[len(packet)-cs.dKey.Overhead():]
|
||||||
_, err := cs.dKey.DecryptDanger(nil, signedPayload, signatureValue, messageCounter, nb)
|
_, err := cs.dKey.DecryptDanger(nil, signedPayload, signatureValue, messageCounter, nb)
|
||||||
@@ -144,5 +103,6 @@ func (cs *ConnectionState) VerifyRelay(l *slog.Logger, messageCounter uint64, pa
|
|||||||
if !result {
|
if !result {
|
||||||
return ErrAlreadySeen
|
return ErrAlreadySeen
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
+2
-199
@@ -2,20 +2,14 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/flynn/noise"
|
"github.com/flynn/noise"
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
ct "github.com/slackhq/nebula/cert_test"
|
ct "github.com/slackhq/nebula/cert_test"
|
||||||
"github.com/slackhq/nebula/handshake"
|
"github.com/slackhq/nebula/handshake"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/overlay"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/slackhq/nebula/udp"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
@@ -85,193 +79,11 @@ func runTestHandshake(t *testing.T) (initR, respR *handshake.Result) {
|
|||||||
return initR, respR
|
return initR, respR
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConnectionState_NextMessageCounter(t *testing.T) {
|
|
||||||
cs := &ConnectionState{}
|
|
||||||
cs.messageCounter.Store(RejectAfterMessages - 2)
|
|
||||||
|
|
||||||
c, ok := cs.NextMessageCounter()
|
|
||||||
assert.True(t, ok)
|
|
||||||
assert.Equal(t, RejectAfterMessages-1, c)
|
|
||||||
|
|
||||||
// Hitting the limit refuses and pins the counter there
|
|
||||||
c, ok = cs.NextMessageCounter()
|
|
||||||
assert.False(t, ok)
|
|
||||||
assert.Equal(t, RejectAfterMessages, c)
|
|
||||||
assert.Equal(t, RejectAfterMessages, cs.messageCounter.Load())
|
|
||||||
|
|
||||||
// Continued send attempts stay refused and the counter never wraps
|
|
||||||
for range 10 {
|
|
||||||
_, ok = cs.NextMessageCounter()
|
|
||||||
assert.False(t, ok)
|
|
||||||
}
|
|
||||||
assert.Equal(t, RejectAfterMessages, cs.messageCounter.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSendNoMetricsDropsExhausted drives the send path to the exhausted drop; metric and out flag prove it.
|
|
||||||
func TestSendNoMetricsDropsExhausted(t *testing.T) {
|
|
||||||
initR, _ := runTestHandshake(t)
|
|
||||||
ci, err := newConnectionStateFromResult(initR)
|
|
||||||
require.NoError(t, err)
|
|
||||||
ci.messageCounter.Store(RejectAfterMessages - 1)
|
|
||||||
|
|
||||||
f := &Interface{l: test.NewLogger(), messageMetrics: &MessageMetrics{txExhausted: metrics.NewCounter()}}
|
|
||||||
hostinfo := &HostInfo{vpnAddrs: []netip.Addr{netip.MustParseAddr("10.0.0.1")}, ConnectionState: ci}
|
|
||||||
|
|
||||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, []byte{}, make([]byte, 12), make([]byte, mtu), 0)
|
|
||||||
|
|
||||||
// The crossing send is refused: it records an exhaustion drop and never reaches connectionManager.Out.
|
|
||||||
assert.Equal(t, int64(1), f.messageMetrics.txExhausted.Count())
|
|
||||||
assert.False(t, hostinfo.sentSinceCheck())
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSendNoMetricsCloseTunnelKeepsRebindEpoch pins that a closing tunnel does not consume a rebind, a later
|
|
||||||
// packet on a re-established tunnel still needs that edge to trigger the far-side punch.
|
|
||||||
func TestSendNoMetricsCloseTunnelKeepsRebindEpoch(t *testing.T) {
|
|
||||||
initR, _ := runTestHandshake(t)
|
|
||||||
ci, err := newConnectionStateFromResult(initR)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
f := &Interface{
|
|
||||||
l: test.NewLogger(),
|
|
||||||
messageMetrics: &MessageMetrics{txExhausted: metrics.NewCounter()},
|
|
||||||
writers: []udp.Conn{udp.NoopConn{}},
|
|
||||||
connectionManager: &connectionManager{},
|
|
||||||
}
|
|
||||||
hostinfo := &HostInfo{vpnAddrs: []netip.Addr{netip.MustParseAddr("10.0.0.1")}, ConnectionState: ci}
|
|
||||||
|
|
||||||
// Tunnel is on epoch 0, then we rebind.
|
|
||||||
hostinfo.markOut(0)
|
|
||||||
f.rebindEpoch.Add(1)
|
|
||||||
|
|
||||||
remote := netip.MustParseAddrPort("10.0.0.2:4242")
|
|
||||||
f.sendNoMetrics(header.CloseTunnel, 0, ci, hostinfo, remote, []byte{}, make([]byte, 12), make([]byte, mtu), 0)
|
|
||||||
|
|
||||||
// markOut at the new epoch still reports the move, so the edge was preserved.
|
|
||||||
assert.True(t, hostinfo.markOut(1), "a CloseTunnel send must not consume the rebind epoch")
|
|
||||||
}
|
|
||||||
|
|
||||||
// capturingConn is a udp.Conn that records every WriteTo.
|
|
||||||
type capturingConn struct {
|
|
||||||
udp.NoopConn
|
|
||||||
writes [][]byte
|
|
||||||
addrs []netip.AddrPort
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *capturingConn) WriteTo(b []byte, addr netip.AddrPort) error {
|
|
||||||
c.writes = append(c.writes, append([]byte(nil), b...))
|
|
||||||
c.addrs = append(c.addrs, addr)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSendNoMetricsViaRelay sends through a relay from the mtu sized buffer the cached packet flush uses. Payloads up
|
|
||||||
// to overlay.MaxMTU go out intact, anything bigger is dropped rather than outgrowing the buffer, which once panicked.
|
|
||||||
func TestSendNoMetricsViaRelay(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
n int
|
|
||||||
sent bool
|
|
||||||
}{
|
|
||||||
{0, true},
|
|
||||||
{1300, true},
|
|
||||||
{overlay.MaxMTU, true},
|
|
||||||
{overlay.MaxMTU + 1, false}, // too big for the relay's tag
|
|
||||||
{mtu - 47, false}, // too big for the inner tag, this panicked
|
|
||||||
{9000, false}, // a full packet at tun.mtu 9000
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(strconv.Itoa(tt.n), func(t *testing.T) {
|
|
||||||
// One tunnel to the target, carried end to end, and one to the relay that wraps it
|
|
||||||
targetInit, targetResp := runTestHandshake(t)
|
|
||||||
relayInit, relayResp := runTestHandshake(t)
|
|
||||||
ci, err := newConnectionStateFromResult(targetInit)
|
|
||||||
require.NoError(t, err)
|
|
||||||
relayCI, err := newConnectionStateFromResult(relayInit)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
targetAddr := netip.MustParseAddr("10.0.0.2")
|
|
||||||
relayAddr := netip.MustParseAddr("10.0.0.3")
|
|
||||||
relayRemote := netip.MustParseAddrPort("192.0.2.1:4242")
|
|
||||||
|
|
||||||
relay := &Relay{Type: TerminalType, State: Established, LocalIndex: 5, RemoteIndex: 6, PeerAddr: targetAddr}
|
|
||||||
relayHI := &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{relayAddr},
|
|
||||||
ConnectionState: relayCI,
|
|
||||||
relayState: RelayState{
|
|
||||||
relayForByAddr: map[netip.Addr]*Relay{targetAddr: relay},
|
|
||||||
relayForByIdx: map[uint32]*Relay{relay.LocalIndex: relay},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
relayHI.remote.Store(&relayRemote)
|
|
||||||
|
|
||||||
// No remote of its own, so the send has to go via the relay
|
|
||||||
hostinfo := &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{targetAddr},
|
|
||||||
ConnectionState: ci,
|
|
||||||
remoteIndexId: 7,
|
|
||||||
relayState: RelayState{
|
|
||||||
relays: []netip.Addr{relayAddr},
|
|
||||||
relayForByAddr: map[netip.Addr]*Relay{},
|
|
||||||
relayForByIdx: map[uint32]*Relay{},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
l := test.NewLogger()
|
|
||||||
hm := newHostMap(l)
|
|
||||||
hm.Hosts[relayAddr] = relayHI
|
|
||||||
conn := &capturingConn{}
|
|
||||||
f := &Interface{
|
|
||||||
l: l,
|
|
||||||
hostMap: hm,
|
|
||||||
messageMetrics: &MessageMetrics{txExhausted: metrics.NewCounter()},
|
|
||||||
writers: []udp.Conn{conn},
|
|
||||||
}
|
|
||||||
f.connectionManager = &connectionManager{intf: f, relayUsed: map[uint32]struct{}{}, relayUsedLock: &sync.RWMutex{}}
|
|
||||||
|
|
||||||
payload := make([]byte, tt.n)
|
|
||||||
for i := range payload {
|
|
||||||
payload[i] = byte(i)
|
|
||||||
}
|
|
||||||
counter := ci.messageCounter.Load()
|
|
||||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, payload, make([]byte, 12), make([]byte, mtu), 0)
|
|
||||||
|
|
||||||
if !tt.sent {
|
|
||||||
assert.Empty(t, conn.writes)
|
|
||||||
assert.Equal(t, counter, ci.messageCounter.Load(), "a dropped packet must not spend a counter")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
require.Len(t, conn.writes, 1)
|
|
||||||
assert.Equal(t, relayRemote, conn.addrs[0])
|
|
||||||
pkt := conn.writes[0]
|
|
||||||
|
|
||||||
// The relay authenticates the whole packet under its own header
|
|
||||||
outer := &header.H{}
|
|
||||||
require.NoError(t, outer.Parse(pkt))
|
|
||||||
assert.Equal(t, header.MessageRelay, outer.Subtype)
|
|
||||||
assert.Equal(t, relay.RemoteIndex, outer.RemoteIndex)
|
|
||||||
relayPeer, err := newConnectionStateFromResult(relayResp)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, relayPeer.VerifyRelay(l, outer.MessageCounter, pkt, make([]byte, 12)))
|
|
||||||
|
|
||||||
// Inside it, the target decrypts the end to end packet back to the payload
|
|
||||||
inner := pkt[header.Len : len(pkt)-relayPeer.dKey.Overhead()]
|
|
||||||
h := &header.H{}
|
|
||||||
require.NoError(t, h.Parse(inner))
|
|
||||||
assert.Equal(t, header.Message, h.Type)
|
|
||||||
assert.Equal(t, hostinfo.remoteIndexId, h.RemoteIndex)
|
|
||||||
targetPeer, err := newConnectionStateFromResult(targetResp)
|
|
||||||
require.NoError(t, err)
|
|
||||||
got, err := targetPeer.Decrypt(l, h.MessageCounter, inner, make([]byte, 12))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, payload, got)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewConnectionStateFromResult(t *testing.T) {
|
func TestNewConnectionStateFromResult(t *testing.T) {
|
||||||
initR, respR := runTestHandshake(t)
|
initR, respR := runTestHandshake(t)
|
||||||
|
|
||||||
t.Run("initiator", func(t *testing.T) {
|
t.Run("initiator", func(t *testing.T) {
|
||||||
ci, err := newConnectionStateFromResult(initR)
|
ci := newConnectionStateFromResult(initR)
|
||||||
require.NoError(t, err)
|
|
||||||
assert.True(t, ci.initiator)
|
assert.True(t, ci.initiator)
|
||||||
assert.Equal(t, initR.MyCert, ci.myCert)
|
assert.Equal(t, initR.MyCert, ci.myCert)
|
||||||
assert.Equal(t, initR.RemoteCert, ci.peerCert)
|
assert.Equal(t, initR.RemoteCert, ci.peerCert)
|
||||||
@@ -290,17 +102,8 @@ func TestNewConnectionStateFromResult(t *testing.T) {
|
|||||||
assert.True(t, ci.window.Check(nil, 3), "counter 3 must not be pre-seeded")
|
assert.True(t, ci.window.Check(nil, 3), "counter 3 must not be pre-seeded")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("message index too large is refused", func(t *testing.T) {
|
|
||||||
bad := *initR
|
|
||||||
bad.MessageIndex = ReplayWindow
|
|
||||||
ci, err := newConnectionStateFromResult(&bad)
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.Nil(t, ci)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("responder", func(t *testing.T) {
|
t.Run("responder", func(t *testing.T) {
|
||||||
ci, err := newConnectionStateFromResult(respR)
|
ci := newConnectionStateFromResult(respR)
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, ci.initiator)
|
assert.False(t, ci.initiator)
|
||||||
assert.Equal(t, respR.MyCert, ci.myCert)
|
assert.Equal(t, respR.MyCert, ci.myCert)
|
||||||
assert.Equal(t, respR.RemoteCert, ci.peerCert)
|
assert.Equal(t, respR.RemoteCert, ci.peerCert)
|
||||||
|
|||||||
+1
-10
@@ -11,7 +11,6 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/overlay"
|
"github.com/slackhq/nebula/overlay"
|
||||||
)
|
)
|
||||||
@@ -48,7 +47,6 @@ type Control struct {
|
|||||||
|
|
||||||
f *Interface
|
f *Interface
|
||||||
l *slog.Logger
|
l *slog.Logger
|
||||||
commands *commands.Registry
|
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
cancel context.CancelFunc
|
cancel context.CancelFunc
|
||||||
sshStart func()
|
sshStart func()
|
||||||
@@ -117,7 +115,7 @@ func (c *Control) Start() error {
|
|||||||
c.lighthouseStart()
|
c.lighthouseStart()
|
||||||
}
|
}
|
||||||
|
|
||||||
c.f.triggerShutdown = func() { go c.Stop() }
|
c.f.triggerShutdown = c.Stop
|
||||||
|
|
||||||
// Start reading packets.
|
// Start reading packets.
|
||||||
c.f.run()
|
c.f.run()
|
||||||
@@ -374,13 +372,6 @@ func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Commands returns the registry the daemon's surfaces serve from. It is the live
|
|
||||||
// registry, not a copy: a command registered on it is served to every ssh session that
|
|
||||||
// starts afterwards. Clone it to run commands without that reach.
|
|
||||||
func (c *Control) Commands() *commands.Registry {
|
|
||||||
return c.commands
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Control) Device() overlay.Device {
|
func (c *Control) Device() overlay.Device {
|
||||||
return c.f.inside
|
return c.f.inside
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-41
@@ -11,8 +11,6 @@ import (
|
|||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/overlay/batch"
|
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
|
||||||
"github.com/slackhq/nebula/routing"
|
"github.com/slackhq/nebula/routing"
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
@@ -32,9 +30,9 @@ func newFakeDevice() *fakeDevice {
|
|||||||
|
|
||||||
// Read blocks until Close like a real tun with no traffic, then reports EOF
|
// Read blocks until Close like a real tun with no traffic, then reports EOF
|
||||||
// the same way a closed device does
|
// the same way a closed device does
|
||||||
func (d *fakeDevice) Read() ([]tio.Packet, error) {
|
func (d *fakeDevice) Read(p []byte) (int, error) {
|
||||||
<-d.closedCh
|
<-d.closedCh
|
||||||
return nil, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *fakeDevice) Write(p []byte) (int, error) { return len(p), nil }
|
func (d *fakeDevice) Write(p []byte) (int, error) { return len(p), nil }
|
||||||
@@ -51,8 +49,10 @@ func (d *fakeDevice) Activate() error { return nil }
|
|||||||
func (d *fakeDevice) Networks() []netip.Prefix { return nil }
|
func (d *fakeDevice) Networks() []netip.Prefix { return nil }
|
||||||
func (d *fakeDevice) Name() string { return "fake" }
|
func (d *fakeDevice) Name() string { return "fake" }
|
||||||
func (d *fakeDevice) RoutesFor(netip.Addr) routing.Gateways { return nil }
|
func (d *fakeDevice) RoutesFor(netip.Addr) routing.Gateways { return nil }
|
||||||
|
func (d *fakeDevice) SupportsMultiqueue() bool { return false }
|
||||||
func (d *fakeDevice) Queues(int) ([]tio.Queue, error) { return []tio.Queue{d}, nil }
|
func (d *fakeDevice) NewMultiQueueReader() (io.ReadWriteCloser, error) {
|
||||||
|
return nil, errors.New("unsupported")
|
||||||
|
}
|
||||||
|
|
||||||
// newReadyControl hand-builds the minimum Control that Main would have
|
// newReadyControl hand-builds the minimum Control that Main would have
|
||||||
// produced right before Start, including the construction token NewInterface
|
// produced right before Start, including the construction token NewInterface
|
||||||
@@ -78,7 +78,7 @@ func newReadyControl(t *testing.T) (*Control, *fakeDevice, *fakeConn) {
|
|||||||
inside: dev,
|
inside: dev,
|
||||||
outside: conn,
|
outside: conn,
|
||||||
writers: []udp.Conn{conn},
|
writers: []udp.Conn{conn},
|
||||||
batchers: make([]*batch.MultiCoalescer, 1),
|
readers: make([]io.ReadWriteCloser, 1),
|
||||||
routines: 1,
|
routines: 1,
|
||||||
hostMap: newHostMap(l),
|
hostMap: newHostMap(l),
|
||||||
lightHouse: lh,
|
lightHouse: lh,
|
||||||
@@ -109,8 +109,7 @@ func TestControl_StopBeforeStart(t *testing.T) {
|
|||||||
require.NoError(t, c.Wait())
|
require.NoError(t, c.Wait())
|
||||||
|
|
||||||
// A stopped control can never be started
|
// A stopped control can never be started
|
||||||
err := c.Start()
|
require.ErrorIs(t, c.Start(), ErrAlreadyStopped)
|
||||||
require.ErrorIs(t, err, ErrAlreadyStopped)
|
|
||||||
|
|
||||||
// A second Stop is a harmless no-op
|
// A second Stop is a harmless no-op
|
||||||
c.Stop()
|
c.Stop()
|
||||||
@@ -144,29 +143,19 @@ type fakeConn struct {
|
|||||||
rebinds int
|
rebinds int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *fakeConn) Rebind() error { c.rebinds++; return nil }
|
func (c *fakeConn) Rebind() error { c.rebinds++; return nil }
|
||||||
func (c *fakeConn) LocalAddr() (netip.AddrPort, error) { return netip.AddrPort{}, nil }
|
func (c *fakeConn) LocalAddr() (netip.AddrPort, error) { return netip.AddrPort{}, nil }
|
||||||
func (c *fakeConn) ListenOut(_ udp.EncReader, _ func()) error { return nil }
|
func (c *fakeConn) ListenOut(_ udp.EncReader) error { return nil }
|
||||||
func (c *fakeConn) WriteTo(_ []byte, _ netip.AddrPort) error { return nil }
|
func (c *fakeConn) WriteTo(_ []byte, _ netip.AddrPort) error { return nil }
|
||||||
func (c *fakeConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
|
func (c *fakeConn) ReloadConfig(_ *config.C) {}
|
||||||
return len(bufs), nil
|
func (c *fakeConn) SupportsMultipleReaders() bool { return true }
|
||||||
}
|
func (c *fakeConn) Close() error { c.closed = true; return nil }
|
||||||
func (c *fakeConn) ReloadConfig(_ *config.C, _ *config.Reload) {}
|
|
||||||
func (c *fakeConn) SupportsMultipleReaders() bool { return true }
|
|
||||||
func (c *fakeConn) Close() error { c.closed = true; return nil }
|
|
||||||
|
|
||||||
type multiqueueDevice struct {
|
type multiqueueDevice struct {
|
||||||
*fakeDevice
|
*fakeDevice
|
||||||
}
|
}
|
||||||
|
|
||||||
// Queues claims multiqueue support but fails to open the second queue,
|
func (d *multiqueueDevice) SupportsMultiqueue() bool { return true }
|
||||||
// exercising the activation error path.
|
|
||||||
func (d *multiqueueDevice) Queues(n int) ([]tio.Queue, error) {
|
|
||||||
if n > 1 {
|
|
||||||
return nil, errors.New("second queue failed to open")
|
|
||||||
}
|
|
||||||
return d.fakeDevice.Queues(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestControl_StartMultiqueueFailureReleases(t *testing.T) {
|
func TestControl_StartMultiqueueFailureReleases(t *testing.T) {
|
||||||
dev := &multiqueueDevice{fakeDevice: newFakeDevice()}
|
dev := &multiqueueDevice{fakeDevice: newFakeDevice()}
|
||||||
@@ -177,7 +166,7 @@ func TestControl_StartMultiqueueFailureReleases(t *testing.T) {
|
|||||||
inside: dev,
|
inside: dev,
|
||||||
outside: conn,
|
outside: conn,
|
||||||
writers: []udp.Conn{conn},
|
writers: []udp.Conn{conn},
|
||||||
batchers: make([]*batch.MultiCoalescer, 2),
|
readers: make([]io.ReadWriteCloser, 2),
|
||||||
routines: 2,
|
routines: 2,
|
||||||
l: test.NewLogger(),
|
l: test.NewLogger(),
|
||||||
}
|
}
|
||||||
@@ -192,8 +181,7 @@ func TestControl_StartMultiqueueFailureReleases(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The second reader fails to open, everything must be released
|
// The second reader fails to open, everything must be released
|
||||||
err := c.Start()
|
require.Error(t, c.Start())
|
||||||
require.Error(t, err)
|
|
||||||
assert.Equal(t, StateStopped, c.State())
|
assert.Equal(t, StateStopped, c.State())
|
||||||
assert.True(t, dev.closed, "the tun device should have been closed")
|
assert.True(t, dev.closed, "the tun device should have been closed")
|
||||||
assert.True(t, conn.closed, "the udp socket should have been closed")
|
assert.True(t, conn.closed, "the udp socket should have been closed")
|
||||||
@@ -247,7 +235,7 @@ func TestControl_ConcurrentStopAndStart(t *testing.T) {
|
|||||||
c, _, _ := newReadyControl(t)
|
c, _, _ := newReadyControl(t)
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
for range 2 {
|
for i := 0; i < 2; i++ {
|
||||||
wg.Go(func() { c.Stop() })
|
wg.Go(func() { c.Stop() })
|
||||||
}
|
}
|
||||||
wg.Go(func() { _ = c.Start() })
|
wg.Go(func() { _ = c.Start() })
|
||||||
@@ -263,18 +251,15 @@ func TestControl_ConcurrentStopAndStart(t *testing.T) {
|
|||||||
// panic and Wait must observe the final state
|
// panic and Wait must observe the final state
|
||||||
require.NoError(t, c.Wait())
|
require.NoError(t, c.Wait())
|
||||||
assert.Equal(t, StateStopped, c.State())
|
assert.Equal(t, StateStopped, c.State())
|
||||||
err := c.Start()
|
require.ErrorIs(t, c.Start(), ErrAlreadyStopped)
|
||||||
require.ErrorIs(t, err, ErrAlreadyStopped)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestControl_StartStopLifecycle(t *testing.T) {
|
func TestControl_StartStopLifecycle(t *testing.T) {
|
||||||
c, dev, conn := newReadyControl(t)
|
c, dev, conn := newReadyControl(t)
|
||||||
|
|
||||||
err := c.Start()
|
require.NoError(t, c.Start())
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, StateStarted, c.State())
|
assert.Equal(t, StateStarted, c.State())
|
||||||
err = c.Start()
|
require.ErrorIs(t, c.Start(), ErrAlreadyStarted)
|
||||||
require.ErrorIs(t, err, ErrAlreadyStarted)
|
|
||||||
|
|
||||||
// Stop must unpark the reader blocked in the device and release everything
|
// Stop must unpark the reader blocked in the device and release everything
|
||||||
c.Stop()
|
c.Stop()
|
||||||
@@ -285,8 +270,7 @@ func TestControl_StartStopLifecycle(t *testing.T) {
|
|||||||
|
|
||||||
// The reader drained off a closed device, that is not a fatal error
|
// The reader drained off a closed device, that is not a fatal error
|
||||||
require.NoError(t, c.Wait())
|
require.NoError(t, c.Wait())
|
||||||
err = c.Start()
|
require.ErrorIs(t, c.Start(), ErrAlreadyStopped)
|
||||||
require.ErrorIs(t, err, ErrAlreadyStopped)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestControl_RebindIsGatedByState(t *testing.T) {
|
func TestControl_RebindIsGatedByState(t *testing.T) {
|
||||||
@@ -296,8 +280,7 @@ func TestControl_RebindIsGatedByState(t *testing.T) {
|
|||||||
c.RebindUDPServer()
|
c.RebindUDPServer()
|
||||||
assert.Equal(t, 0, conn.rebinds, "rebind before start must be a no-op")
|
assert.Equal(t, 0, conn.rebinds, "rebind before start must be a no-op")
|
||||||
|
|
||||||
err := c.Start()
|
require.NoError(t, c.Start())
|
||||||
require.NoError(t, err)
|
|
||||||
c.RebindUDPServer()
|
c.RebindUDPServer()
|
||||||
assert.Equal(t, 1, conn.rebinds, "rebind while started must reach the conn")
|
assert.Equal(t, 1, conn.rebinds, "rebind while started must reach the conn")
|
||||||
|
|
||||||
|
|||||||
@@ -123,16 +123,6 @@ func (c *Control) SetLocalAddrsFn(fn func(*LocalAllowList) []netip.Addr) {
|
|||||||
c.f.lightHouse.localAddrsFn = fn
|
c.f.lightHouse.localAddrsFn = fn
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRebindEpochFor returns the rebind epoch a tunnel last sent under, so a test can tell whether a send
|
|
||||||
// consumed the epoch edge without having to infer it from lighthouse traffic.
|
|
||||||
func (c *Control) GetRebindEpochFor(vpnAddr netip.Addr) (uint32, bool) {
|
|
||||||
h := c.f.hostMap.QueryVpnAddr(vpnAddr)
|
|
||||||
if h == nil {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
return h.state.Load() >> stateEpochShift, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Control) KillPendingTunnel(vpnIp netip.Addr) bool {
|
func (c *Control) KillPendingTunnel(vpnIp netip.Addr) bool {
|
||||||
hostinfo := c.f.handshakeManager.QueryVpnAddr(vpnIp)
|
hostinfo := c.f.handshakeManager.QueryVpnAddr(vpnIp)
|
||||||
if hostinfo == nil {
|
if hostinfo == nil {
|
||||||
|
|||||||
@@ -1,187 +0,0 @@
|
|||||||
// Package cpupick chooses which CPUs the tun reader threads pin to when the
|
|
||||||
// operator has not chosen for us (tun.cpu_affinity). The stock spread —
|
|
||||||
// allowed[i] for routine i — has two failure modes this package exists to fix:
|
|
||||||
//
|
|
||||||
// - every co-located nebula starts its spread at allowed[0], so N instances
|
|
||||||
// on one box stack their readers onto the same cores, and allowed[0] is
|
|
||||||
// usually CPU 0, the core housekeeping and default IRQ affinity already
|
|
||||||
// favor;
|
|
||||||
// - on heterogeneous CPUs (ARM big.LITTLE, Intel P/E hybrids, AMD compact
|
|
||||||
// cores) low IDs are not necessarily fast cores, and pinning an encrypt
|
|
||||||
// thread to an efficiency core caps that queue's throughput.
|
|
||||||
//
|
|
||||||
// Default instead returns a preference-ordered pin list: the allowed set
|
|
||||||
// filtered to performance cores (when the platform distinguishes them and
|
|
||||||
// enough remain for every routine), confined to a single NUMA node and spread
|
|
||||||
// across distinct physical cores when the topology permits, CPU 0's physical
|
|
||||||
// core demoted to last resort, and the order rotated by a stable per-instance
|
|
||||||
// key so co-located instances spread instead of stacking.
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log/slog"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
// topology is the slice of machine layout arrange consults: the NUMA node
|
|
||||||
// and the physical core behind each candidate CPU, plus which core CPU 0
|
|
||||||
// lives on (zeroCore, -1 when unknown — tracked separately because CPU 0's
|
|
||||||
// SMT sibling deserves demotion even when CPU 0 itself isn't a candidate).
|
|
||||||
// Probed from sysfs on Linux; flatTopology stands in when the platform can't
|
|
||||||
// say, which turns every topology rule into a no-op rather than a wrong
|
|
||||||
// answer.
|
|
||||||
type topology struct {
|
|
||||||
nodeOf map[int]int
|
|
||||||
coreOf map[int]int
|
|
||||||
zeroCore int
|
|
||||||
}
|
|
||||||
|
|
||||||
// flatTopology places every CPU on node 0 and on a physical core of its own.
|
|
||||||
func flatTopology(cpus []int) topology {
|
|
||||||
t := topology{
|
|
||||||
nodeOf: make(map[int]int, len(cpus)),
|
|
||||||
coreOf: make(map[int]int, len(cpus)),
|
|
||||||
zeroCore: -1,
|
|
||||||
}
|
|
||||||
for i, c := range cpus {
|
|
||||||
t.nodeOf[c] = 0
|
|
||||||
t.coreOf[c] = i
|
|
||||||
if c == 0 {
|
|
||||||
t.zeroCore = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default computes the pin order for `routines` tun readers. key is any
|
|
||||||
// stable per-instance value; the bound UDP port is ideal — distinct across
|
|
||||||
// co-located instances, stable across restarts so benchmark runs stay
|
|
||||||
// comparable. Returns nil when there is nothing useful to say (no affinity
|
|
||||||
// support on this platform, lookup failure); callers keep their existing
|
|
||||||
// fallback spread.
|
|
||||||
func Default(routines int, key uint64, l *slog.Logger) []int {
|
|
||||||
allowed, err := util.AllowedCPUs()
|
|
||||||
if err != nil || len(allowed) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
perf, signal := perfCPUs(allowed)
|
|
||||||
cands := pickCandidates(allowed, perf, routines)
|
|
||||||
if len(cands) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if len(perf) < routines {
|
|
||||||
signal = ""
|
|
||||||
}
|
|
||||||
cpus := arrange(cands, readTopology(cands), routines, splitmix64(key))
|
|
||||||
if l != nil {
|
|
||||||
l.Info("chose default pin CPUs for tun readers",
|
|
||||||
"cpus", cpus[:min(routines, len(cpus))],
|
|
||||||
"perfSignal", signal)
|
|
||||||
}
|
|
||||||
return cpus
|
|
||||||
}
|
|
||||||
|
|
||||||
// pickCandidates applies the enough-for-everyone guard: a perf filter that
|
|
||||||
// leaves fewer candidates than routines is discarded — giving every reader
|
|
||||||
// its own (possibly slow) core beats stacking two readers on a fast one.
|
|
||||||
func pickCandidates(allowed, perf []int, routines int) []int {
|
|
||||||
if len(perf) < routines {
|
|
||||||
return allowed
|
|
||||||
}
|
|
||||||
return perf
|
|
||||||
}
|
|
||||||
|
|
||||||
// arrange turns the candidate set into the final pin order:
|
|
||||||
//
|
|
||||||
// 1. NUMA: when at least one node holds enough candidates for every
|
|
||||||
// routine, confine to one such node, chosen by the instance hash. The
|
|
||||||
// readers share hostmap and cipher state, so splitting one instance
|
|
||||||
// across nodes taxes every packet — and co-located instances that hash
|
|
||||||
// to different nodes stop competing entirely. When no node is big
|
|
||||||
// enough, span nodes rather than stack readers.
|
|
||||||
// 2. Rotate the preferred candidates by the hash so instances spread.
|
|
||||||
// 3. SMT: emit one thread per physical core before any of their siblings —
|
|
||||||
// two encrypt threads on one core split its execution units. Siblings
|
|
||||||
// still follow for the routines > cores case.
|
|
||||||
// 4. CPU 0's whole physical core goes last: housekeeping and default IRQ
|
|
||||||
// noise on CPU 0 bleeds into its SMT sibling too. Within that tail the
|
|
||||||
// sibling precedes CPU 0 itself, which only catches the bleed-through.
|
|
||||||
//
|
|
||||||
// The rotation happens before the SMT pass so each instance's one-per-core
|
|
||||||
// walk also starts at a different core, and CPU 0's core is excluded from
|
|
||||||
// the rotation so no hash value can put it back at the front.
|
|
||||||
func arrange(cands []int, topo topology, routines int, h uint64) []int {
|
|
||||||
byNode := map[int][]int{}
|
|
||||||
var nodes []int
|
|
||||||
for _, c := range cands {
|
|
||||||
n := topo.nodeOf[c]
|
|
||||||
if _, ok := byNode[n]; !ok {
|
|
||||||
nodes = append(nodes, n)
|
|
||||||
}
|
|
||||||
byNode[n] = append(byNode[n], c)
|
|
||||||
}
|
|
||||||
var eligible []int
|
|
||||||
for _, n := range nodes {
|
|
||||||
if len(byNode[n]) >= routines {
|
|
||||||
eligible = append(eligible, n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(eligible) > 0 {
|
|
||||||
cands = byNode[eligible[int(h%uint64(len(eligible)))]]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Split off CPU 0's core: its siblings tail the list, CPU 0 tails them.
|
|
||||||
preferred := make([]int, 0, len(cands))
|
|
||||||
var zeroTail []int
|
|
||||||
hasZero := false
|
|
||||||
for _, c := range cands {
|
|
||||||
switch {
|
|
||||||
case c == 0:
|
|
||||||
hasZero = true
|
|
||||||
case topo.zeroCore >= 0 && topo.coreOf[c] == topo.zeroCore:
|
|
||||||
zeroTail = append(zeroTail, c)
|
|
||||||
default:
|
|
||||||
preferred = append(preferred, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if hasZero {
|
|
||||||
zeroTail = append(zeroTail, 0)
|
|
||||||
}
|
|
||||||
if len(preferred) == 0 {
|
|
||||||
return zeroTail // CPU 0's core is all we have
|
|
||||||
}
|
|
||||||
|
|
||||||
// The node pick consumed the low hash bits; rotate by the high ones so
|
|
||||||
// the two choices stay independent.
|
|
||||||
off := int((h >> 32) % uint64(len(preferred)))
|
|
||||||
rot := make([]int, 0, len(preferred))
|
|
||||||
rot = append(rot, preferred[off:]...)
|
|
||||||
rot = append(rot, preferred[:off]...)
|
|
||||||
|
|
||||||
seenCore := make(map[int]bool, len(rot))
|
|
||||||
out := make([]int, 0, len(cands))
|
|
||||||
var siblings []int
|
|
||||||
for _, c := range rot {
|
|
||||||
g := topo.coreOf[c]
|
|
||||||
if seenCore[g] {
|
|
||||||
siblings = append(siblings, c)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
seenCore[g] = true
|
|
||||||
out = append(out, c)
|
|
||||||
}
|
|
||||||
out = append(out, siblings...)
|
|
||||||
out = append(out, zeroTail...)
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// splitmix64 decorrelates instance keys before the selection modulos: ports
|
|
||||||
// on one box often share spacing (4242/4243, or round steps like +1000) that
|
|
||||||
// raw key%len arithmetic would fold onto the same offset.
|
|
||||||
func splitmix64(x uint64) uint64 {
|
|
||||||
x += 0x9e3779b97f4a7c15
|
|
||||||
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9
|
|
||||||
x = (x ^ (x >> 27)) * 0x94d049bb133111eb
|
|
||||||
return x ^ (x >> 31)
|
|
||||||
}
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
package cpupick
|
|
||||||
|
|
||||||
import (
|
|
||||||
"slices"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// pairTopo builds a topology where consecutive candidate pairs are SMT
|
|
||||||
// siblings: (cpus[0],cpus[1]) share a core, (cpus[2],cpus[3]) the next, ...
|
|
||||||
// All CPUs land on node 0.
|
|
||||||
func pairTopo(cpus []int) topology {
|
|
||||||
t := topology{
|
|
||||||
nodeOf: make(map[int]int, len(cpus)),
|
|
||||||
coreOf: make(map[int]int, len(cpus)),
|
|
||||||
zeroCore: -1,
|
|
||||||
}
|
|
||||||
for i, c := range cpus {
|
|
||||||
t.nodeOf[c] = 0
|
|
||||||
t.coreOf[c] = i / 2
|
|
||||||
if c == 0 {
|
|
||||||
t.zeroCore = i / 2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return t
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeDemotesZeroForEveryKey(t *testing.T) {
|
|
||||||
candidates := []int{0, 1, 2, 3, 4, 5, 6, 7}
|
|
||||||
for key := range uint64(64) {
|
|
||||||
got := arrange(candidates, flatTopology(candidates), 4, splitmix64(key))
|
|
||||||
if len(got) != len(candidates) {
|
|
||||||
t.Fatalf("key %d: len=%d want %d", key, len(got), len(candidates))
|
|
||||||
}
|
|
||||||
if got[0] == 0 {
|
|
||||||
t.Errorf("key %d: CPU 0 at the front: %v", key, got)
|
|
||||||
}
|
|
||||||
if got[len(got)-1] != 0 {
|
|
||||||
t.Errorf("key %d: CPU 0 not demoted to last: %v", key, got)
|
|
||||||
}
|
|
||||||
sorted := slices.Clone(got)
|
|
||||||
slices.Sort(sorted)
|
|
||||||
if !slices.Equal(sorted, candidates) {
|
|
||||||
t.Errorf("key %d: not a permutation: %v", key, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeDemotesZeroSiblings(t *testing.T) {
|
|
||||||
// Pairs (0,1),(2,3),(4,5),(6,7): CPU 0's core — 0 and its sibling 1 —
|
|
||||||
// must tail the list, sibling ahead of 0 itself.
|
|
||||||
candidates := []int{0, 1, 2, 3, 4, 5, 6, 7}
|
|
||||||
for key := range uint64(64) {
|
|
||||||
got := arrange(candidates, pairTopo(candidates), 2, splitmix64(key))
|
|
||||||
n := len(got)
|
|
||||||
if got[n-1] != 0 || got[n-2] != 1 {
|
|
||||||
t.Fatalf("key %d: tail = %v, want [... 1 0]", key, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeZeroSiblingWithoutZero(t *testing.T) {
|
|
||||||
// CPU 0 excluded (cpuset) but its sibling 1 remains: the sibling still
|
|
||||||
// tails the list when the topology knows which core CPU 0 lives on.
|
|
||||||
candidates := []int{1, 2, 3, 4, 5}
|
|
||||||
topo := pairTopo([]int{0, 1, 2, 3, 4, 5})
|
|
||||||
got := arrange(candidates, topo, 2, splitmix64(7))
|
|
||||||
if got[len(got)-1] != 1 {
|
|
||||||
t.Errorf("CPU 0's sibling not demoted: %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeRotatesByKey(t *testing.T) {
|
|
||||||
candidates := []int{1, 2, 3, 4, 5, 6, 7, 8}
|
|
||||||
seen := map[int]bool{}
|
|
||||||
for key := range uint64(64) {
|
|
||||||
seen[arrange(candidates, flatTopology(candidates), 4, splitmix64(key))[0]] = true
|
|
||||||
}
|
|
||||||
// 64 hashed keys over 8 slots must hit more than one starting CPU, or
|
|
||||||
// co-located instances would all stack again.
|
|
||||||
if len(seen) < 2 {
|
|
||||||
t.Errorf("rotation never varied across keys: %v", seen)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeStableForSameKey(t *testing.T) {
|
|
||||||
candidates := []int{0, 2, 4, 6}
|
|
||||||
topo := flatTopology(candidates)
|
|
||||||
a := arrange(candidates, topo, 2, splitmix64(4242))
|
|
||||||
b := arrange(candidates, topo, 2, splitmix64(4242))
|
|
||||||
if !slices.Equal(a, b) {
|
|
||||||
t.Errorf("same key ordered differently: %v vs %v", a, b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeZeroOnly(t *testing.T) {
|
|
||||||
if got := arrange([]int{0}, flatTopology([]int{0}), 1, splitmix64(7)); !slices.Equal(got, []int{0}) {
|
|
||||||
t.Errorf("sole CPU 0 must survive: %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeSMTSiblingsLast(t *testing.T) {
|
|
||||||
// Pairs (1,2),(3,4),(5,6),(7,8): the first four picks must cover four
|
|
||||||
// distinct physical cores before any sibling repeats.
|
|
||||||
candidates := []int{1, 2, 3, 4, 5, 6, 7, 8}
|
|
||||||
topo := pairTopo(candidates)
|
|
||||||
for key := range uint64(16) {
|
|
||||||
got := arrange(candidates, topo, 4, splitmix64(key))
|
|
||||||
seen := map[int]bool{}
|
|
||||||
for _, c := range got[:4] {
|
|
||||||
g := topo.coreOf[c]
|
|
||||||
if seen[g] {
|
|
||||||
t.Fatalf("key %d: sibling before all cores covered: %v", key, got)
|
|
||||||
}
|
|
||||||
seen[g] = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeNUMAConfinesToOneNode(t *testing.T) {
|
|
||||||
// Two nodes of four; both fit routines=3, so the result must sit
|
|
||||||
// entirely inside one of them, and the hash must pick both across keys.
|
|
||||||
candidates := []int{1, 2, 3, 4, 10, 11, 12, 13}
|
|
||||||
topo := flatTopology(candidates)
|
|
||||||
for _, c := range []int{10, 11, 12, 13} {
|
|
||||||
topo.nodeOf[c] = 1
|
|
||||||
}
|
|
||||||
nodesSeen := map[int]bool{}
|
|
||||||
for key := range uint64(32) {
|
|
||||||
got := arrange(candidates, topo, 3, splitmix64(key))
|
|
||||||
if len(got) != 4 {
|
|
||||||
t.Fatalf("key %d: not confined to one node: %v", key, got)
|
|
||||||
}
|
|
||||||
n := topo.nodeOf[got[0]]
|
|
||||||
for _, c := range got {
|
|
||||||
if topo.nodeOf[c] != n {
|
|
||||||
t.Fatalf("key %d: spans nodes: %v", key, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
nodesSeen[n] = true
|
|
||||||
}
|
|
||||||
if len(nodesSeen) != 2 {
|
|
||||||
t.Errorf("hash never spread instances across nodes: %v", nodesSeen)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestArrangeNUMASpansWhenNoNodeFits(t *testing.T) {
|
|
||||||
candidates := []int{1, 2, 3, 4, 10, 11, 12, 13}
|
|
||||||
topo := flatTopology(candidates)
|
|
||||||
for _, c := range []int{10, 11, 12, 13} {
|
|
||||||
topo.nodeOf[c] = 1
|
|
||||||
}
|
|
||||||
got := arrange(candidates, topo, 6, splitmix64(1))
|
|
||||||
if len(got) != len(candidates) {
|
|
||||||
t.Errorf("undersized nodes must span, got %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPickCandidates(t *testing.T) {
|
|
||||||
allowed := []int{0, 1, 2, 3, 4, 5, 6, 7}
|
|
||||||
perf := []int{4, 5}
|
|
||||||
|
|
||||||
// Enough perf cores for every routine: only they are used.
|
|
||||||
if got := pickCandidates(allowed, perf, 2); !slices.Equal(got, perf) {
|
|
||||||
t.Errorf("perf filter not applied: %v", got)
|
|
||||||
}
|
|
||||||
// Perf filter too small for the routine count: discarded, everyone
|
|
||||||
// gets their own core from the full allowed set.
|
|
||||||
if got := pickCandidates(allowed, perf, 4); !slices.Equal(got, allowed) {
|
|
||||||
t.Errorf("undersized perf filter not discarded: %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
//go:build linux
|
|
||||||
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// capacityKeepPct is the cpu_capacity admission threshold, relative to the
|
|
||||||
// fastest allowed core. LITTLE cores are normalized to ~250-400 of the big
|
|
||||||
// core's 1024 while mid cores sit at ~75%+, so half of max separates little
|
|
||||||
// from the rest without splitting prime from mid on three-tier parts.
|
|
||||||
const capacityKeepPct = 50
|
|
||||||
|
|
||||||
// freqKeepPct is the cpuinfo_max_freq admission threshold. Favored-core
|
|
||||||
// turbo skew is 2-4% and ARM mid-vs-prime ~12%, while E-cores, LITTLE
|
|
||||||
// cores, and AMD compact cores all sit >= 20% below their siblings' max.
|
|
||||||
const freqKeepPct = 85
|
|
||||||
|
|
||||||
// perfCPUs partitions allowed into the subset that are "performance" cores,
|
|
||||||
// consulting (in order of authority):
|
|
||||||
//
|
|
||||||
// 1. cpu_capacity — arch_topology's normalized per-CPU capacity, exposed on
|
|
||||||
// arm/arm64/riscv; the scheduler's own view of big vs LITTLE.
|
|
||||||
// 2. /sys/devices/cpu_core/cpus — the Intel hybrid P-core PMU mask, present
|
|
||||||
// only on P/E parts (x86 has no cpu_capacity) and naming P cores outright.
|
|
||||||
// 3. cpuinfo_max_freq — the cross-vendor fallback; catches AMD compact
|
|
||||||
// cores, which neither of the above covers.
|
|
||||||
//
|
|
||||||
// Returns allowed unchanged (signal "") when nothing distinguishes the
|
|
||||||
// cores: homogeneous parts, VMs without cpufreq, sysfs unavailable.
|
|
||||||
func perfCPUs(allowed []int) ([]int, string) {
|
|
||||||
return perfCPUsFrom("/sys/devices/system/cpu", "/sys/devices/cpu_core/cpus", allowed)
|
|
||||||
}
|
|
||||||
|
|
||||||
func perfCPUsFrom(cpuDir, intelCoreMask string, allowed []int) ([]int, string) {
|
|
||||||
if cpus, ok := byPerCPUValue(cpuDir, "cpu_capacity", allowed, capacityKeepPct); ok {
|
|
||||||
return cpus, "cpu_capacity"
|
|
||||||
}
|
|
||||||
if cpus, ok := byIntelCoreMask(intelCoreMask, allowed); ok {
|
|
||||||
return cpus, "intel_core_pmu"
|
|
||||||
}
|
|
||||||
if cpus, ok := byPerCPUValue(cpuDir, "cpufreq/cpuinfo_max_freq", allowed, freqKeepPct); ok {
|
|
||||||
return cpus, "max_freq"
|
|
||||||
}
|
|
||||||
return allowed, ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// byPerCPUValue keeps the allowed CPUs whose per-CPU sysfs value is at least
|
|
||||||
// keepPct percent of the maximum across allowed. Inconclusive (ok=false)
|
|
||||||
// when any CPU is missing the file or when every value is equal.
|
|
||||||
func byPerCPUValue(cpuDir, file string, allowed []int, keepPct int) ([]int, bool) {
|
|
||||||
vals := make([]int, len(allowed))
|
|
||||||
minV, maxV := 0, 0
|
|
||||||
for i, cpu := range allowed {
|
|
||||||
v, err := readIntFile(filepath.Join(cpuDir, fmt.Sprintf("cpu%d", cpu), file))
|
|
||||||
if err != nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
vals[i] = v
|
|
||||||
if i == 0 || v < minV {
|
|
||||||
minV = v
|
|
||||||
}
|
|
||||||
if v > maxV {
|
|
||||||
maxV = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if minV == maxV {
|
|
||||||
return nil, false // homogeneous by this signal; try the next one
|
|
||||||
}
|
|
||||||
keep := make([]int, 0, len(allowed))
|
|
||||||
for i, cpu := range allowed {
|
|
||||||
if vals[i]*100 >= maxV*keepPct {
|
|
||||||
keep = append(keep, cpu)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return keep, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// byIntelCoreMask keeps the allowed CPUs named by the hybrid P-core PMU
|
|
||||||
// mask. Inconclusive when the file is absent (non-hybrid x86, other arches)
|
|
||||||
// or no allowed CPU is in the mask (the process was deliberately confined
|
|
||||||
// to E-cores; nothing useful to prefer within that).
|
|
||||||
func byIntelCoreMask(maskPath string, allowed []int) ([]int, bool) {
|
|
||||||
b, err := os.ReadFile(maskPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
set, err := parseCPUList(strings.TrimSpace(string(b)))
|
|
||||||
if err != nil || len(set) == 0 {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
pcore := make(map[int]bool, len(set))
|
|
||||||
for _, c := range set {
|
|
||||||
pcore[c] = true
|
|
||||||
}
|
|
||||||
keep := make([]int, 0, len(allowed))
|
|
||||||
for _, cpu := range allowed {
|
|
||||||
if pcore[cpu] {
|
|
||||||
keep = append(keep, cpu)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(keep) == 0 {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return keep, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseCPUList decodes the kernel's cpulist format ("0-7,16-23", "3") into
|
|
||||||
// individual CPU IDs. Empty input yields an empty list.
|
|
||||||
func parseCPUList(s string) ([]int, error) {
|
|
||||||
if s == "" {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
var out []int
|
|
||||||
for part := range strings.SplitSeq(s, ",") {
|
|
||||||
part = strings.TrimSpace(part)
|
|
||||||
if part == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
lo, hi, isRange := strings.Cut(part, "-")
|
|
||||||
a, err := strconv.Atoi(lo)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("bad cpulist entry %q: %w", part, err)
|
|
||||||
}
|
|
||||||
if !isRange {
|
|
||||||
out = append(out, a)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
b, err := strconv.Atoi(hi)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("bad cpulist entry %q: %w", part, err)
|
|
||||||
}
|
|
||||||
if b < a || b-a > 8192 {
|
|
||||||
return nil, fmt.Errorf("bad cpulist range %q", part)
|
|
||||||
}
|
|
||||||
for v := a; v <= b; v++ {
|
|
||||||
out = append(out, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readIntFile(path string) (int, error) {
|
|
||||||
b, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return strconv.Atoi(strings.TrimSpace(string(b)))
|
|
||||||
}
|
|
||||||
@@ -1,163 +0,0 @@
|
|||||||
//go:build linux
|
|
||||||
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"slices"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fakeSysfs builds a cpuDir tree with the given per-CPU file values.
|
|
||||||
// A nil map for a file means "file absent on every CPU".
|
|
||||||
func fakeSysfs(t *testing.T, capacity, maxFreq map[int]int) string {
|
|
||||||
t.Helper()
|
|
||||||
dir := t.TempDir()
|
|
||||||
write := func(cpu int, rel string, v int) {
|
|
||||||
p := filepath.Join(dir, fmt.Sprintf("cpu%d", cpu), rel)
|
|
||||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(p, fmt.Appendf(nil, "%d\n", v), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for cpu, v := range capacity {
|
|
||||||
write(cpu, "cpu_capacity", v)
|
|
||||||
}
|
|
||||||
for cpu, v := range maxFreq {
|
|
||||||
write(cpu, "cpufreq/cpuinfo_max_freq", v)
|
|
||||||
}
|
|
||||||
return dir
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeCoreMask(t *testing.T, mask string) string {
|
|
||||||
t.Helper()
|
|
||||||
p := filepath.Join(t.TempDir(), "cpus")
|
|
||||||
if err := os.WriteFile(p, []byte(mask+"\n"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsBigLittleCapacity(t *testing.T) {
|
|
||||||
// 4 big (1024) + 4 LITTLE (~290): capacity is authoritative on ARM.
|
|
||||||
dir := fakeSysfs(t, map[int]int{
|
|
||||||
0: 1024, 1: 1024, 2: 1024, 3: 1024,
|
|
||||||
4: 290, 5: 290, 6: 290, 7: 290,
|
|
||||||
}, nil)
|
|
||||||
got, signal := perfCPUsFrom(dir, filepath.Join(dir, "nope"), []int{0, 1, 2, 3, 4, 5, 6, 7})
|
|
||||||
if signal != "cpu_capacity" {
|
|
||||||
t.Fatalf("signal = %q", signal)
|
|
||||||
}
|
|
||||||
if !slices.Equal(got, []int{0, 1, 2, 3}) {
|
|
||||||
t.Errorf("got %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsThreeTierKeepsMid(t *testing.T) {
|
|
||||||
// prime (1024) + mid (~780) + little (~280): 50% keeps prime+mid.
|
|
||||||
dir := fakeSysfs(t, map[int]int{
|
|
||||||
0: 280, 1: 280, 2: 280, 3: 280,
|
|
||||||
4: 780, 5: 780, 6: 780,
|
|
||||||
7: 1024,
|
|
||||||
}, nil)
|
|
||||||
got, _ := perfCPUsFrom(dir, filepath.Join(dir, "nope"), []int{0, 1, 2, 3, 4, 5, 6, 7})
|
|
||||||
if !slices.Equal(got, []int{4, 5, 6, 7}) {
|
|
||||||
t.Errorf("got %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsIntelHybridMask(t *testing.T) {
|
|
||||||
// No cpu_capacity on x86; the P-core PMU mask decides.
|
|
||||||
dir := fakeSysfs(t, nil, nil)
|
|
||||||
mask := writeCoreMask(t, "0-7")
|
|
||||||
got, signal := perfCPUsFrom(dir, mask, []int{0, 1, 2, 3, 8, 9, 10, 11})
|
|
||||||
if signal != "intel_core_pmu" {
|
|
||||||
t.Fatalf("signal = %q", signal)
|
|
||||||
}
|
|
||||||
if !slices.Equal(got, []int{0, 1, 2, 3}) {
|
|
||||||
t.Errorf("got %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsIntelMaskDisjointFallsThrough(t *testing.T) {
|
|
||||||
// Confined to E-cores only: the mask can't help, and equal freqs below
|
|
||||||
// mean nothing else distinguishes them either -> allowed unchanged.
|
|
||||||
dir := fakeSysfs(t, nil, map[int]int{8: 4300000, 9: 4300000})
|
|
||||||
mask := writeCoreMask(t, "0-7")
|
|
||||||
got, signal := perfCPUsFrom(dir, mask, []int{8, 9})
|
|
||||||
if signal != "" || !slices.Equal(got, []int{8, 9}) {
|
|
||||||
t.Errorf("got %v signal %q", got, signal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsMaxFreqCompactCores(t *testing.T) {
|
|
||||||
// AMD-style compact cores: no capacity, no Intel mask; 3.3 vs 5.7 GHz.
|
|
||||||
dir := fakeSysfs(t, nil, map[int]int{
|
|
||||||
0: 5700000, 1: 5700000, 2: 3300000, 3: 3300000,
|
|
||||||
})
|
|
||||||
got, signal := perfCPUsFrom(dir, filepath.Join(dir, "nope"), []int{0, 1, 2, 3})
|
|
||||||
if signal != "max_freq" {
|
|
||||||
t.Fatalf("signal = %q", signal)
|
|
||||||
}
|
|
||||||
if !slices.Equal(got, []int{0, 1}) {
|
|
||||||
t.Errorf("got %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsFavoredCoreSkewKept(t *testing.T) {
|
|
||||||
// Turbo Boost Max favored cores run a few percent hot; they must not
|
|
||||||
// shrink the candidate set to one or two cores.
|
|
||||||
dir := fakeSysfs(t, nil, map[int]int{
|
|
||||||
0: 5800000, 1: 5700000, 2: 5700000, 3: 5600000,
|
|
||||||
})
|
|
||||||
got, _ := perfCPUsFrom(dir, filepath.Join(dir, "nope"), []int{0, 1, 2, 3})
|
|
||||||
if !slices.Equal(got, []int{0, 1, 2, 3}) {
|
|
||||||
t.Errorf("favored-core skew filtered CPUs: %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsHomogeneousInconclusive(t *testing.T) {
|
|
||||||
dir := fakeSysfs(t, nil, map[int]int{0: 3000000, 1: 3000000})
|
|
||||||
got, signal := perfCPUsFrom(dir, filepath.Join(dir, "nope"), []int{0, 1})
|
|
||||||
if signal != "" || !slices.Equal(got, []int{0, 1}) {
|
|
||||||
t.Errorf("got %v signal %q", got, signal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPerfCPUsNoSysfs(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
got, signal := perfCPUsFrom(dir, filepath.Join(dir, "nope"), []int{0, 1, 2})
|
|
||||||
if signal != "" || !slices.Equal(got, []int{0, 1, 2}) {
|
|
||||||
t.Errorf("got %v signal %q", got, signal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParseCPUList(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
in string
|
|
||||||
want []int
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"0-3", []int{0, 1, 2, 3}, false},
|
|
||||||
{"0-1,16-17", []int{0, 1, 16, 17}, false},
|
|
||||||
{"5", []int{5}, false},
|
|
||||||
{"", nil, false},
|
|
||||||
{"3-1", nil, true},
|
|
||||||
{"a-b", nil, true},
|
|
||||||
{"1,x", nil, true},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
got, err := parseCPUList(c.in)
|
|
||||||
if (err != nil) != c.wantErr {
|
|
||||||
t.Errorf("%q: err=%v wantErr=%v", c.in, err, c.wantErr)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !c.wantErr && !slices.Equal(got, c.want) {
|
|
||||||
t.Errorf("%q: got %v want %v", c.in, got, c.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
//go:build !linux
|
|
||||||
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
// perfCPUs is Linux-only sysfs walking; elsewhere report "no distinction".
|
|
||||||
// Default already returns nil off-Linux (util.AllowedCPUs has no answer
|
|
||||||
// there), so this exists to keep the package compiling everywhere.
|
|
||||||
func perfCPUs(allowed []int) ([]int, string) {
|
|
||||||
return allowed, ""
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
//go:build linux
|
|
||||||
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// readTopology probes the NUMA node and physical-core layout of cpus from
|
|
||||||
// sysfs. Anything sysfs won't say degrades toward flatTopology: an unknown
|
|
||||||
// node becomes node 0, an unknown core becomes a core of its own — either
|
|
||||||
// way the corresponding arrange rule becomes a no-op instead of a wrong
|
|
||||||
// answer.
|
|
||||||
func readTopology(cpus []int) topology {
|
|
||||||
return readTopologyFrom("/sys/devices/system/node", "/sys/devices/system/cpu", cpus)
|
|
||||||
}
|
|
||||||
|
|
||||||
func readTopologyFrom(nodeDir, cpuDir string, cpus []int) topology {
|
|
||||||
coreOf, zeroCore := coreGroups(cpuDir, cpus)
|
|
||||||
return topology{
|
|
||||||
nodeOf: numaNodes(nodeDir, cpus),
|
|
||||||
coreOf: coreOf,
|
|
||||||
zeroCore: zeroCore,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// numaNodes maps each cpu to its NUMA node via
|
|
||||||
// /sys/devices/system/node/nodeN/cpulist. CPUs no node claims (or no node
|
|
||||||
// dirs at all: VMs, non-NUMA kernels) land on node 0.
|
|
||||||
func numaNodes(nodeDir string, cpus []int) map[int]int {
|
|
||||||
out := make(map[int]int, len(cpus))
|
|
||||||
for _, c := range cpus {
|
|
||||||
out[c] = 0
|
|
||||||
}
|
|
||||||
entries, err := os.ReadDir(nodeDir)
|
|
||||||
if err != nil {
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
want := make(map[int]bool, len(cpus))
|
|
||||||
for _, c := range cpus {
|
|
||||||
want[c] = true
|
|
||||||
}
|
|
||||||
for _, e := range entries {
|
|
||||||
id, ok := strings.CutPrefix(e.Name(), "node")
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
n, err := strconv.Atoi(id)
|
|
||||||
if err != nil {
|
|
||||||
continue // has_cpu, possible, ... share the prefix
|
|
||||||
}
|
|
||||||
b, err := os.ReadFile(filepath.Join(nodeDir, e.Name(), "cpulist"))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
list, err := parseCPUList(strings.TrimSpace(string(b)))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, c := range list {
|
|
||||||
if want[c] {
|
|
||||||
out[c] = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// coreGroups maps each cpu to a dense physical-core id derived from its
|
|
||||||
// (physical_package_id, core_id) pair — core_id alone repeats across
|
|
||||||
// sockets. CPUs whose topology files are unreadable get a core of their own.
|
|
||||||
// The second return is the group id of the core CPU 0 lives on, or -1 when
|
|
||||||
// that can't be determined; CPU 0's own files are consulted even when 0 is
|
|
||||||
// not a candidate, so its SMT siblings are recognized under cpusets that
|
|
||||||
// exclude CPU 0 itself.
|
|
||||||
func coreGroups(cpuDir string, cpus []int) (map[int]int, int) {
|
|
||||||
type pkgCore struct{ pkg, core int }
|
|
||||||
pairOf := func(cpu int) (pkgCore, bool) {
|
|
||||||
topoDir := filepath.Join(cpuDir, fmt.Sprintf("cpu%d", cpu), "topology")
|
|
||||||
pkg, err1 := readIntFile(filepath.Join(topoDir, "physical_package_id"))
|
|
||||||
core, err2 := readIntFile(filepath.Join(topoDir, "core_id"))
|
|
||||||
if err1 != nil || err2 != nil {
|
|
||||||
return pkgCore{}, false
|
|
||||||
}
|
|
||||||
return pkgCore{pkg, core}, true
|
|
||||||
}
|
|
||||||
|
|
||||||
ids := map[pkgCore]int{}
|
|
||||||
out := make(map[int]int, len(cpus))
|
|
||||||
next := 0
|
|
||||||
for _, cpu := range cpus {
|
|
||||||
k, ok := pairOf(cpu)
|
|
||||||
if !ok {
|
|
||||||
out[cpu] = next
|
|
||||||
next++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
id, ok := ids[k]
|
|
||||||
if !ok {
|
|
||||||
id = next
|
|
||||||
next++
|
|
||||||
ids[k] = id
|
|
||||||
}
|
|
||||||
out[cpu] = id
|
|
||||||
}
|
|
||||||
|
|
||||||
zeroCore := -1
|
|
||||||
if k, ok := pairOf(0); ok {
|
|
||||||
if id, ok := ids[k]; ok {
|
|
||||||
zeroCore = id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, zeroCore
|
|
||||||
}
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
//go:build linux
|
|
||||||
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fakeTopoSysfs builds nodeDir/cpuDir trees. nodes maps node id -> cpulist
|
|
||||||
// string; cores maps cpu -> (package, core) pair.
|
|
||||||
func fakeTopoSysfs(t *testing.T, nodes map[int]string, cores map[int][2]int) (string, string) {
|
|
||||||
t.Helper()
|
|
||||||
base := t.TempDir()
|
|
||||||
nodeDir := filepath.Join(base, "node")
|
|
||||||
cpuDir := filepath.Join(base, "cpu")
|
|
||||||
for n, list := range nodes {
|
|
||||||
d := filepath.Join(nodeDir, fmt.Sprintf("node%d", n))
|
|
||||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(d, "cpulist"), []byte(list+"\n"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for cpu, pc := range cores {
|
|
||||||
d := filepath.Join(cpuDir, fmt.Sprintf("cpu%d", cpu), "topology")
|
|
||||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(d, "physical_package_id"), fmt.Appendf(nil, "%d\n", pc[0]), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(d, "core_id"), fmt.Appendf(nil, "%d\n", pc[1]), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nodeDir, cpuDir
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReadTopology(t *testing.T) {
|
|
||||||
// Two nodes; SMT pairs (0,4),(1,5) on node 0 and (2,6),(3,7) on node 1.
|
|
||||||
// core_id repeats across packages on purpose: the pair must disambiguate.
|
|
||||||
nodeDir, cpuDir := fakeTopoSysfs(t,
|
|
||||||
map[int]string{0: "0-1,4-5", 1: "2-3,6-7"},
|
|
||||||
map[int][2]int{
|
|
||||||
0: {0, 0}, 4: {0, 0}, 1: {0, 1}, 5: {0, 1},
|
|
||||||
2: {1, 0}, 6: {1, 0}, 3: {1, 1}, 7: {1, 1},
|
|
||||||
})
|
|
||||||
cpus := []int{0, 1, 2, 3, 4, 5, 6, 7}
|
|
||||||
topo := readTopologyFrom(nodeDir, cpuDir, cpus)
|
|
||||||
|
|
||||||
for _, c := range []int{0, 1, 4, 5} {
|
|
||||||
if topo.nodeOf[c] != 0 {
|
|
||||||
t.Errorf("cpu %d on node %d, want 0", c, topo.nodeOf[c])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, c := range []int{2, 3, 6, 7} {
|
|
||||||
if topo.nodeOf[c] != 1 {
|
|
||||||
t.Errorf("cpu %d on node %d, want 1", c, topo.nodeOf[c])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pairs := [][2]int{{0, 4}, {1, 5}, {2, 6}, {3, 7}}
|
|
||||||
for _, p := range pairs {
|
|
||||||
if topo.coreOf[p[0]] != topo.coreOf[p[1]] {
|
|
||||||
t.Errorf("siblings %v not grouped: %d vs %d", p, topo.coreOf[p[0]], topo.coreOf[p[1]])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if topo.coreOf[0] == topo.coreOf[2] {
|
|
||||||
t.Error("cross-package cores with equal core_id must not merge")
|
|
||||||
}
|
|
||||||
if topo.zeroCore != topo.coreOf[0] {
|
|
||||||
t.Errorf("zeroCore = %d, want %d", topo.zeroCore, topo.coreOf[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReadTopologyZeroCoreWithoutZeroCandidate(t *testing.T) {
|
|
||||||
// CPU 0 is not a candidate (cpuset excludes it) but its sibling 4 is:
|
|
||||||
// zeroCore must still identify their shared core.
|
|
||||||
nodeDir, cpuDir := fakeTopoSysfs(t,
|
|
||||||
map[int]string{0: "0-7"},
|
|
||||||
map[int][2]int{0: {0, 0}, 4: {0, 0}, 1: {0, 1}, 5: {0, 1}})
|
|
||||||
topo := readTopologyFrom(nodeDir, cpuDir, []int{1, 4, 5})
|
|
||||||
if topo.zeroCore < 0 || topo.coreOf[4] != topo.zeroCore {
|
|
||||||
t.Errorf("zeroCore = %d, coreOf[4] = %d; sibling of CPU 0 not identified", topo.zeroCore, topo.coreOf[4])
|
|
||||||
}
|
|
||||||
if topo.coreOf[1] == topo.zeroCore {
|
|
||||||
t.Error("cpu 1 wrongly grouped with CPU 0's core")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReadTopologyMissingSysfs(t *testing.T) {
|
|
||||||
base := t.TempDir()
|
|
||||||
cpus := []int{0, 1, 2}
|
|
||||||
topo := readTopologyFrom(filepath.Join(base, "nope"), filepath.Join(base, "also-nope"), cpus)
|
|
||||||
seen := map[int]bool{}
|
|
||||||
for _, c := range cpus {
|
|
||||||
if topo.nodeOf[c] != 0 {
|
|
||||||
t.Errorf("cpu %d node = %d, want 0", c, topo.nodeOf[c])
|
|
||||||
}
|
|
||||||
if seen[topo.coreOf[c]] {
|
|
||||||
t.Errorf("cpu %d shares a fallback core group", c)
|
|
||||||
}
|
|
||||||
seen[topo.coreOf[c]] = true
|
|
||||||
}
|
|
||||||
if topo.zeroCore != -1 {
|
|
||||||
t.Errorf("zeroCore = %d, want -1 when unknown", topo.zeroCore)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
//go:build !linux
|
|
||||||
|
|
||||||
package cpupick
|
|
||||||
|
|
||||||
// readTopology has no sysfs to consult off Linux; the flat stand-in makes
|
|
||||||
// arrange's NUMA and SMT rules no-ops. Default is already nil off Linux
|
|
||||||
// (util.AllowedCPUs has no answer there) — this keeps the package compiling.
|
|
||||||
func readTopology(cpus []int) topology {
|
|
||||||
return flatTopology(cpus)
|
|
||||||
}
|
|
||||||
+22
-13
@@ -12,7 +12,6 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
|
||||||
"github.com/miekg/dns"
|
"github.com/miekg/dns"
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -70,10 +69,9 @@ func newDnsServerFromConfig(ctx context.Context, l *slog.Logger, pki *PKI, hostM
|
|||||||
ds.mux = dns.NewServeMux()
|
ds.mux = dns.NewServeMux()
|
||||||
ds.mux.HandleFunc(".", ds.handleDnsRequest)
|
ds.mux.HandleFunc(".", ds.handleDnsRequest)
|
||||||
|
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C) {
|
||||||
if err := ds.reload(c, false); err != nil {
|
if err := ds.reload(c, false); err != nil {
|
||||||
ds.l.Error("Failed to reload DNS responder from config", "error", err)
|
ds.l.Error("Failed to reload DNS responder from config", "error", err)
|
||||||
r.Failed()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -260,20 +258,31 @@ func (d *dnsServer) QueryCert(data string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Our own address answers with the certificate handshakes are initiated with, as the
|
// The hostmap only ever contains peers we have handshaked with, so it never carries an entry for ourselves.
|
||||||
// TXT record always has; which of our certificates identity reports is its own choice.
|
// Answer self lookups straight from the local cert state.
|
||||||
cs := d.certState()
|
if cs := d.certState(); cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip) {
|
||||||
var crt cert.Certificate
|
c := cs.GetDefaultCertificate()
|
||||||
if ownsVpnAddr(cs, ip) {
|
if c == nil {
|
||||||
crt = cs.getCertificate(cs.initiatingVersion)
|
return ""
|
||||||
} else {
|
}
|
||||||
crt, _ = peerCertificateForVpnAddr(d.hostMap, ip)
|
b, err := c.MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
}
|
}
|
||||||
if crt == nil {
|
|
||||||
|
hostinfo := d.hostMap.QueryVpnAddr(ip)
|
||||||
|
if hostinfo == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
b, err := crt.MarshalJSON()
|
q := hostinfo.GetCert()
|
||||||
|
if q == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
b, err := q.Certificate.MarshalJSON()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@@ -403,32 +402,6 @@ func TestDnsServer_QueryCert_returnsOwnCert(t *testing.T) {
|
|||||||
assert.Empty(t, ds.QueryCert(other.String()+"."), "unknown peer IP should return nothing")
|
assert.Empty(t, ds.QueryCert(other.String()+"."), "unknown peer IP should return nothing")
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDnsServer_QueryCert_answersWithTheInitiatingCertificate: with both versions loaded
|
|
||||||
// the TXT record carries the certificate handshakes start with, as it always has, where
|
|
||||||
// identity and print-cert report the v2.
|
|
||||||
func TestDnsServer_QueryCert_answersWithTheInitiatingCertificate(t *testing.T) {
|
|
||||||
ds, _ := newTestDnsServer(t)
|
|
||||||
me := netip.MustParseAddr("10.0.0.1")
|
|
||||||
network := netip.PrefixFrom(me, 24)
|
|
||||||
ca1, _, caKey1, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
v1, _, _, _ := cert_test.NewTestCert(cert.Version1, cert.Curve_CURVE25519, ca1, caKey1, "lighthouse", time.Time{}, time.Time{}, []netip.Prefix{network}, nil, nil)
|
|
||||||
ca2, _, caKey2, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
v2, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca2, caKey2, "lighthouse", time.Time{}, time.Time{}, []netip.Prefix{network}, nil, nil)
|
|
||||||
|
|
||||||
addrsTable := new(bart.Lite)
|
|
||||||
addrsTable.Insert(netip.PrefixFrom(me, me.BitLen()))
|
|
||||||
cs := &CertState{v1Cert: v1, v2Cert: v2, initiatingVersion: cert.Version1, myVpnAddrs: []netip.Addr{me}, myVpnAddrsTable: addrsTable}
|
|
||||||
ds.pki = &PKI{}
|
|
||||||
ds.pki.cs.Store(cs)
|
|
||||||
|
|
||||||
var got struct {
|
|
||||||
Version cert.Version `json:"version"`
|
|
||||||
}
|
|
||||||
require.NoError(t, json.Unmarshal([]byte(ds.QueryCert(me.String()+".")), &got))
|
|
||||||
assert.Equal(t, cert.Version1, got.Version)
|
|
||||||
assert.Equal(t, v2, ownCertificate(cs), "identity reports the v2 from the same state")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDnsServer_reload_disable_stopsRunningServer(t *testing.T) {
|
func TestDnsServer_reload_disable_stopsRunningServer(t *testing.T) {
|
||||||
port := freeUDPPort(t)
|
port := freeUDPPort(t)
|
||||||
ds, c := newTestDnsServer(t)
|
ds, c := newTestDnsServer(t)
|
||||||
|
|||||||
@@ -1,181 +0,0 @@
|
|||||||
//go:build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"path/filepath"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/cert_test"
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/sshd"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// volatile lists everything in command output that legitimately differs between runs.
|
|
||||||
// Each run mints fresh certificates and indexes, so these are replaced with a marker
|
|
||||||
// before comparison. Keep the list short: anything added here is something the golden
|
|
||||||
// stops guarding.
|
|
||||||
var volatile = []struct {
|
|
||||||
re *regexp.Regexp
|
|
||||||
with string
|
|
||||||
}{
|
|
||||||
{regexp.MustCompile(`[0-9a-f]{40,}`), "<hex>"}, // fingerprints, keys, signatures
|
|
||||||
{regexp.MustCompile(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})`), "<time>"}, // RFC 3339
|
|
||||||
{regexp.MustCompile(`\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4} \w+`), "<time>"}, // time.Time.String()
|
|
||||||
{regexp.MustCompile(`(?s)(-----BEGIN [A-Z ]+-----\n).*?(\n-----END [A-Z ]+-----)`), "${1}<pem>${2}"}, // print-cert -raw
|
|
||||||
{regexp.MustCompile(`(-----BEGIN [A-Z ]+-----\\n).*?(\\n-----END [A-Z ]+-----)`), "${1}<pem>${2}"}, // the same, inside a JSON string
|
|
||||||
{regexp.MustCompile(`"(localIndex|remoteIndex|messageCounter)":\d+`), `"$1":<n>`},
|
|
||||||
{regexp.MustCompile(`(?m)^(\s*"?(?:LocalIndex|RemoteIndex|localIndex|remoteIndex|messageCounter)"?:?\s*)\d+`), "${1}<n>"}, // and the -pretty form
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalise(s string) string {
|
|
||||||
for _, v := range volatile {
|
|
||||||
s = v.re.ReplaceAllString(s, v.with)
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// outputCase is one command line to run through the ssh dispatch path.
|
|
||||||
type outputCase struct {
|
|
||||||
name string
|
|
||||||
args []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestCommandOutput pins the bytes every command produces, in every format, through the
|
|
||||||
// ssh dispatch path. It is the safety net for moving rendering out of the commands: a
|
|
||||||
// change here is a change someone at an ssh prompt would see. Regenerate with:
|
|
||||||
//
|
|
||||||
// go test -tags e2e_testing ./e2e -run TestCommandOutput -update
|
|
||||||
func TestCommandOutput(t *testing.T) {
|
|
||||||
ca, _, caKey, _ := cert_test.NewTestCaCert(
|
|
||||||
cert.Version1, cert.Curve_CURVE25519,
|
|
||||||
time.Now(), time.Now().Add(10*time.Minute),
|
|
||||||
nil, nil, []string{},
|
|
||||||
)
|
|
||||||
|
|
||||||
control, _, _, _ := newSimpleServer(cert.Version1, ca, caKey, "output-golden", "10.222.0.1/24", nil)
|
|
||||||
control.Start()
|
|
||||||
t.Cleanup(func() { control.Stop() })
|
|
||||||
|
|
||||||
// As an ssh session does: a clone of the daemon's registry with logout added, which
|
|
||||||
// help on the clone lists and describes. There is no session to end here.
|
|
||||||
reg := control.Commands().Clone()
|
|
||||||
reg.Register(sshd.LogoutCommand(func() {}))
|
|
||||||
// Dispatch with ssh's default-format policy, so the no-flag column records what an
|
|
||||||
// operator at an ssh prompt sees.
|
|
||||||
reg.DefaultFormat = sshd.DefaultFormat
|
|
||||||
|
|
||||||
// run dispatches as the ssh exec path does and returns the output and the error, which
|
|
||||||
// over ssh is exit status 1.
|
|
||||||
run := func(args ...string) (string, error) {
|
|
||||||
buf := &bytes.Buffer{}
|
|
||||||
err := reg.DispatchArgs(args, commands.MergedOutput(buf))
|
|
||||||
return buf.String(), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Seed a pending tunnel so the listing and per-address commands have something to show.
|
|
||||||
seed, err := run("create-tunnel", "10.222.0.9")
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, "Created\n", seed, "seeding a tunnel should succeed before anything else is recorded")
|
|
||||||
|
|
||||||
cases := []outputCase{
|
|
||||||
{"version", nil},
|
|
||||||
{"device-info", nil},
|
|
||||||
{"list-hostmap", nil},
|
|
||||||
{"list-hostmap", []string{"-by-index"}},
|
|
||||||
{"list-pending-hostmap", nil},
|
|
||||||
{"list-pending-hostmap", []string{"-by-index"}},
|
|
||||||
{"list-lighthouse-addrmap", nil},
|
|
||||||
{"print-cert", nil},
|
|
||||||
{"print-cert", []string{"-raw"}},
|
|
||||||
{"print-cert", []string{"10.222.0.9"}},
|
|
||||||
// A flag after the operand is still a flag, on both surfaces.
|
|
||||||
{"print-cert", []string{"10.222.0.9", "-json"}},
|
|
||||||
{"print-cert", []string{"10.222.0.250"}},
|
|
||||||
{"print-cert", []string{"not-an-address"}},
|
|
||||||
{"whoami", nil},
|
|
||||||
{"whoami", []string{"x"}},
|
|
||||||
// No address is a refusal that names whoami, never this node's identity.
|
|
||||||
{"identity", nil},
|
|
||||||
// Our own address, which the hostmap never holds, answers from our certificate.
|
|
||||||
{"identity", []string{"-address", "10.222.0.1"}},
|
|
||||||
{"identity", []string{"-address", "10.222.0.1:4242"}},
|
|
||||||
// A pending tunnel has no certificate yet.
|
|
||||||
{"identity", []string{"-address", "10.222.0.9"}},
|
|
||||||
{"identity", []string{"-address", "not-an-address"}},
|
|
||||||
{"identity", []string{"-address", ""}},
|
|
||||||
{"identity", []string{"10.222.0.9"}},
|
|
||||||
{"print-tunnel", nil},
|
|
||||||
{"print-tunnel", []string{"10.222.0.9"}},
|
|
||||||
{"print-tunnel", []string{"10.222.0.250"}},
|
|
||||||
{"print-relays", nil},
|
|
||||||
{"query-lighthouse", nil},
|
|
||||||
{"query-lighthouse", []string{"10.222.0.9"}},
|
|
||||||
{"query-lighthouse", []string{"not-an-address"}},
|
|
||||||
// The test logger cannot change level or format, so these cases record the
|
|
||||||
// refusal each command prints on it, not a successful change.
|
|
||||||
{"log-level", nil},
|
|
||||||
{"log-level", []string{"debug"}},
|
|
||||||
{"log-level", []string{"bogus"}},
|
|
||||||
{"log-level", []string{"info"}},
|
|
||||||
{"log-format", nil},
|
|
||||||
{"log-format", []string{"json"}},
|
|
||||||
{"log-format", []string{"text"}},
|
|
||||||
{"change-remote", nil},
|
|
||||||
{"change-remote", []string{"10.222.0.9"}},
|
|
||||||
{"change-remote", []string{"-address", "10.94.0.10:4242", "10.222.0.9"}},
|
|
||||||
{"change-remote", []string{"-address", "10.94.0.10:4242", "10.222.0.250"}},
|
|
||||||
{"create-tunnel", nil},
|
|
||||||
{"create-tunnel", []string{"10.222.0.9"}},
|
|
||||||
// A fresh address, so this exercises the handshake start with a remote attached
|
|
||||||
// rather than the "already handshaking" path above.
|
|
||||||
{"create-tunnel", []string{"-address", "10.94.0.10:4242", "10.222.0.10"}},
|
|
||||||
{"create-tunnel", []string{"not-an-address"}},
|
|
||||||
{"close-tunnel", nil},
|
|
||||||
{"close-tunnel", []string{"10.222.0.250"}},
|
|
||||||
{"close-tunnel", []string{"not-an-address"}},
|
|
||||||
{"help", nil},
|
|
||||||
{"help", []string{"print-cert"}},
|
|
||||||
{"help", []string{"logout"}},
|
|
||||||
{"logout", []string{"-h"}},
|
|
||||||
{"not-a-command", []string{"10.222.0.9"}},
|
|
||||||
// reload is last so that whatever a reload does to the daemon cannot leak into an
|
|
||||||
// earlier case. In this harness it fails: the config was loaded from a string and
|
|
||||||
// has no path to re-read, which is what the recorded result says.
|
|
||||||
{"reload", nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
got := &strings.Builder{}
|
|
||||||
for _, c := range cases {
|
|
||||||
for _, fmtFlags := range [][]string{nil, {"-json"}, {"-pretty"}} {
|
|
||||||
args := append([]string{c.name}, fmtFlags...)
|
|
||||||
args = append(args, c.args...)
|
|
||||||
|
|
||||||
fmt.Fprintf(got, "$ %s\n", strings.Join(args, " "))
|
|
||||||
out, err := run(args...)
|
|
||||||
out = normalise(out)
|
|
||||||
got.WriteString(out)
|
|
||||||
// Output that does not end in a newline is recorded as such, the way diff marks
|
|
||||||
// it, so the golden sees that byte too and the next prompt still starts a line.
|
|
||||||
if out != "" && !strings.HasSuffix(out, "\n") {
|
|
||||||
got.WriteString("\\ No newline at end of output\n")
|
|
||||||
}
|
|
||||||
// A failed command is recorded as the exit status an ssh caller sees, so the
|
|
||||||
// golden pins which outcomes count as failures.
|
|
||||||
if err != nil {
|
|
||||||
got.WriteString("exit status 1\n")
|
|
||||||
}
|
|
||||||
got.WriteString("\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test.Golden(t, filepath.Join("testdata", "commands_output.golden"), got.String())
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
@@ -1513,7 +1514,7 @@ func TestLighthouseUpdateOnReload(t *testing.T) {
|
|||||||
// Reload the config. The lighthouse.hosts change triggers TriggerUpdate,
|
// Reload the config. The lighthouse.hosts change triggers TriggerUpdate,
|
||||||
// which wakes the update worker. It calls SendUpdate, initiating a
|
// which wakes the update worker. It calls SendUpdate, initiating a
|
||||||
// handshake to the new lighthouse and caching the HostUpdateNotification.
|
// handshake to the new lighthouse and caching the HostUpdateNotification.
|
||||||
require.NoError(t, myConfig.ReloadConfigString(string(newCfg)).Err)
|
require.NoError(t, myConfig.ReloadConfigString(string(newCfg)))
|
||||||
|
|
||||||
// Route until the lighthouse receives the HostUpdateNotification.
|
// Route until the lighthouse receives the HostUpdateNotification.
|
||||||
// This covers: handshake stage 1, stage 2, then the cached update.
|
// This covers: handshake stage 1, stage 2, then the cached update.
|
||||||
|
|||||||
+5
-2
@@ -1,15 +1,18 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log/slog"
|
"io"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
"dario.cat/mergo"
|
"dario.cat/mergo"
|
||||||
"github.com/google/gopacket"
|
"github.com/google/gopacket"
|
||||||
"github.com/google/gopacket/layers"
|
"github.com/google/gopacket/layers"
|
||||||
@@ -379,7 +382,7 @@ func getAddrs(ns []netip.Prefix) []netip.Addr {
|
|||||||
func NewTestLogger() *slog.Logger {
|
func NewTestLogger() *slog.Logger {
|
||||||
v := os.Getenv("TEST_LOGS")
|
v := os.Getenv("TEST_LOGS")
|
||||||
if v == "" {
|
if v == "" {
|
||||||
return slog.New(slog.DiscardHandler)
|
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
level := slog.LevelInfo
|
level := slog.LevelInfo
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
//go:build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/netip"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/cert_test"
|
|
||||||
"github.com/slackhq/nebula/e2e/router"
|
|
||||||
"github.com/slackhq/nebula/localapi"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestIdentityOverTheInfoAPI is the info API's reason to exist, end to end: a program on
|
|
||||||
// this host has a connection arriving over the overlay and asks who is behind its
|
|
||||||
// source address, and the answer is the identity in the certificate the tunnel was
|
|
||||||
// established with.
|
|
||||||
func TestIdentityOverTheInfoAPI(t *testing.T) {
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
t.Skip("the test's HTTP helpers dial unix sockets; on windows the info API is a named pipe")
|
|
||||||
}
|
|
||||||
|
|
||||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
|
||||||
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.1/24", nil)
|
|
||||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.2/24", nil)
|
|
||||||
|
|
||||||
myControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
|
||||||
|
|
||||||
r := router.NewR(t, myControl, theirControl)
|
|
||||||
defer r.RenderFlow()
|
|
||||||
|
|
||||||
myControl.Start()
|
|
||||||
theirControl.Start()
|
|
||||||
t.Cleanup(func() {
|
|
||||||
myControl.Stop()
|
|
||||||
theirControl.Stop()
|
|
||||||
})
|
|
||||||
|
|
||||||
// Before the tunnel is up their address is unknown to us.
|
|
||||||
path := infoSocket(t)
|
|
||||||
info := localapi.NewInfoServer(NewTestLogger(), myControl.Commands())
|
|
||||||
require.NoError(t, info.Rebind(context.Background(), path, localapi.Access{Mode: 0600}))
|
|
||||||
t.Cleanup(info.Stop)
|
|
||||||
|
|
||||||
status, body := test.HTTPGet(t, path, "/v1/identity?address="+theirVpnIpNet[0].Addr().String())
|
|
||||||
assert.Equal(t, http.StatusNotFound, status)
|
|
||||||
assert.JSONEq(t, `{"error":"No active tunnel for vpn addr: 10.128.0.2"}`, body)
|
|
||||||
|
|
||||||
// Only we know how to reach them, so the first packet has to be ours; once the tunnel
|
|
||||||
// is up both directions work and assertTunnel can check it.
|
|
||||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("Hi from me")))
|
|
||||||
p := r.RouteForAllUntilTxTun(theirControl)
|
|
||||||
assertUdpPacket(t, []byte("Hi from me"), p, myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), 80, 80)
|
|
||||||
assertTunnel(t, myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), myControl, theirControl, r)
|
|
||||||
|
|
||||||
type identity struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
VpnAddrs []netip.Addr `json:"vpnAddrs"`
|
|
||||||
Networks []netip.Prefix `json:"networks"`
|
|
||||||
Groups []string `json:"groups"`
|
|
||||||
Issuer string `json:"issuer"`
|
|
||||||
Fingerprint string `json:"fingerprint"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// A connection's RemoteAddr, port and all, resolves to the peer.
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/identity?address="+netip.AddrPortFrom(theirVpnIpNet[0].Addr(), 51234).String())
|
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
|
||||||
var them identity
|
|
||||||
require.NoError(t, json.Unmarshal([]byte(body), &them))
|
|
||||||
assert.Equal(t, "them", them.Name)
|
|
||||||
assert.Equal(t, []netip.Addr{theirVpnIpNet[0].Addr()}, them.VpnAddrs)
|
|
||||||
assert.Equal(t, theirVpnIpNet, them.Networks)
|
|
||||||
assert.Equal(t, []string{}, them.Groups)
|
|
||||||
caFP, err := ca.Fingerprint()
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, caFP, them.Issuer)
|
|
||||||
|
|
||||||
// No address is a caller that forgot the parameter, and is refused rather than handed
|
|
||||||
// this node's identity to authorize against; whoami is the command for that.
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/identity")
|
|
||||||
assert.Equal(t, http.StatusBadRequest, status, body)
|
|
||||||
assert.Contains(t, body, "whoami")
|
|
||||||
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/whoami")
|
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
|
||||||
var me identity
|
|
||||||
require.NoError(t, json.Unmarshal([]byte(body), &me))
|
|
||||||
assert.Equal(t, "me", me.Name)
|
|
||||||
assert.Equal(t, []netip.Addr{myVpnIpNet[0].Addr()}, me.VpnAddrs)
|
|
||||||
|
|
||||||
// An empty address is a caller's bug, and is told so rather than handed our identity.
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/identity?address=")
|
|
||||||
assert.Equal(t, http.StatusBadRequest, status)
|
|
||||||
assert.JSONEq(t, `{"error":"The provided vpn addr could not be parsed: "}`, body)
|
|
||||||
|
|
||||||
// The certificate itself, for a program that verifies it against its own CAs: the one
|
|
||||||
// nebula verified when the tunnel came up, as PEM, by the address a connection carries.
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/print-cert?address="+netip.AddrPortFrom(theirVpnIpNet[0].Addr(), 51234).String()+"&raw=true")
|
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
|
||||||
var raw struct {
|
|
||||||
PEM string `json:"pem"`
|
|
||||||
}
|
|
||||||
require.NoError(t, json.Unmarshal([]byte(body), &raw))
|
|
||||||
theirs, _, err := cert.UnmarshalCertificateFromPEM([]byte(raw.PEM))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, "them", theirs.Name())
|
|
||||||
fp, err := theirs.Fingerprint()
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, them.Fingerprint, fp, "the same certificate identity reports")
|
|
||||||
|
|
||||||
// Without raw it is the certificate's fields; without an address, our own.
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/print-cert")
|
|
||||||
require.Equal(t, http.StatusOK, status, body)
|
|
||||||
assert.Contains(t, body, `"name":"me"`)
|
|
||||||
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/print-cert?address=10.128.0.9")
|
|
||||||
assert.Equal(t, http.StatusNotFound, status)
|
|
||||||
assert.JSONEq(t, `{"error":"Could not find tunnel for vpn addr: 10.128.0.9"}`, body)
|
|
||||||
|
|
||||||
// Nothing else nebula serves is reachable here.
|
|
||||||
status, body = test.HTTPGet(t, path, "/v1/list-hostmap")
|
|
||||||
assert.Equal(t, http.StatusForbidden, status)
|
|
||||||
assert.Contains(t, body, "identity lookups only")
|
|
||||||
|
|
||||||
r.RenderHostmaps("Final hostmaps", myControl, theirControl)
|
|
||||||
}
|
|
||||||
|
|
||||||
// infoSocket returns a short socket path in a private directory, one level below it
|
|
||||||
// so that listen has a directory of its own to create.
|
|
||||||
func infoSocket(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
return filepath.Join(test.ShortTempDir(t), "n", "info.sock")
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
+1
-57
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
@@ -222,60 +223,3 @@ func TestRebindAdvertisesNewAddressAfterMove(t *testing.T) {
|
|||||||
lhControl.Stop()
|
lhControl.Stop()
|
||||||
myControl.Stop()
|
myControl.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
// A relayed send records traffic but must not consume the rebind epoch. If it does, the next direct send to the
|
|
||||||
// relay host sees the epoch already current and never requeries, so the far side is never told to punch at our
|
|
||||||
// new address. This pins the SendVia call site, which the unit tests cannot reach.
|
|
||||||
func TestRebindRequeriesAfterRelayedSend(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
|
||||||
|
|
||||||
// No lighthouse on purpose: it would hand out a direct address for them and nothing would relay.
|
|
||||||
// Long connection manager timers so it never fires a direct test packet at the relay tunnel and bumps its
|
|
||||||
// epoch mid-test, which is the only other thing that touches that tunnel and would flake the assertion below.
|
|
||||||
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.1/24",
|
|
||||||
m{"relay": m{"use_relays": true}, "timers": m{"connection_alive_interval": 3600, "pending_deletion_interval": 3600}})
|
|
||||||
relayControl, relayVpnIpNet, relayUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "relay", "10.128.0.128/24", m{"relay": m{"am_relay": true}})
|
|
||||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.2/24", m{"relay": m{"use_relays": true}})
|
|
||||||
|
|
||||||
myControl.InjectLightHouseAddr(relayVpnIpNet[0].Addr(), relayUdpAddr)
|
|
||||||
myControl.InjectRelays(theirVpnIpNet[0].Addr(), []netip.Addr{relayVpnIpNet[0].Addr()})
|
|
||||||
relayControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
|
||||||
|
|
||||||
r := router.NewR(t, myControl, relayControl, theirControl)
|
|
||||||
defer r.RenderFlow()
|
|
||||||
|
|
||||||
myControl.Start()
|
|
||||||
relayControl.Start()
|
|
||||||
theirControl.Start()
|
|
||||||
|
|
||||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("establish")))
|
|
||||||
r.RouteForAllUntilTxTun(theirControl)
|
|
||||||
r.RouteFor(time.Millisecond * 500)
|
|
||||||
|
|
||||||
hi := myControl.GetHostInfoByVpnAddr(theirVpnIpNet[0].Addr(), false)
|
|
||||||
require.NotNil(t, hi, "expected a tunnel to them")
|
|
||||||
require.NotEmpty(t, hi.CurrentRelaysToMe, "them must be reachable only via the relay for this test to mean anything")
|
|
||||||
// sendNoMetrics only reaches SendVia when there is no direct remote, so pin that too. Without this the test
|
|
||||||
// keeps passing while quietly sending direct and never exercising the relay path.
|
|
||||||
require.False(t, hi.CurrentRemote.IsValid(), "them must have no direct remote, otherwise SendVia is never called")
|
|
||||||
|
|
||||||
before, ok := myControl.GetRebindEpochFor(relayVpnIpNet[0].Addr())
|
|
||||||
require.True(t, ok, "expected a tunnel to the relay")
|
|
||||||
|
|
||||||
myControl.RebindUDPServer()
|
|
||||||
|
|
||||||
// Traffic to them goes through SendVia on the relay tunnel. That must record traffic without consuming the
|
|
||||||
// relay tunnel's own epoch edge, which belongs to the direct path.
|
|
||||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("relayed")))
|
|
||||||
r.RouteForAllUntilTxTun(theirControl)
|
|
||||||
|
|
||||||
after, ok := myControl.GetRebindEpochFor(relayVpnIpNet[0].Addr())
|
|
||||||
require.True(t, ok)
|
|
||||||
assert.Equal(t, before, after,
|
|
||||||
"a relayed send consumed the relay tunnel's rebind epoch, so the next direct send will not requery")
|
|
||||||
|
|
||||||
myControl.Stop()
|
|
||||||
relayControl.Stop()
|
|
||||||
theirControl.Stop()
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package router
|
package router
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package router
|
package router
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"maps"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
"slices"
|
|
||||||
"sort"
|
"sort"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -23,6 +22,7 @@ import (
|
|||||||
"github.com/slackhq/nebula"
|
"github.com/slackhq/nebula"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
|
"golang.org/x/exp/maps"
|
||||||
)
|
)
|
||||||
|
|
||||||
// outNatKey is the (from, to) pair used by outNat. Comparable struct, so it works as a map key without the
|
// outNatKey is the (from, to) pair used by outNat. Comparable struct, so it works as a map key without the
|
||||||
@@ -374,7 +374,7 @@ func (r *R) RenderHostmaps(title string, controls ...*nebula.Control) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *R) renderHostmaps(title string) {
|
func (r *R) renderHostmaps(title string) {
|
||||||
c := slices.AppendSeq(make([]*nebula.Control, 0, len(r.controls)), maps.Values(r.controls))
|
c := maps.Values(r.controls)
|
||||||
sort.SliceStable(c, func(i, j int) bool {
|
sort.SliceStable(c, func(i, j int) bool {
|
||||||
return c[i].GetVpnAddrs()[0].Compare(c[j].GetVpnAddrs()[0]) > 0
|
return c[i].GetVpnAddrs()[0].Compare(c[j].GetVpnAddrs()[0]) > 0
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
Vendored
-1362
File diff suppressed because it is too large.
Load diff
+3
-2
@@ -1,4 +1,5 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
|
// +build e2e_testing
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
@@ -129,7 +130,7 @@ func TestCertUpgrade(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
r.Logf("reload new v2-only config")
|
r.Logf("reload new v2-only config")
|
||||||
err = myC.ReloadConfigString(string(cb)).Err
|
err = myC.ReloadConfigString(string(cb))
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
r.Log("yay, spin until their sees it")
|
r.Log("yay, spin until their sees it")
|
||||||
waitStart := time.Now()
|
waitStart := time.Now()
|
||||||
@@ -222,7 +223,7 @@ func TestCertDowngrade(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
r.Logf("reload new v1-only config")
|
r.Logf("reload new v1-only config")
|
||||||
err = myC.ReloadConfigString(string(cb)).Err
|
err = myC.ReloadConfigString(string(cb))
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
r.Log("yay, spin until their sees it")
|
r.Log("yay, spin until their sees it")
|
||||||
waitStart := time.Now()
|
waitStart := time.Now()
|
||||||
|
|||||||
+19
-112
@@ -8,7 +8,6 @@ pki:
|
|||||||
cert: /etc/nebula/host.crt
|
cert: /etc/nebula/host.crt
|
||||||
key: /etc/nebula/host.key
|
key: /etc/nebula/host.key
|
||||||
# blocklist is a list of certificate fingerprints that we will refuse to talk to
|
# blocklist is a list of certificate fingerprints that we will refuse to talk to
|
||||||
# Entries are the hex fingerprints shown by `nebula-cert print`, an invalid entry fails startup and reload.
|
|
||||||
#blocklist:
|
#blocklist:
|
||||||
# - c99d4e650533b92061b09918e838a5a0a6aaee21eed1d12fd937682865936c72
|
# - c99d4e650533b92061b09918e838a5a0a6aaee21eed1d12fd937682865936c72
|
||||||
# disconnect_invalid is a toggle to force a client to be disconnected if the certificate is expired or invalid.
|
# disconnect_invalid is a toggle to force a client to be disconnected if the certificate is expired or invalid.
|
||||||
@@ -44,7 +43,7 @@ static_host_map:
|
|||||||
|
|
||||||
lighthouse:
|
lighthouse:
|
||||||
# am_lighthouse is used to enable lighthouse functionality for a node. This should ONLY be true on nodes
|
# am_lighthouse is used to enable lighthouse functionality for a node. This should ONLY be true on nodes
|
||||||
# you have configured to be lighthouses in your network. Not reloadable.
|
# you have configured to be lighthouses in your network
|
||||||
am_lighthouse: false
|
am_lighthouse: false
|
||||||
# serve_dns optionally starts a dns listener that responds to various queries and can even be
|
# serve_dns optionally starts a dns listener that responds to various queries and can even be
|
||||||
# delegated to for resolution
|
# delegated to for resolution
|
||||||
@@ -127,23 +126,18 @@ lighthouse:
|
|||||||
# Port Nebula will be listening on. The default here is 4242. For a lighthouse node, the port should be defined,
|
# Port Nebula will be listening on. The default here is 4242. For a lighthouse node, the port should be defined,
|
||||||
# however using port 0 will dynamically assign a port and is recommended for roaming nodes.
|
# however using port 0 will dynamically assign a port and is recommended for roaming nodes.
|
||||||
listen:
|
listen:
|
||||||
# To listen on only ipv4, use "0.0.0.0". Not reloadable.
|
# To listen on only ipv4, use "0.0.0.0"
|
||||||
host: "::"
|
host: "::"
|
||||||
# Not reloadable.
|
|
||||||
port: 4242
|
port: 4242
|
||||||
# Sets the max number of packets to pull from the kernel for each syscall (under systems that support recvmmsg)
|
# Sets the max number of packets to pull from the kernel for each syscall (under systems that support recvmmsg)
|
||||||
# default is 64, does not support reload
|
# default is 64, does not support reload
|
||||||
# Note: on Linux with UDP GRO (kernel 5.10+), each receive slot is sized for a full 64KiB coalesced
|
|
||||||
# superpacket, so the receive scratch is batch * 64KiB per listening socket (~4MiB per routine at the
|
|
||||||
# default of 64). Lower this to trade peak per-syscall throughput for memory on constrained hosts.
|
|
||||||
#batch: 64
|
#batch: 64
|
||||||
# Linux only. Reloadable, but removing a value leaves the socket at the old size until Nebula restarts.
|
|
||||||
# Configure socket buffers for the udp side (outside), leave unset to use the system defaults. Values will be doubled by the kernel
|
# Configure socket buffers for the udp side (outside), leave unset to use the system defaults. Values will be doubled by the kernel
|
||||||
# Default is net.core.rmem_default and net.core.wmem_default (/proc/sys/net/core/rmem_default and /proc/sys/net/core/rmem_default)
|
# Default is net.core.rmem_default and net.core.wmem_default (/proc/sys/net/core/rmem_default and /proc/sys/net/core/rmem_default)
|
||||||
# Maximum is limited by memory in the system, SO_RCVBUFFORCE and SO_SNDBUFFORCE is used to avoid having to raise the system wide
|
# Maximum is limited by memory in the system, SO_RCVBUFFORCE and SO_SNDBUFFORCE is used to avoid having to raise the system wide
|
||||||
# max, net.core.rmem_max and net.core.wmem_max
|
# max, net.core.rmem_max and net.core.wmem_max
|
||||||
read_buffer: 3412512
|
#read_buffer: 10485760
|
||||||
write_buffer: 3412512
|
#write_buffer: 10485760
|
||||||
|
|
||||||
# On Windows only
|
# On Windows only
|
||||||
# When true, Nebula installs a WFP (Windows Filtering Platform) PERMIT filter scoped to UDP at the listener port.
|
# When true, Nebula installs a WFP (Windows Filtering Platform) PERMIT filter scoped to UDP at the listener port.
|
||||||
@@ -175,14 +169,12 @@ listen:
|
|||||||
# allowing for more precise routing decisions based on the packet tags. Default is 0 meaning no mark is set.
|
# allowing for more precise routing decisions based on the packet tags. Default is 0 meaning no mark is set.
|
||||||
# This setting is reloadable.
|
# This setting is reloadable.
|
||||||
#so_mark: 0
|
#so_mark: 0
|
||||||
# the udp_offloads setting controls if Nebula will attempt to enable GSO and GRO for its UDP socket(s). Linux only, not reloadable.
|
|
||||||
# udp_offloads: false
|
|
||||||
|
|
||||||
# Routines is the number of thread pairs to run that consume from the tun and UDP queues.
|
# Routines is the number of thread pairs to run that consume from the tun and UDP queues.
|
||||||
# Currently, this defaults to 1 which means we have 1 tun queue reader and 1
|
# Currently, this defaults to 1 which means we have 1 tun queue reader and 1
|
||||||
# UDP queue reader. Setting this above one will set IFF_MULTI_QUEUE on the tun
|
# UDP queue reader. Setting this above one will set IFF_MULTI_QUEUE on the tun
|
||||||
# device and SO_REUSEPORT on the UDP socket to allow multiple queues.
|
# device and SO_REUSEPORT on the UDP socket to allow multiple queues.
|
||||||
# This option is only supported on Linux. Not reloadable.
|
# This option is only supported on Linux.
|
||||||
#routines: 1
|
#routines: 1
|
||||||
|
|
||||||
punchy:
|
punchy:
|
||||||
@@ -206,7 +198,6 @@ punchy:
|
|||||||
|
|
||||||
# Cipher allows you to choose between the available ciphers for your network. Options are chachapoly or aes
|
# Cipher allows you to choose between the available ciphers for your network. Options are chachapoly or aes
|
||||||
# IMPORTANT: this value must be identical on ALL NODES/LIGHTHOUSES. We do not/will not support use of different ciphers simultaneously!
|
# IMPORTANT: this value must be identical on ALL NODES/LIGHTHOUSES. We do not/will not support use of different ciphers simultaneously!
|
||||||
# Not reloadable.
|
|
||||||
#cipher: aes
|
#cipher: aes
|
||||||
|
|
||||||
# Preferred ranges is used to define a hint about the local network ranges, which speeds up discovering the fastest
|
# Preferred ranges is used to define a hint about the local network ranges, which speeds up discovering the fastest
|
||||||
@@ -233,57 +224,12 @@ punchy:
|
|||||||
# Trusted SSH CA public keys. These are the public keys of the CAs that are allowed to sign SSH keys for access.
|
# Trusted SSH CA public keys. These are the public keys of the CAs that are allowed to sign SSH keys for access.
|
||||||
#trusted_cas:
|
#trusted_cas:
|
||||||
#- "ssh public key string"
|
#- "ssh public key string"
|
||||||
|
# sandbox_dir restricts file paths for profiling commands (start-cpu-profile, save-heap-profile,
|
||||||
# Local APIs allow accessing running nebula state.
|
# save-mutex-profile) to the specified directory. Relative paths will be resolved within this directory,
|
||||||
#local_api:
|
# and absolute paths outside of it will be rejected. Default is $TMP/nebula-debug.
|
||||||
# There are two types of sockets available: a control socket intended for use on the
|
# The directory is NOT automatically created.
|
||||||
# local machine, primarily for debugging, and an info socket intended to make
|
# Overriding this to "" is the same as "/" and will allow overwriting any path on the host.
|
||||||
# nebula's internal state available to other consumers.
|
#sandbox_dir: /var/tmp/nebula-debug
|
||||||
#
|
|
||||||
# The control socket is made available by default, and can be accessed via
|
|
||||||
# `nebula ctl <command>`. It defaults to /var/run/nebula/ctl.sock on Linux, macOS and
|
|
||||||
# the BSDs; on Windows it is a named pipe under \\.\pipe\ProtectedPrefix\Administrators.
|
|
||||||
#control:
|
|
||||||
# Set to false to turn the control socket off. Reloadable.
|
|
||||||
#enabled: true
|
|
||||||
# The absolute path where the control socket should live, or a full pipe name on
|
|
||||||
# Windows. The last directory is created if missing, and must be owned by root or by
|
|
||||||
# the user running nebula. It must not be writable by anyone else.
|
|
||||||
#socket: /var/run/nebula/ctl.sock
|
|
||||||
# A group (or account/group/SID on Windows) that should be allowed to access the
|
|
||||||
# socket.
|
|
||||||
#group: nebula
|
|
||||||
|
|
||||||
# The info socket is not made available by default. If you enable it, it makes some
|
|
||||||
# internal state available over HTTP.
|
|
||||||
#
|
|
||||||
# The currently supported HTTP requests are:
|
|
||||||
# GET /v1/identity?address=<vpn addr>[:port] the host owning the address; the port
|
|
||||||
# is ignored. 404 when no tunnel is
|
|
||||||
# up, 400 when no address is given.
|
|
||||||
# GET /v1/whoami this node's identity
|
|
||||||
# GET /v1/print-cert?address=<vpn addr>[:port]&raw=true
|
|
||||||
# the certificate for the specified
|
|
||||||
# address, as {"pem": ...}.
|
|
||||||
# GET /v1 describes what is served
|
|
||||||
#
|
|
||||||
# NB: unless a connection arrived on the nebula interface, there's no guarantee
|
|
||||||
# that the identity returned belongs to the sender.
|
|
||||||
#
|
|
||||||
#info:
|
|
||||||
#enabled: false
|
|
||||||
# The absolute path to listen on, or a full pipe name on Windows. Name a pipe under
|
|
||||||
# \\.\pipe\ProtectedPrefix\Administrators\.
|
|
||||||
#socket: /var/run/nebula/info.sock
|
|
||||||
# A group (or account/group/SID on Windows) that should be allowed to access the
|
|
||||||
# socket. On Windows the group may read and write the pipe but not create an
|
|
||||||
# instance of it, so a client in the group must open the pipe asking for read and
|
|
||||||
# write data rather than generic read and write.
|
|
||||||
#group: nebula-info
|
|
||||||
# Octal mode for the socket, as a quoted string. Defaults to "0600" unless a
|
|
||||||
# group is set, in which case it defaults to "0660". On Windows a pipe has no
|
|
||||||
# mode and this is ignored; the group alone decides who may connect.
|
|
||||||
#socket_mode: "0660"
|
|
||||||
|
|
||||||
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
||||||
relay:
|
relay:
|
||||||
@@ -302,54 +248,20 @@ relay:
|
|||||||
# Configure the private interface. Note: addr is baked into the nebula certificate
|
# Configure the private interface. Note: addr is baked into the nebula certificate
|
||||||
tun:
|
tun:
|
||||||
# When tun is disabled, a lighthouse can be started without a local tun interface (and therefore without root)
|
# When tun is disabled, a lighthouse can be started without a local tun interface (and therefore without root)
|
||||||
# Not reloadable.
|
|
||||||
disabled: false
|
disabled: false
|
||||||
# Name of the device. If not set, a default will be chosen by the OS.
|
# Name of the device. If not set, a default will be chosen by the OS.
|
||||||
# For macOS: if set, must be in the form `utun[0-9]+`.
|
# For macOS: if set, must be in the form `utun[0-9]+`.
|
||||||
# For OpenBSD and NetBSD: if set, must be in the form `tun[0-9]+`, otherwise the first free one is used.
|
# For NetBSD: Required to be set, must be in the form `tun[0-9]+`
|
||||||
# Not reloadable.
|
|
||||||
dev: nebula1
|
dev: nebula1
|
||||||
# Toggles forwarding of local broadcast packets, the address of which depends on the ip/mask encoded in pki.cert
|
# Toggles forwarding of local broadcast packets, the address of which depends on the ip/mask encoded in pki.cert
|
||||||
# Not reloadable.
|
|
||||||
drop_local_broadcast: false
|
drop_local_broadcast: false
|
||||||
# Toggles forwarding of multicast packets. Not reloadable.
|
# Toggles forwarding of multicast packets
|
||||||
drop_multicast: false
|
drop_multicast: false
|
||||||
# Sets the transmit queue length, if you notice lots of transmit drops on the tun it may help to raise this number. Default is 5000
|
# Sets the transmit queue length, if you notice lots of transmit drops on the tun it may help to raise this number. Default is 500
|
||||||
# Not reloadable.
|
tx_queue: 500
|
||||||
tx_queue: 5000
|
|
||||||
# Default MTU for every packet, safe setting is (and the default) 1300 for internet based traffic
|
# Default MTU for every packet, safe setting is (and the default) 1300 for internet based traffic
|
||||||
# Anything above 8937, here or on a route below, is capped to 8937 with a warning
|
|
||||||
# Reloadable on Linux only. Where the tun is handed to nebula by a host app (iOS, Android, macOS network extensions)
|
|
||||||
# the host app owns the MTU.
|
|
||||||
mtu: 1300
|
mtu: 1300
|
||||||
|
|
||||||
# the use_offloads setting controls if Nebula will attempt to enable GSO and GRO for the tun device. Linux only, not reloadable.
|
|
||||||
#use_offloads: false
|
|
||||||
|
|
||||||
# Linux only. pin_threads pins each tun reader/encrypt OS thread to a single CPU. This keeps every goroutine's
|
|
||||||
# batched sends flowing through one XPS-selected NIC TX ring, so packets within a flow stay ordered on the wire
|
|
||||||
# instead of being sprayed across multiple TX rings and reordered. Not reloadable. Coerced to false if routines <= 1.
|
|
||||||
#pin_threads: true
|
|
||||||
|
|
||||||
# pin_threads_key helps the CPU-auto-selector shuffle which CPUs are chosen for pinning.
|
|
||||||
# Valid options are "pid" or "port". Use "port" if you want Nebula to choose the same cores every time, which is nice for benchmarking.
|
|
||||||
# Linux only, not reloadable.
|
|
||||||
#pin_threads_key: "pid"
|
|
||||||
|
|
||||||
# Linux only. cpu_affinity overrides which CPUs the tun reader threads pin to: a list of CPU IDs, one per routine
|
|
||||||
# (see the top-level `routines` setting). Lists shorter than `routines` are modulo-cycled across the queues; extra
|
|
||||||
# entries are ignored. IDs must be within the process's allowed CPU set, so this respects taskset / cgroup cpusets;
|
|
||||||
# a non-integer or not-allowed entry disables the override, leaving the default pin selection described below.
|
|
||||||
# Only meaningful while pin_threads is true. Not reloadable.
|
|
||||||
# When unset (or rejected), the default spread prefers performance cores on heterogeneous CPUs (ARM big.LITTLE,
|
|
||||||
# Intel P/E hybrids, AMD compact cores), keeps all readers on one NUMA node and on distinct physical cores when the
|
|
||||||
# topology allows (SMT siblings last), leaves CPU 0's physical core as a last resort, and rotates its starting
|
|
||||||
# point per instance (keyed by the bound UDP port) so co-located nebulas don't stack their readers onto the
|
|
||||||
# same cores.
|
|
||||||
#cpu_affinity:
|
|
||||||
# - 2
|
|
||||||
# - 4
|
|
||||||
|
|
||||||
# Route based MTU overrides, you have known vpn ip paths that can support larger MTUs you can increase/decrease them here
|
# Route based MTU overrides, you have known vpn ip paths that can support larger MTUs you can increase/decrease them here
|
||||||
routes:
|
routes:
|
||||||
#- mtu: 8800
|
#- mtu: 8800
|
||||||
@@ -382,9 +294,6 @@ tun:
|
|||||||
# `mtu`: will default to tun mtu if this option is not specified
|
# `mtu`: will default to tun mtu if this option is not specified
|
||||||
# `metric`: will default to 0 if this option is not specified
|
# `metric`: will default to 0 if this option is not specified
|
||||||
# `install`: will default to true, controls whether this route is installed in the systems routing table.
|
# `install`: will default to true, controls whether this route is installed in the systems routing table.
|
||||||
# On macOS, a route whose destination another interface already routes, like the local network, is installed once
|
|
||||||
# that route is removed. One deleted by hand stays deleted until nebula reloads or restarts, or until another
|
|
||||||
# interface routes its destination and lets it go.
|
|
||||||
# This setting is reloadable.
|
# This setting is reloadable.
|
||||||
unsafe_routes:
|
unsafe_routes:
|
||||||
#- route: 172.16.1.0/24
|
#- route: 172.16.1.0/24
|
||||||
@@ -416,7 +325,7 @@ tun:
|
|||||||
#use_system_route_table: false
|
#use_system_route_table: false
|
||||||
# Buffer size for reading routes updates. 0 means default system buffer size. (/proc/sys/net/core/rmem_default).
|
# Buffer size for reading routes updates. 0 means default system buffer size. (/proc/sys/net/core/rmem_default).
|
||||||
# If using massive routes updates, for example BGP, you may need to increase this value to avoid packet loss.
|
# If using massive routes updates, for example BGP, you may need to increase this value to avoid packet loss.
|
||||||
# SO_RCVBUFFORCE is used to avoid having to raise the system wide max. Not reloadable.
|
# SO_RCVBUFFORCE is used to avoid having to raise the system wide max
|
||||||
#use_system_route_table_buffer_size: 0
|
#use_system_route_table_buffer_size: 0
|
||||||
|
|
||||||
# Configure logging level
|
# Configure logging level
|
||||||
@@ -466,16 +375,14 @@ logging:
|
|||||||
# Handshakes are sent to all known addresses at each interval with a linear backoff,
|
# Handshakes are sent to all known addresses at each interval with a linear backoff,
|
||||||
# Wait try_interval after the 1st attempt, 2 * try_interval after the 2nd, etc, until the handshake is older than timeout
|
# Wait try_interval after the 1st attempt, 2 * try_interval after the 2nd, etc, until the handshake is older than timeout
|
||||||
# A 100ms interval with the default 10 retries will give a handshake 5.5 seconds to resolve before timing out
|
# A 100ms interval with the default 10 retries will give a handshake 5.5 seconds to resolve before timing out
|
||||||
# Not reloadable.
|
|
||||||
#try_interval: 100ms
|
#try_interval: 100ms
|
||||||
#retries: 20
|
#retries: 20
|
||||||
|
|
||||||
# query_buffer is the size of the buffer channel for querying lighthouses, drops are recorded in the lighthouse.query.dropped metric.
|
# query_buffer is the size of the buffer channel for querying lighthouses
|
||||||
# Not reloadable.
|
#query_buffer: 64
|
||||||
#query_buffer: 1024
|
|
||||||
|
|
||||||
# trigger_buffer is the size of the buffer channel for quickly sending handshakes
|
# trigger_buffer is the size of the buffer channel for quickly sending handshakes
|
||||||
# after receiving the response for lighthouse queries. Not reloadable.
|
# after receiving the response for lighthouse queries
|
||||||
#trigger_buffer: 64
|
#trigger_buffer: 64
|
||||||
|
|
||||||
# Tunnel manager settings
|
# Tunnel manager settings
|
||||||
|
|||||||
+18
-53
@@ -21,7 +21,6 @@ import (
|
|||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/slackhq/nebula/iputil"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type FirewallInterface interface {
|
type FirewallInterface interface {
|
||||||
@@ -60,18 +59,12 @@ type Firewall struct {
|
|||||||
|
|
||||||
// assignedNetworks is a list of vpn networks assigned to us in the certificate.
|
// assignedNetworks is a list of vpn networks assigned to us in the certificate.
|
||||||
assignedNetworks []netip.Prefix
|
assignedNetworks []netip.Prefix
|
||||||
// vpnNetworks holds assignedNetworks for lookup: a source address inside one of them
|
|
||||||
// belongs to a node of the overlay, and only that node may send as it.
|
|
||||||
vpnNetworks *bart.Lite
|
|
||||||
// unsafeNetworks is the list of unsafe networks issued to us in the certificate
|
// unsafeNetworks is the list of unsafe networks issued to us in the certificate
|
||||||
unsafeNetworks []netip.Prefix
|
unsafeNetworks []netip.Prefix
|
||||||
|
|
||||||
rules string
|
rules string
|
||||||
rulesVersion uint16
|
rulesVersion uint16
|
||||||
|
|
||||||
// source is the rendered firewall config this firewall was built from, the cert networks are kept above
|
|
||||||
source string
|
|
||||||
|
|
||||||
defaultLocalCIDRAny bool
|
defaultLocalCIDRAny bool
|
||||||
incomingMetrics firewallMetrics
|
incomingMetrics firewallMetrics
|
||||||
outgoingMetrics firewallMetrics
|
outgoingMetrics firewallMetrics
|
||||||
@@ -159,12 +152,10 @@ func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Dur
|
|||||||
}
|
}
|
||||||
|
|
||||||
routableNetworks := new(bart.Lite)
|
routableNetworks := new(bart.Lite)
|
||||||
vpnNetworks := new(bart.Lite)
|
|
||||||
var assignedNetworks []netip.Prefix
|
var assignedNetworks []netip.Prefix
|
||||||
for _, network := range c.Networks() {
|
for _, network := range c.Networks() {
|
||||||
nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
|
nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
|
||||||
routableNetworks.Insert(nprefix)
|
routableNetworks.Insert(nprefix)
|
||||||
vpnNetworks.Insert(network)
|
|
||||||
assignedNetworks = append(assignedNetworks, network)
|
assignedNetworks = append(assignedNetworks, network)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +176,6 @@ func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Dur
|
|||||||
DefaultTimeout: defaultTimeout,
|
DefaultTimeout: defaultTimeout,
|
||||||
routableNetworks: routableNetworks,
|
routableNetworks: routableNetworks,
|
||||||
assignedNetworks: assignedNetworks,
|
assignedNetworks: assignedNetworks,
|
||||||
vpnNetworks: vpnNetworks,
|
|
||||||
unsafeNetworks: unsafeNetworks,
|
unsafeNetworks: unsafeNetworks,
|
||||||
l: l,
|
l: l,
|
||||||
|
|
||||||
@@ -212,25 +202,11 @@ func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewal
|
|||||||
panic("No certificate available to reconfigure the firewall")
|
panic("No certificate available to reconfigure the firewall")
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpTimeout := c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12)
|
|
||||||
udpTimeout := c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3)
|
|
||||||
defaultTimeout := c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10)
|
|
||||||
|
|
||||||
if tcpTimeout <= 0 {
|
|
||||||
return nil, fmt.Errorf("firewall.conntrack.tcp_timeout must be greater than 0, got: %s", tcpTimeout)
|
|
||||||
}
|
|
||||||
if udpTimeout <= 0 {
|
|
||||||
return nil, fmt.Errorf("firewall.conntrack.udp_timeout must be greater than 0, got: %s", udpTimeout)
|
|
||||||
}
|
|
||||||
if defaultTimeout <= 0 {
|
|
||||||
return nil, fmt.Errorf("firewall.conntrack.default_timeout must be greater than 0, got: %s", defaultTimeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
fw := NewFirewall(
|
fw := NewFirewall(
|
||||||
l,
|
l,
|
||||||
tcpTimeout,
|
c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12),
|
||||||
udpTimeout,
|
c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3),
|
||||||
defaultTimeout,
|
c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10),
|
||||||
certificate,
|
certificate,
|
||||||
//TODO: max_connections
|
//TODO: max_connections
|
||||||
)
|
)
|
||||||
@@ -269,7 +245,6 @@ func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewal
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
fw.source = c.Render("firewall")
|
|
||||||
return fw, nil
|
return fw, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,11 +262,11 @@ func (f *Firewall) AddRule(incoming bool, proto uint8, startPort int32, endPort
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch proto {
|
switch proto {
|
||||||
case iputil.IPProtocolTCP:
|
case firewall.ProtoTCP:
|
||||||
fp = ft.TCP
|
fp = ft.TCP
|
||||||
case iputil.IPProtocolUDP:
|
case firewall.ProtoUDP:
|
||||||
fp = ft.UDP
|
fp = ft.UDP
|
||||||
case iputil.IPProtocolICMP, iputil.IPProtocolICMPv6:
|
case firewall.ProtoICMP, firewall.ProtoICMPv6:
|
||||||
//ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
|
//ICMP traffic doesn't have ports, so we always coerce to "any", even if a value is provided
|
||||||
if startPort != firewall.PortAny {
|
if startPort != firewall.PortAny {
|
||||||
f.l.Warn("ignoring port specification for ICMP firewall rule", "startPort", startPort)
|
f.l.Warn("ignoring port specification for ICMP firewall rule", "startPort", startPort)
|
||||||
@@ -389,13 +364,13 @@ func AddFirewallRulesFromConfig(l *slog.Logger, inbound bool, c *config.C, fw Fi
|
|||||||
proto = firewall.ProtoAny
|
proto = firewall.ProtoAny
|
||||||
startPort, endPort, err = parsePort(sPort)
|
startPort, endPort, err = parsePort(sPort)
|
||||||
case "tcp":
|
case "tcp":
|
||||||
proto = iputil.IPProtocolTCP
|
proto = firewall.ProtoTCP
|
||||||
startPort, endPort, err = parsePort(sPort)
|
startPort, endPort, err = parsePort(sPort)
|
||||||
case "udp":
|
case "udp":
|
||||||
proto = iputil.IPProtocolUDP
|
proto = firewall.ProtoUDP
|
||||||
startPort, endPort, err = parsePort(sPort)
|
startPort, endPort, err = parsePort(sPort)
|
||||||
case "icmp":
|
case "icmp":
|
||||||
proto = iputil.IPProtocolICMP
|
proto = firewall.ProtoICMP
|
||||||
startPort = firewall.PortAny
|
startPort = firewall.PortAny
|
||||||
endPort = firewall.PortAny
|
endPort = firewall.PortAny
|
||||||
if sPort != "" {
|
if sPort != "" {
|
||||||
@@ -468,17 +443,7 @@ func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *
|
|||||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||||
return ErrPeerRejected // reject for now, one day this may have different FW rules
|
return ErrPeerRejected // reject for now, one day this may have different FW rules
|
||||||
case NetworkTypeUnsafe:
|
case NetworkTypeUnsafe:
|
||||||
// An unsafe network says what a peer routes for, never who it is. One that
|
break // nothing special, one day this may have different FW rules
|
||||||
// overlaps our own networks would let the peer send as any node of the overlay,
|
|
||||||
// and whatever trusts the source address, the firewall's own rules and the
|
|
||||||
// identity a program looks up for it, would be told the wrong node. A source
|
|
||||||
// inside our networks is a node's own address, which only that node sends
|
|
||||||
// from, as NetworkTypeVPN, matched first; through an unsafe network it is
|
|
||||||
// refused. Outbound the address is a destination and claims nothing.
|
|
||||||
if incoming && f.vpnNetworks.Contains(fp.RemoteAddr) {
|
|
||||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
|
||||||
return ErrInvalidRemoteIP
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||||
return ErrUnknownNetworkType //should never happen
|
return ErrUnknownNetworkType //should never happen
|
||||||
@@ -595,9 +560,9 @@ func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool,
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch fp.Protocol {
|
switch fp.Protocol {
|
||||||
case iputil.IPProtocolTCP:
|
case firewall.ProtoTCP:
|
||||||
c.Expires = time.Now().Add(f.TCPTimeout)
|
c.Expires = time.Now().Add(f.TCPTimeout)
|
||||||
case iputil.IPProtocolUDP:
|
case firewall.ProtoUDP:
|
||||||
c.Expires = time.Now().Add(f.UDPTimeout)
|
c.Expires = time.Now().Add(f.UDPTimeout)
|
||||||
default:
|
default:
|
||||||
c.Expires = time.Now().Add(f.DefaultTimeout)
|
c.Expires = time.Now().Add(f.DefaultTimeout)
|
||||||
@@ -617,9 +582,9 @@ func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
|
|||||||
c := &conn{}
|
c := &conn{}
|
||||||
|
|
||||||
switch fp.Protocol {
|
switch fp.Protocol {
|
||||||
case iputil.IPProtocolTCP:
|
case firewall.ProtoTCP:
|
||||||
timeout = f.TCPTimeout
|
timeout = f.TCPTimeout
|
||||||
case iputil.IPProtocolUDP:
|
case firewall.ProtoUDP:
|
||||||
timeout = f.UDPTimeout
|
timeout = f.UDPTimeout
|
||||||
default:
|
default:
|
||||||
timeout = f.DefaultTimeout
|
timeout = f.DefaultTimeout
|
||||||
@@ -670,15 +635,15 @@ func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedC
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch p.Protocol {
|
switch p.Protocol {
|
||||||
case iputil.IPProtocolTCP:
|
case firewall.ProtoTCP:
|
||||||
if ft.TCP.match(p, incoming, c, caPool) {
|
if ft.TCP.match(p, incoming, c, caPool) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
case iputil.IPProtocolUDP:
|
case firewall.ProtoUDP:
|
||||||
if ft.UDP.match(p, incoming, c, caPool) {
|
if ft.UDP.match(p, incoming, c, caPool) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
case iputil.IPProtocolICMP, iputil.IPProtocolICMPv6:
|
case firewall.ProtoICMP, firewall.ProtoICMPv6:
|
||||||
if ft.ICMP.match(p, incoming, c, caPool) {
|
if ft.ICMP.match(p, incoming, c, caPool) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -715,7 +680,7 @@ func (fp firewallPort) match(p firewall.Packet, incoming bool, c *cert.CachedCer
|
|||||||
}
|
}
|
||||||
|
|
||||||
// this branch is here to catch traffic from FirewallTable.Any.match and FirewallTable.ICMP.match
|
// this branch is here to catch traffic from FirewallTable.Any.match and FirewallTable.ICMP.match
|
||||||
if p.Protocol == iputil.IPProtocolICMP || p.Protocol == iputil.IPProtocolICMPv6 {
|
if p.Protocol == firewall.ProtoICMP || p.Protocol == firewall.ProtoICMPv6 {
|
||||||
// port numbers are re-used for connection tracking of ICMP,
|
// port numbers are re-used for connection tracking of ICMP,
|
||||||
// but we don't want to actually filter on them.
|
// but we don't want to actually filter on them.
|
||||||
return fp[firewall.PortAny].match(p, c, caPool)
|
return fp[firewall.PortAny].match(p, c, caPool)
|
||||||
|
|||||||
+2
-4
@@ -5,8 +5,6 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/logging"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConntrackCache is used as a local routine cache to know if a given flow
|
// ConntrackCache is used as a local routine cache to know if a given flow
|
||||||
@@ -58,8 +56,8 @@ func (c *ConntrackCacheTicker) Get() ConntrackCache {
|
|||||||
if tick := c.cacheTick.Load(); tick != c.cacheV {
|
if tick := c.cacheTick.Load(); tick != c.cacheV {
|
||||||
c.cacheV = tick
|
c.cacheV = tick
|
||||||
if ll := len(c.cache); ll > 0 {
|
if ll := len(c.cache); ll > 0 {
|
||||||
if c.l.Enabled(context.Background(), logging.LevelTrace) {
|
if c.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
c.l.Log(context.Background(), logging.LevelTrace, "resetting conntrack cache", "len", ll)
|
c.l.Debug("resetting conntrack cache", "len", ll)
|
||||||
}
|
}
|
||||||
c.cache = make(ConntrackCache, ll)
|
c.cache = make(ConntrackCache, ll)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/logging"
|
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
@@ -22,7 +21,7 @@ func newFixedTicker(t *testing.T, l *slog.Logger, cacheLen int) *ConntrackCacheT
|
|||||||
l: l,
|
l: l,
|
||||||
cache: make(ConntrackCache, cacheLen),
|
cache: make(ConntrackCache, cacheLen),
|
||||||
}
|
}
|
||||||
for i := range cacheLen {
|
for i := 0; i < cacheLen; i++ {
|
||||||
c.cache[Packet{LocalPort: uint16(i) + 1}] = struct{}{}
|
c.cache[Packet{LocalPort: uint16(i) + 1}] = struct{}{}
|
||||||
}
|
}
|
||||||
c.cacheTick.Store(1) // cacheV starts at 0, so Get() takes the reset path
|
c.cacheTick.Store(1) // cacheV starts at 0, so Get() takes the reset path
|
||||||
@@ -31,27 +30,27 @@ func newFixedTicker(t *testing.T, l *slog.Logger, cacheLen int) *ConntrackCacheT
|
|||||||
|
|
||||||
func TestConntrackCacheTicker_Get_TextFormat(t *testing.T) {
|
func TestConntrackCacheTicker_Get_TextFormat(t *testing.T) {
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
l := test.NewLoggerWithOutputAndLevel(buf, logging.LevelTrace)
|
l := test.NewLoggerWithOutputAndLevel(buf, slog.LevelDebug)
|
||||||
|
|
||||||
c := newFixedTicker(t, l, 3)
|
c := newFixedTicker(t, l, 3)
|
||||||
c.Get()
|
c.Get()
|
||||||
|
|
||||||
assert.Equal(t, "level=DEBUG-4 msg=\"resetting conntrack cache\" len=3\n", buf.String())
|
assert.Equal(t, "level=DEBUG msg=\"resetting conntrack cache\" len=3\n", buf.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConntrackCacheTicker_Get_JSONFormat(t *testing.T) {
|
func TestConntrackCacheTicker_Get_JSONFormat(t *testing.T) {
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
l := test.NewJSONLoggerWithOutput(buf, logging.LevelTrace)
|
l := test.NewJSONLoggerWithOutput(buf, slog.LevelDebug)
|
||||||
|
|
||||||
c := newFixedTicker(t, l, 2)
|
c := newFixedTicker(t, l, 2)
|
||||||
c.Get()
|
c.Get()
|
||||||
|
|
||||||
assert.JSONEq(t, `{"level":"DEBUG-4","msg":"resetting conntrack cache","len":2}`, strings.TrimSpace(buf.String()))
|
assert.JSONEq(t, `{"level":"DEBUG","msg":"resetting conntrack cache","len":2}`, strings.TrimSpace(buf.String()))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConntrackCacheTicker_Get_QuietBelowTrace(t *testing.T) {
|
func TestConntrackCacheTicker_Get_QuietBelowDebug(t *testing.T) {
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
l := test.NewLoggerWithOutputAndLevel(buf, slog.LevelDebug)
|
l := test.NewLoggerWithOutputAndLevel(buf, slog.LevelInfo)
|
||||||
|
|
||||||
c := newFixedTicker(t, l, 5)
|
c := newFixedTicker(t, l, 5)
|
||||||
c.Get()
|
c.Get()
|
||||||
@@ -61,7 +60,7 @@ func TestConntrackCacheTicker_Get_QuietBelowTrace(t *testing.T) {
|
|||||||
|
|
||||||
func TestConntrackCacheTicker_Get_QuietWhenCacheEmpty(t *testing.T) {
|
func TestConntrackCacheTicker_Get_QuietWhenCacheEmpty(t *testing.T) {
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
l := test.NewLoggerWithOutputAndLevel(buf, logging.LevelTrace)
|
l := test.NewLoggerWithOutputAndLevel(buf, slog.LevelDebug)
|
||||||
|
|
||||||
c := newFixedTicker(t, l, 0)
|
c := newFixedTicker(t, l, 0)
|
||||||
c.Get()
|
c.Get()
|
||||||
|
|||||||
+10
-16
@@ -4,14 +4,17 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/iputil"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type m = map[string]any
|
type m = map[string]any
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ProtoAny = 0 // When we want to handle HOPOPT (0) we can change this, if ever
|
ProtoAny = 0 // When we want to handle HOPOPT (0) we can change this, if ever
|
||||||
|
ProtoTCP = 6
|
||||||
|
ProtoUDP = 17
|
||||||
|
ProtoICMP = 1
|
||||||
|
ProtoICMPv6 = 58
|
||||||
|
|
||||||
PortAny = 0 // Special value for matching `port: any`
|
PortAny = 0 // Special value for matching `port: any`
|
||||||
PortFragment = -1 // Special value for matching `port: fragment`
|
PortFragment = -1 // Special value for matching `port: fragment`
|
||||||
)
|
)
|
||||||
@@ -42,13 +45,13 @@ func (fp *Packet) Copy() *Packet {
|
|||||||
func (fp Packet) MarshalJSON() ([]byte, error) {
|
func (fp Packet) MarshalJSON() ([]byte, error) {
|
||||||
var proto string
|
var proto string
|
||||||
switch fp.Protocol {
|
switch fp.Protocol {
|
||||||
case iputil.IPProtocolTCP:
|
case ProtoTCP:
|
||||||
proto = "tcp"
|
proto = "tcp"
|
||||||
case iputil.IPProtocolICMP:
|
case ProtoICMP:
|
||||||
proto = "icmp"
|
proto = "icmp"
|
||||||
case iputil.IPProtocolICMPv6:
|
case ProtoICMPv6:
|
||||||
proto = "icmpv6"
|
proto = "icmpv6"
|
||||||
case iputil.IPProtocolUDP:
|
case ProtoUDP:
|
||||||
proto = "udp"
|
proto = "udp"
|
||||||
default:
|
default:
|
||||||
proto = fmt.Sprintf("unknown %v", fp.Protocol)
|
proto = fmt.Sprintf("unknown %v", fp.Protocol)
|
||||||
@@ -62,12 +65,3 @@ func (fp Packet) MarshalJSON() ([]byte, error) {
|
|||||||
"Fragment": fp.Fragment,
|
"Fragment": fp.Fragment,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParsedPacket is a Packet plus the parse byproducts the RX path reuses
|
|
||||||
type ParsedPacket struct {
|
|
||||||
Packet
|
|
||||||
IPHdrLen int
|
|
||||||
// FragAny reports any fragmentation at all: MF flag or nonzero offset for IPv4, a fragment extension header for IPv6.
|
|
||||||
// Distinct from Packet.Fragment, which is true only for NON-FIRST fragments
|
|
||||||
FragAny bool
|
|
||||||
}
|
|
||||||
+33
-111
@@ -13,7 +13,6 @@ import (
|
|||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/slackhq/nebula/iputil"
|
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
@@ -58,31 +57,6 @@ func TestNewFirewall(t *testing.T) {
|
|||||||
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewFirewall_ZeroOrNegativeTimeout(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
c := &dummyCert{}
|
|
||||||
cs := &CertState{v2Cert: c, initiatingVersion: cert.Version2}
|
|
||||||
|
|
||||||
cases := map[string]string{
|
|
||||||
"tcp_timeout zero": "firewall:\n conntrack:\n tcp_timeout: 0s\n",
|
|
||||||
"tcp_timeout negative": "firewall:\n conntrack:\n tcp_timeout: -5s\n",
|
|
||||||
"udp_timeout zero": "firewall:\n conntrack:\n udp_timeout: 0s\n",
|
|
||||||
"udp_timeout negative": "firewall:\n conntrack:\n udp_timeout: -5s\n",
|
|
||||||
"default_timeout zero": "firewall:\n conntrack:\n default_timeout: 0s\n",
|
|
||||||
"default_timeout negative": "firewall:\n conntrack:\n default_timeout: -5s\n",
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, cfgStr := range cases {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
cfg := config.NewC(l)
|
|
||||||
require.NoError(t, cfg.LoadString(cfgStr))
|
|
||||||
_, err := NewFirewallFromConfig(l, cs, cfg)
|
|
||||||
require.Error(t, err, "expected error for non-positive timeout duration")
|
|
||||||
assert.ErrorContains(t, err, "must be greater than 0")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFirewall_AddRule(t *testing.T) {
|
func TestFirewall_AddRule(t *testing.T) {
|
||||||
ob := &bytes.Buffer{}
|
ob := &bytes.Buffer{}
|
||||||
l := test.NewLoggerWithOutput(ob)
|
l := test.NewLoggerWithOutput(ob)
|
||||||
@@ -98,20 +72,20 @@ func TestFirewall_AddRule(t *testing.T) {
|
|||||||
ti6, err := netip.ParsePrefix("fd12::34/128")
|
ti6, err := netip.ParsePrefix("fd12::34/128")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
require.NoError(t, fw.AddRule(true, iputil.IPProtocolTCP, 1, 1, []string{}, "", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoTCP, 1, 1, []string{}, "", "", "", "", ""))
|
||||||
// An empty rule is any
|
// An empty rule is any
|
||||||
assert.True(t, fw.InRules.TCP[1].Any.Any.Any)
|
assert.True(t, fw.InRules.TCP[1].Any.Any.Any)
|
||||||
assert.Empty(t, fw.InRules.TCP[1].Any.Groups)
|
assert.Empty(t, fw.InRules.TCP[1].Any.Groups)
|
||||||
assert.Empty(t, fw.InRules.TCP[1].Any.Hosts)
|
assert.Empty(t, fw.InRules.TCP[1].Any.Hosts)
|
||||||
|
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
||||||
require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", "", "", "", ""))
|
||||||
assert.Nil(t, fw.InRules.UDP[1].Any.Any)
|
assert.Nil(t, fw.InRules.UDP[1].Any.Any)
|
||||||
assert.Contains(t, fw.InRules.UDP[1].Any.Groups[0].Groups, "g1")
|
assert.Contains(t, fw.InRules.UDP[1].Any.Groups[0].Groups, "g1")
|
||||||
assert.Empty(t, fw.InRules.UDP[1].Any.Hosts)
|
assert.Empty(t, fw.InRules.UDP[1].Any.Hosts)
|
||||||
|
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
||||||
require.NoError(t, fw.AddRule(true, iputil.IPProtocolICMP, 1, 1, []string{}, "h1", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoICMP, 1, 1, []string{}, "h1", "", "", "", ""))
|
||||||
//no matter what port is given for icmp, it should end up as "any"
|
//no matter what port is given for icmp, it should end up as "any"
|
||||||
assert.Nil(t, fw.InRules.ICMP[firewall.PortAny].Any.Any)
|
assert.Nil(t, fw.InRules.ICMP[firewall.PortAny].Any.Any)
|
||||||
assert.Empty(t, fw.InRules.ICMP[firewall.PortAny].Any.Groups)
|
assert.Empty(t, fw.InRules.ICMP[firewall.PortAny].Any.Groups)
|
||||||
@@ -142,11 +116,11 @@ func TestFirewall_AddRule(t *testing.T) {
|
|||||||
assert.True(t, ok)
|
assert.True(t, ok)
|
||||||
|
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
||||||
require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "ca-name", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", "", "", "ca-name", ""))
|
||||||
assert.Contains(t, fw.InRules.UDP[1].CANames, "ca-name")
|
assert.Contains(t, fw.InRules.UDP[1].CANames, "ca-name")
|
||||||
|
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
||||||
require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 1, 1, []string{"g1"}, "", "", "", "", "ca-sha"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", "", "", "", "ca-sha"))
|
||||||
assert.Contains(t, fw.InRules.UDP[1].CAShas, "ca-sha")
|
assert.Contains(t, fw.InRules.UDP[1].CAShas, "ca-sha")
|
||||||
|
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
||||||
@@ -211,7 +185,7 @@ func TestFirewall_Drop(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
||||||
LocalPort: 10,
|
LocalPort: 10,
|
||||||
RemotePort: 90,
|
RemotePort: 90,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,58 +251,6 @@ func TestFirewall_Drop(t *testing.T) {
|
|||||||
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestFirewall_DropOverlaySourceThroughUnsafeNetwork: a peer whose unsafe network
|
|
||||||
// overlaps our overlay may not send as another node of it. Its own address and sources
|
|
||||||
// outside the overlay still pass through the unsafe network, and outbound to such an
|
|
||||||
// address, where the address is a destination, is not the firewall's to refuse here.
|
|
||||||
func TestFirewall_DropOverlaySourceThroughUnsafeNetwork(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
myVpnNetworksTable := new(bart.Lite)
|
|
||||||
myVpnNetworksTable.Insert(netip.MustParsePrefix("1.2.3.0/24"))
|
|
||||||
|
|
||||||
me := dummyCert{name: "me", networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")}}
|
|
||||||
// A router for 1.2.0.0/16, which contains the whole overlay.
|
|
||||||
peer := dummyCert{
|
|
||||||
name: "router",
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.9/24")},
|
|
||||||
unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("1.2.0.0/16")},
|
|
||||||
groups: []string{"default-group"},
|
|
||||||
}
|
|
||||||
h := HostInfo{
|
|
||||||
ConnectionState: &ConnectionState{
|
|
||||||
peerCert: &cert.CachedCertificate{Certificate: &peer, InvertedGroups: map[string]struct{}{"default-group": {}}},
|
|
||||||
},
|
|
||||||
vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.9")},
|
|
||||||
}
|
|
||||||
h.buildNetworks(myVpnNetworksTable, &peer)
|
|
||||||
|
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &me)
|
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
|
||||||
cp := cert.NewCAPool()
|
|
||||||
packet := func(remote string) firewall.Packet {
|
|
||||||
return firewall.Packet{
|
|
||||||
LocalAddr: netip.MustParseAddr("1.2.3.4"),
|
|
||||||
RemoteAddr: netip.MustParseAddr(remote),
|
|
||||||
LocalPort: 10,
|
|
||||||
RemotePort: 90,
|
|
||||||
Protocol: iputil.IPProtocolUDP,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Another node's overlay address, through the unsafe network: refused.
|
|
||||||
assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(packet("1.2.3.10"), true, &h, cp, nil))
|
|
||||||
assert.Equal(t, int64(1), fw.incomingMetrics.droppedRemoteAddr.Count())
|
|
||||||
|
|
||||||
// The peer's own address, and an address outside the overlay it routes for: served.
|
|
||||||
require.NoError(t, fw.Drop(packet("1.2.3.9"), true, &h, cp, nil))
|
|
||||||
require.NoError(t, fw.Drop(packet("1.2.5.5"), true, &h, cp, nil))
|
|
||||||
|
|
||||||
// Outbound to the overlay address via the router is not refused here; it meets the
|
|
||||||
// outbound rules as before.
|
|
||||||
resetConntrack(fw)
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(packet("1.2.3.10"), false, &h, cp, nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFirewall_DropV6(t *testing.T) {
|
func TestFirewall_DropV6(t *testing.T) {
|
||||||
ob := &bytes.Buffer{}
|
ob := &bytes.Buffer{}
|
||||||
l := test.NewLoggerWithOutput(ob)
|
l := test.NewLoggerWithOutput(ob)
|
||||||
@@ -341,7 +263,7 @@ func TestFirewall_DropV6(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("fd12::34"),
|
RemoteAddr: netip.MustParseAddr("fd12::34"),
|
||||||
LocalPort: 10,
|
LocalPort: 10,
|
||||||
RemotePort: 90,
|
RemotePort: 90,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -428,7 +350,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
Certificate: &dummyCert{},
|
Certificate: &dummyCert{},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolUDP}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoUDP}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -438,7 +360,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
Certificate: &dummyCert{},
|
Certificate: &dummyCert{},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 1}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 1}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -448,7 +370,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
}
|
}
|
||||||
ip := netip.MustParsePrefix("9.254.254.254/32")
|
ip := netip.MustParsePrefix("9.254.254.254/32")
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
b.Run("pass proto, port, fail on local CIDRv6", func(b *testing.B) {
|
b.Run("pass proto, port, fail on local CIDRv6", func(b *testing.B) {
|
||||||
@@ -457,7 +379,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
}
|
}
|
||||||
ip := netip.MustParsePrefix("fd99::99/128")
|
ip := netip.MustParsePrefix("fd99::99/128")
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -470,7 +392,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"nope": {}},
|
InvertedGroups: map[string]struct{}{"nope": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
b.Run("pass proto, port, any local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
|
b.Run("pass proto, port, any local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
|
||||||
@@ -482,7 +404,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"nope": {}},
|
InvertedGroups: map[string]struct{}{"nope": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -495,7 +417,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"nope": {}},
|
InvertedGroups: map[string]struct{}{"nope": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
b.Run("pass proto, port, specific local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
|
b.Run("pass proto, port, specific local CIDRv6, fail all group, name, and cidr", func(b *testing.B) {
|
||||||
@@ -507,7 +429,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"nope": {}},
|
InvertedGroups: map[string]struct{}{"nope": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -519,7 +441,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"good-group": {}},
|
InvertedGroups: map[string]struct{}{"good-group": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
|
assert.True(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -531,7 +453,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"good-group": {}},
|
InvertedGroups: map[string]struct{}{"good-group": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
|
assert.True(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
b.Run("pass on group on specific local cidr6", func(b *testing.B) {
|
b.Run("pass on group on specific local cidr6", func(b *testing.B) {
|
||||||
@@ -542,7 +464,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"good-group": {}},
|
InvertedGroups: map[string]struct{}{"good-group": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
assert.True(b, ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -554,7 +476,7 @@ func BenchmarkFirewallTable_match(b *testing.B) {
|
|||||||
InvertedGroups: map[string]struct{}{"nope": {}},
|
InvertedGroups: map[string]struct{}{"nope": {}},
|
||||||
}
|
}
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp)
|
ft.match(firewall.Packet{Protocol: firewall.ProtoTCP, LocalPort: 10}, true, c, cp)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -570,7 +492,7 @@ func TestFirewall_Drop2(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
||||||
LocalPort: 10,
|
LocalPort: 10,
|
||||||
RemotePort: 90,
|
RemotePort: 90,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -628,7 +550,7 @@ func TestFirewall_Drop3(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
||||||
LocalPort: 1,
|
LocalPort: 1,
|
||||||
RemotePort: 1,
|
RemotePort: 1,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,7 +638,7 @@ func TestFirewall_Drop3V6(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("fd12::34"),
|
RemoteAddr: netip.MustParseAddr("fd12::34"),
|
||||||
LocalPort: 1,
|
LocalPort: 1,
|
||||||
RemotePort: 1,
|
RemotePort: 1,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -753,7 +675,7 @@ func TestFirewall_DropConntrackReload(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
||||||
LocalPort: 10,
|
LocalPort: 10,
|
||||||
RemotePort: 90,
|
RemotePort: 90,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
network := netip.MustParsePrefix("1.2.3.4/24")
|
network := netip.MustParsePrefix("1.2.3.4/24")
|
||||||
@@ -836,13 +758,13 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
templ := firewall.Packet{
|
templ := firewall.Packet{
|
||||||
LocalAddr: netip.MustParseAddr("1.2.3.4"),
|
LocalAddr: netip.MustParseAddr("1.2.3.4"),
|
||||||
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
||||||
Protocol: iputil.IPProtocolICMP,
|
Protocol: firewall.ProtoICMP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("ICMP allowed", func(t *testing.T) {
|
t.Run("ICMP allowed", func(t *testing.T) {
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
||||||
require.NoError(t, fw.AddRule(true, iputil.IPProtocolICMP, 0, 0, []string{"any"}, "", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoICMP, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||||
t.Run("zero ports", func(t *testing.T) {
|
t.Run("zero ports", func(t *testing.T) {
|
||||||
p := templ.Copy()
|
p := templ.Copy()
|
||||||
p.LocalPort = 0
|
p.LocalPort = 0
|
||||||
@@ -988,7 +910,7 @@ func TestFirewall_DropIPSpoofing(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("192.0.2.3"),
|
RemoteAddr: netip.MustParseAddr("192.0.2.3"),
|
||||||
LocalPort: 1,
|
LocalPort: 1,
|
||||||
RemotePort: 1,
|
RemotePort: 1,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
assert.Equal(t, fw.Drop(p, true, &h1, cp, nil), ErrInvalidRemoteIP)
|
assert.Equal(t, fw.Drop(p, true, &h1, cp, nil), ErrInvalidRemoteIP)
|
||||||
@@ -1039,7 +961,7 @@ func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
|
|||||||
RemoteAddr: netip.MustParseAddr("192.0.2.2"),
|
RemoteAddr: netip.MustParseAddr("192.0.2.2"),
|
||||||
LocalPort: 443,
|
LocalPort: 443,
|
||||||
RemotePort: 55000,
|
RemotePort: 55000,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
|
require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
|
||||||
@@ -1109,7 +1031,7 @@ func BenchmarkFirewallDropConntrackHit(b *testing.B) {
|
|||||||
RemoteAddr: netip.MustParseAddr("192.0.2.2"),
|
RemoteAddr: netip.MustParseAddr("192.0.2.2"),
|
||||||
LocalPort: 443,
|
LocalPort: 443,
|
||||||
RemotePort: 55000,
|
RemotePort: 55000,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
@@ -1395,28 +1317,28 @@ func TestAddFirewallRulesFromConfig(t *testing.T) {
|
|||||||
mf := &mockFirewall{}
|
mf := &mockFirewall{}
|
||||||
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "tcp", "host": "a"}}}
|
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "tcp", "host": "a"}}}
|
||||||
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
||||||
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolTCP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoTCP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
||||||
|
|
||||||
// Test adding udp rule
|
// Test adding udp rule
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
mf = &mockFirewall{}
|
mf = &mockFirewall{}
|
||||||
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "udp", "host": "a"}}}
|
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "udp", "host": "a"}}}
|
||||||
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
||||||
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolUDP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoUDP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
||||||
|
|
||||||
// Test adding icmp rule
|
// Test adding icmp rule
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
mf = &mockFirewall{}
|
mf = &mockFirewall{}
|
||||||
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "icmp", "host": "a"}}}
|
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"port": "1", "proto": "icmp", "host": "a"}}}
|
||||||
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
||||||
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
||||||
|
|
||||||
// Test adding icmp rule no port
|
// Test adding icmp rule no port
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
mf = &mockFirewall{}
|
mf = &mockFirewall{}
|
||||||
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"proto": "icmp", "host": "a"}}}
|
conf.Settings["firewall"] = map[string]any{"outbound": []any{map[string]any{"proto": "icmp", "host": "a"}}}
|
||||||
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
require.NoError(t, AddFirewallRulesFromConfig(l, false, conf, mf))
|
||||||
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: firewall.ProtoICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
||||||
|
|
||||||
// Test adding any rule
|
// Test adding any rule
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
@@ -1660,7 +1582,7 @@ func buildTestCase(setup testsetup, err error, theirPrefixes ...netip.Prefix) te
|
|||||||
RemoteAddr: theirPrefixes[0].Addr(),
|
RemoteAddr: theirPrefixes[0].Addr(),
|
||||||
LocalPort: 10,
|
LocalPort: 10,
|
||||||
RemotePort: 90,
|
RemotePort: 90,
|
||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: firewall.ProtoUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
return testcase{
|
return testcase{
|
||||||
|
|||||||
@@ -1,50 +1,56 @@
|
|||||||
module github.com/slackhq/nebula
|
module github.com/slackhq/nebula
|
||||||
|
|
||||||
go 1.27.2
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
dario.cat/mergo v1.0.2
|
dario.cat/mergo v1.0.2
|
||||||
filippo.io/bigmod v0.1.0
|
filippo.io/bigmod v0.1.0
|
||||||
github.com/DefinedNet/netlink v1.3.2-dn.1
|
|
||||||
github.com/Microsoft/go-winio v0.6.2
|
|
||||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
|
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
|
||||||
|
github.com/armon/go-radix v1.0.0
|
||||||
|
github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432
|
||||||
github.com/flynn/noise v1.1.0
|
github.com/flynn/noise v1.1.0
|
||||||
github.com/gaissmai/bart v0.29.0
|
github.com/gaissmai/bart v0.28.0
|
||||||
github.com/gogo/protobuf v1.3.2
|
github.com/gogo/protobuf v1.3.2
|
||||||
github.com/google/gopacket v1.1.19
|
github.com/google/gopacket v1.1.19
|
||||||
github.com/kardianos/service v1.3.0
|
github.com/kardianos/service v1.3.0
|
||||||
github.com/miekg/dns v1.1.73
|
github.com/miekg/dns v1.1.72
|
||||||
github.com/miekg/pkcs11 v1.1.2
|
github.com/miekg/pkcs11 v1.1.2
|
||||||
github.com/nbrownus/go-metrics-prometheus v0.0.0-20210712211119-974a6260965f
|
github.com/nbrownus/go-metrics-prometheus v0.0.0-20210712211119-974a6260965f
|
||||||
github.com/prometheus/client_golang v1.24.1
|
github.com/prometheus/client_golang v1.23.2
|
||||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475
|
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475
|
||||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||||
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6
|
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6
|
||||||
github.com/stretchr/testify v1.12.1
|
github.com/stretchr/testify v1.11.1
|
||||||
|
github.com/vishvananda/netlink v1.3.1
|
||||||
go.uber.org/goleak v1.3.0
|
go.uber.org/goleak v1.3.0
|
||||||
go.yaml.in/yaml/v3 v3.0.5
|
go.yaml.in/yaml/v3 v3.0.4
|
||||||
golang.org/x/crypto v0.57.0
|
golang.org/x/crypto v0.54.0
|
||||||
golang.org/x/net v0.59.0
|
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090
|
||||||
golang.org/x/sync v0.23.0
|
golang.org/x/net v0.57.0
|
||||||
golang.org/x/sys v0.48.0
|
golang.org/x/sync v0.22.0
|
||||||
golang.org/x/term v0.46.0
|
golang.org/x/sys v0.47.0
|
||||||
|
golang.org/x/term v0.45.0
|
||||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b
|
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b
|
||||||
golang.zx2c4.com/wireguard/windows v1.0.1
|
golang.zx2c4.com/wireguard/windows v1.0.1
|
||||||
google.golang.org/protobuf v1.36.12
|
google.golang.org/protobuf v1.36.11
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980
|
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/beorn7/perks v1.0.1 // indirect
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/google/btree v1.1.2 // indirect
|
github.com/google/btree v1.1.2 // indirect
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/prometheus/client_model v0.6.2 // indirect
|
github.com/prometheus/client_model v0.6.2 // indirect
|
||||||
github.com/prometheus/common v0.70.1 // indirect
|
github.com/prometheus/common v0.66.1 // indirect
|
||||||
github.com/prometheus/procfs v0.21.1 // indirect
|
github.com/prometheus/procfs v0.16.1 // indirect
|
||||||
github.com/vishvananda/netns v0.0.5 // indirect
|
github.com/vishvananda/netns v0.0.5 // indirect
|
||||||
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc // indirect
|
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||||
golang.org/x/time v0.15.0 // indirect
|
golang.org/x/mod v0.36.0 // indirect
|
||||||
|
golang.org/x/time v0.5.0 // indirect
|
||||||
|
golang.org/x/tools v0.45.0 // indirect
|
||||||
)
|
)
|
||||||
@@ -3,10 +3,6 @@ dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
|||||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||||
filippo.io/bigmod v0.1.0 h1:UNzDk7y9ADKST+axd9skUpBQeW7fG2KrTZyOE4uGQy8=
|
filippo.io/bigmod v0.1.0 h1:UNzDk7y9ADKST+axd9skUpBQeW7fG2KrTZyOE4uGQy8=
|
||||||
filippo.io/bigmod v0.1.0/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
|
filippo.io/bigmod v0.1.0/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
|
||||||
github.com/DefinedNet/netlink v1.3.2-dn.1 h1:Md2PsUE1Xuy1Zxs/Bm6356n1kt5bq2HspXlPJ6pEspg=
|
|
||||||
github.com/DefinedNet/netlink v1.3.2-dn.1/go.mod h1:o4YSn8Jw7zoDcYXDmV77TRd4eS5sSLuE+vu2zAN67C8=
|
|
||||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
|
||||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
|
||||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||||
@@ -14,6 +10,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
|
|||||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
||||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||||
|
github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI=
|
||||||
|
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
|
||||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||||
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
||||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
@@ -21,12 +19,15 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r
|
|||||||
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432 h1:M5QgkYacWj0Xs8MhpIK/5uwU02icXpEoSo9sM2aRCps=
|
||||||
|
github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432/go.mod h1:xwIwAxMvYnVrGJPe2FKx5prTrnAjGOD8zvDOnxnrrkM=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg=
|
github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg=
|
||||||
github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag=
|
github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag=
|
||||||
github.com/gaissmai/bart v0.29.0 h1:wO6HGE8g9YE0Wm0bCpYxwRzfQ4+fbJKOhL64e5ACGCI=
|
github.com/gaissmai/bart v0.28.0 h1:89yZLo8NmyqD0RYgJ3QO9HhqqGGw+oWhf90cZm69Lko=
|
||||||
github.com/gaissmai/bart v0.29.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
|
github.com/gaissmai/bart v0.28.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
|
||||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||||
@@ -69,22 +70,23 @@ github.com/kardianos/service v1.3.0 h1:/LGy+xPP2TM+GLTiCZ2di7cy0Jd/qrawlTUfqKYFd
|
|||||||
github.com/kardianos/service v1.3.0/go.mod h1:E4V9ufUuY82F7Ztlu1eN9VXWIQxg8NoLQlmFe0MtrXc=
|
github.com/kardianos/service v1.3.0/go.mod h1:E4V9ufUuY82F7Ztlu1eN9VXWIQxg8NoLQlmFe0MtrXc=
|
||||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
|
|
||||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||||
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||||
github.com/miekg/pkcs11 v1.1.2 h1:/VxmeAX5qU6Q3EwafypogwWbYryHFmF2RpkJmw3m4MQ=
|
github.com/miekg/pkcs11 v1.1.2 h1:/VxmeAX5qU6Q3EwafypogwWbYryHFmF2RpkJmw3m4MQ=
|
||||||
github.com/miekg/pkcs11 v1.1.2/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=
|
github.com/miekg/pkcs11 v1.1.2/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
@@ -100,13 +102,14 @@ github.com/nbrownus/go-metrics-prometheus v0.0.0-20210712211119-974a6260965f/go.
|
|||||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
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.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||||
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
||||||
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
||||||
github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
|
github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
|
||||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
@@ -115,16 +118,18 @@ github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvM
|
|||||||
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||||
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
|
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
|
||||||
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
|
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
|
||||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||||
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||||
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
||||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
|
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
|
||||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||||
@@ -138,31 +143,35 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
|
|||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
|
||||||
|
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
|
||||||
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||||
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc h1:TS73t7x3KarrNd5qAipmspBDS1rkMcgVG/fS1aRb4Rc=
|
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 h1:Di6/M8l0O2lCLc6VVRWhgCiApHV8MnQurBnFSHsQtNY=
|
||||||
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
|
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
|
||||||
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
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.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
|
||||||
|
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
|
||||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
@@ -173,8 +182,8 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL
|
|||||||
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
@@ -182,8 +191,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
|
|||||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
@@ -197,21 +206,25 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||||
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||||
|
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
|
||||||
|
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
@@ -230,8 +243,8 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE
|
|||||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
@@ -245,5 +258,5 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980 h1:ribyrTYQ/QYeUIs8x8bVLYwGyepa7RnHLqJzegT5YYk=
|
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe h1:fre4i6mv4iBuz5lCMOzHD1rH1ljqHWSICFmZRbbgp3g=
|
||||||
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980/go.mod h1:pK/dapF5Bf3KGW7/kd5CI5IC4lYh9FMFY1qETAIGLXk=
|
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe/go.mod h1:sxc3Uvk/vHcd3tj7/DHVBoR5wvWT/MmRq2pj7HRJnwU=
|
||||||
-130
@@ -1,130 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
// This file is a trimmed, inlined copy of the graphite exporter from
|
|
||||||
// github.com/cyberdelia/go-metrics-graphite, retaining only the Config type and
|
|
||||||
// the Once entrypoint that Nebula uses. The upstream package has been
|
|
||||||
// unmaintained for 10+ years, so it was vendored here to drop the dependency.
|
|
||||||
// See https://github.com/slackhq/nebula/issues/1831.
|
|
||||||
//
|
|
||||||
// Copyright 2015 Timothée Peignier. All rights reserved.
|
|
||||||
//
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are met:
|
|
||||||
//
|
|
||||||
// 1. Redistributions of source code must retain the above copyright notice,
|
|
||||||
// this list of conditions and the following disclaimer.
|
|
||||||
//
|
|
||||||
// 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
||||||
// this list of conditions and the following disclaimer in the documentation
|
|
||||||
// and/or other materials provided with the distribution.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
||||||
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
||||||
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
||||||
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
||||||
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
||||||
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
||||||
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
||||||
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
)
|
|
||||||
|
|
||||||
// graphiteConfigExport provides a container with configuration parameters for
|
|
||||||
// the Graphite exporter.
|
|
||||||
type graphiteConfigExport struct {
|
|
||||||
Addr *net.TCPAddr // Network address to connect to
|
|
||||||
Registry metrics.Registry // Registry to be exported
|
|
||||||
FlushInterval time.Duration // Flush interval
|
|
||||||
DurationUnit time.Duration // Time conversion unit for durations
|
|
||||||
Prefix string // Prefix to be prepended to metric names
|
|
||||||
Percentiles []float64 // Percentiles to export from timers and histograms
|
|
||||||
}
|
|
||||||
|
|
||||||
// graphiteTimeout bounds one submission, the connect and the write together. An export is a few KB, a host that can't
|
|
||||||
// take that in this long isn't going to.
|
|
||||||
const graphiteTimeout = 30 * time.Second
|
|
||||||
|
|
||||||
// graphiteOnce performs a single submission to Graphite, returning a non-nil
|
|
||||||
// error if it could not connect or write all of it within timeout. It gives up
|
|
||||||
// as soon as ctx is done.
|
|
||||||
func graphiteOnce(ctx context.Context, c graphiteConfigExport, timeout time.Duration) error {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
du := float64(c.DurationUnit)
|
|
||||||
flushSeconds := float64(c.FlushInterval) / float64(time.Second)
|
|
||||||
deadline := time.Now().Add(timeout)
|
|
||||||
d := net.Dialer{Deadline: deadline}
|
|
||||||
conn, err := d.DialContext(ctx, "tcp", c.Addr.String())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
if err := conn.SetDeadline(deadline); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
|
|
||||||
defer stop()
|
|
||||||
w := bufio.NewWriter(conn)
|
|
||||||
c.Registry.Each(func(name string, i any) {
|
|
||||||
switch metric := i.(type) {
|
|
||||||
case metrics.Counter:
|
|
||||||
count := metric.Count()
|
|
||||||
fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, count, now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.count_ps %.2f %d\n", c.Prefix, name, float64(count)/flushSeconds, now)
|
|
||||||
case metrics.Gauge:
|
|
||||||
fmt.Fprintf(w, "%s.%s.value %d %d\n", c.Prefix, name, metric.Value(), now)
|
|
||||||
case metrics.GaugeFloat64:
|
|
||||||
fmt.Fprintf(w, "%s.%s.value %f %d\n", c.Prefix, name, metric.Value(), now)
|
|
||||||
case metrics.Histogram:
|
|
||||||
h := metric.Snapshot()
|
|
||||||
ps := h.Percentiles(c.Percentiles)
|
|
||||||
fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, h.Count(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, h.Min(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, h.Max(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, h.Mean(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, h.StdDev(), now)
|
|
||||||
for psIdx, psKey := range c.Percentiles {
|
|
||||||
key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
|
|
||||||
fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now)
|
|
||||||
}
|
|
||||||
case metrics.Meter:
|
|
||||||
m := metric.Snapshot()
|
|
||||||
fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, m.Count(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, m.Rate1(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, m.Rate5(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, m.Rate15(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, m.RateMean(), now)
|
|
||||||
case metrics.Timer:
|
|
||||||
t := metric.Snapshot()
|
|
||||||
ps := t.Percentiles(c.Percentiles)
|
|
||||||
count := t.Count()
|
|
||||||
fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, count, now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.count_ps %.2f %d\n", c.Prefix, name, float64(count)/flushSeconds, now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, t.Min()/int64(du), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, t.Max()/int64(du), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, t.Mean()/du, now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, t.StdDev()/du, now)
|
|
||||||
for psIdx, psKey := range c.Percentiles {
|
|
||||||
key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
|
|
||||||
fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx]/du, now)
|
|
||||||
}
|
|
||||||
fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, t.Rate1(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, t.Rate5(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, t.Rate15(), now)
|
|
||||||
fmt.Fprintf(w, "%s.%s.mean-rate %.2f %d\n", c.Prefix, name, t.RateMean(), now)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
// A failed write sticks, so this reports the first one
|
|
||||||
return w.Flush()
|
|
||||||
}
|
|
||||||
@@ -1,315 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// graphiteHost accepts connections and hands each one to the test
|
|
||||||
type graphiteHost struct {
|
|
||||||
ln net.Listener
|
|
||||||
conns chan net.Conn
|
|
||||||
|
|
||||||
mu sync.Mutex
|
|
||||||
closed bool
|
|
||||||
open []net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// newGraphiteHost accepts connections for the test. A non-zero window shrinks each connection's receive buffer, so a
|
|
||||||
// sender that is not read from blocks after a little whatever the host's TCP tuning. Only for tests that need a stall,
|
|
||||||
// a small window makes reading very slow on Linux.
|
|
||||||
func newGraphiteHost(t *testing.T, window int) *graphiteHost {
|
|
||||||
t.Helper()
|
|
||||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
require.NoError(t, err)
|
|
||||||
h := &graphiteHost{ln: ln, conns: make(chan net.Conn, 8)}
|
|
||||||
done := make(chan struct{})
|
|
||||||
t.Cleanup(func() {
|
|
||||||
_ = ln.Close()
|
|
||||||
h.mu.Lock()
|
|
||||||
h.closed = true
|
|
||||||
for _, c := range h.open {
|
|
||||||
_ = c.Close()
|
|
||||||
}
|
|
||||||
h.mu.Unlock()
|
|
||||||
close(done)
|
|
||||||
})
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
c, err := ln.Accept()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.mu.Lock()
|
|
||||||
if h.closed {
|
|
||||||
h.mu.Unlock()
|
|
||||||
_ = c.Close()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.open = append(h.open, c)
|
|
||||||
h.mu.Unlock()
|
|
||||||
if tc, ok := c.(*net.TCPConn); ok && window > 0 {
|
|
||||||
_ = tc.SetReadBuffer(window)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case h.conns <- c:
|
|
||||||
case <-done:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *graphiteHost) addr(t *testing.T) *net.TCPAddr {
|
|
||||||
a, err := net.ResolveTCPAddr("tcp", h.ln.Addr().String())
|
|
||||||
require.NoError(t, err)
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
|
|
||||||
// readExport reads what one send wrote, bounded so a send that never finishes fails the test rather than hanging it
|
|
||||||
func readExport(t *testing.T, c net.Conn) []byte {
|
|
||||||
t.Helper()
|
|
||||||
require.NoError(t, c.SetReadDeadline(time.Now().Add(10*time.Second)))
|
|
||||||
b, err := io.ReadAll(c)
|
|
||||||
require.NoError(t, err)
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *graphiteHost) next(t *testing.T, wait time.Duration) net.Conn {
|
|
||||||
t.Helper()
|
|
||||||
select {
|
|
||||||
case c := <-h.conns:
|
|
||||||
return c
|
|
||||||
case <-time.After(wait):
|
|
||||||
t.Fatal("no connection")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// lockedBuffer is a log destination a test can read while the code under test writes to it from another goroutine
|
|
||||||
type lockedBuffer struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
buf bytes.Buffer
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *lockedBuffer) Write(p []byte) (int, error) {
|
|
||||||
b.mu.Lock()
|
|
||||||
defer b.mu.Unlock()
|
|
||||||
return b.buf.Write(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *lockedBuffer) String() string {
|
|
||||||
b.mu.Lock()
|
|
||||||
defer b.mu.Unlock()
|
|
||||||
return b.buf.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func testGraphiteConfig(addr *net.TCPAddr, r metrics.Registry) graphiteConfigExport {
|
|
||||||
return graphiteConfigExport{Addr: addr, Registry: r, FlushInterval: time.Second, DurationUnit: time.Nanosecond, Prefix: "nebula"}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enough metrics that one export overflows the socket buffers on any platform, so a send to a host that stops
|
|
||||||
// reading blocks
|
|
||||||
func bigGraphiteRegistry(r metrics.Registry, t *testing.T) {
|
|
||||||
for i := range 200000 {
|
|
||||||
name := fmt.Sprintf("big.gauge.%d", i)
|
|
||||||
metrics.GetOrRegisterGauge(name, r).Update(int64(i))
|
|
||||||
t.Cleanup(func() { r.Unregister(name) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGraphiteOnce_sends(t *testing.T) {
|
|
||||||
r := metrics.NewRegistry()
|
|
||||||
metrics.GetOrRegisterGauge("g", r).Update(7)
|
|
||||||
metrics.GetOrRegisterCounter("c", r).Inc(3)
|
|
||||||
h := newGraphiteHost(t, 0)
|
|
||||||
|
|
||||||
require.NoError(t, graphiteOnce(t.Context(), testGraphiteConfig(h.addr(t), r), time.Minute))
|
|
||||||
b := readExport(t, h.next(t, 5*time.Second))
|
|
||||||
assert.Contains(t, string(b), "nebula.g.value 7 ")
|
|
||||||
assert.Contains(t, string(b), "nebula.c.count 3 ")
|
|
||||||
assert.Contains(t, string(b), "nebula.c.count_ps 3.00 ")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A host that accepts and never reads is given up on, and the failed write is reported
|
|
||||||
func TestGraphiteOnce_stalledHostTimesOut(t *testing.T) {
|
|
||||||
r := metrics.NewRegistry()
|
|
||||||
bigGraphiteRegistry(r, t)
|
|
||||||
h := newGraphiteHost(t, 4096)
|
|
||||||
done := make(chan error, 1)
|
|
||||||
cfg := testGraphiteConfig(h.addr(t), r)
|
|
||||||
go func() { done <- graphiteOnce(t.Context(), cfg, 300*time.Millisecond) }()
|
|
||||||
h.next(t, 5*time.Second) // accepted, never read
|
|
||||||
|
|
||||||
select {
|
|
||||||
case err := <-done:
|
|
||||||
require.Error(t, err)
|
|
||||||
case <-time.After(10 * time.Second):
|
|
||||||
t.Fatal("the send did not give up on a host that stopped reading")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The timeout covers the whole send, a host that keeps reading but too slowly is still given up on
|
|
||||||
func TestGraphiteOnce_timeoutCoversTheWholeSend(t *testing.T) {
|
|
||||||
r := metrics.NewRegistry()
|
|
||||||
bigGraphiteRegistry(r, t)
|
|
||||||
h := newGraphiteHost(t, 0)
|
|
||||||
done := make(chan error, 1)
|
|
||||||
start := time.Now()
|
|
||||||
cfg := testGraphiteConfig(h.addr(t), r)
|
|
||||||
go func() { done <- graphiteOnce(t.Context(), cfg, 500*time.Millisecond) }()
|
|
||||||
c := h.next(t, 5*time.Second)
|
|
||||||
stopReading := make(chan struct{})
|
|
||||||
defer close(stopReading)
|
|
||||||
// 32KB every 10ms keeps every write well inside the timeout, the whole export takes seconds
|
|
||||||
go func() {
|
|
||||||
buf := make([]byte, 32<<10)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-stopReading:
|
|
||||||
return
|
|
||||||
case <-time.After(10 * time.Millisecond):
|
|
||||||
}
|
|
||||||
if _, err := c.Read(buf); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case err := <-done:
|
|
||||||
require.Error(t, err)
|
|
||||||
assert.Less(t, time.Since(start), 5*time.Second)
|
|
||||||
case <-time.After(10 * time.Second):
|
|
||||||
t.Fatal("a host that kept reading slowly held the send past its timeout")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGraphiteOnce_cancelledCtxDoesNotConnect(t *testing.T) {
|
|
||||||
h := newGraphiteHost(t, 0)
|
|
||||||
ctx, cancel := context.WithCancel(t.Context())
|
|
||||||
cancel()
|
|
||||||
require.Error(t, graphiteOnce(ctx, testGraphiteConfig(h.addr(t), metrics.NewRegistry()), time.Minute))
|
|
||||||
select {
|
|
||||||
case <-h.conns:
|
|
||||||
t.Fatal("connected on a cancelled ctx")
|
|
||||||
case <-time.After(200 * time.Millisecond):
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A stop or reload abandons a stuck send rather than waiting out its timeout
|
|
||||||
func TestGraphiteOnce_cancelAbandonsSend(t *testing.T) {
|
|
||||||
r := metrics.NewRegistry()
|
|
||||||
bigGraphiteRegistry(r, t)
|
|
||||||
h := newGraphiteHost(t, 4096)
|
|
||||||
ctx, cancel := context.WithCancel(t.Context())
|
|
||||||
done := make(chan error, 1)
|
|
||||||
cfg := testGraphiteConfig(h.addr(t), r)
|
|
||||||
go func() { done <- graphiteOnce(ctx, cfg, time.Minute) }()
|
|
||||||
h.next(t, 5*time.Second)
|
|
||||||
select {
|
|
||||||
case err := <-done:
|
|
||||||
t.Fatalf("the send should be stuck on a host that is not reading, it ended with %v", err)
|
|
||||||
case <-time.After(200 * time.Millisecond):
|
|
||||||
}
|
|
||||||
|
|
||||||
cancel()
|
|
||||||
select {
|
|
||||||
case err := <-done:
|
|
||||||
require.Error(t, err)
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("the send is still stuck after its ctx was cancelled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// buildRuntime hands graphite the configured prefix and interval
|
|
||||||
func TestStatsServer_graphiteExportUsesConfig(t *testing.T) {
|
|
||||||
const name = "graphite.wiring.test"
|
|
||||||
metrics.GetOrRegisterCounter(name, nil).Inc(8)
|
|
||||||
t.Cleanup(func() { metrics.DefaultRegistry.Unregister(name) })
|
|
||||||
h := newGraphiteHost(t, 0)
|
|
||||||
s, c := newTestStatsServer(t)
|
|
||||||
setStatsConfig(c, map[string]any{"type": "graphite", "interval": "4s", "prefix": "pfx", "host": h.ln.Addr().String()})
|
|
||||||
cfg, err := loadStatsConfig(c)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
s.runMu.Lock()
|
|
||||||
fns, _ := s.buildRuntime(t.Context(), cfg)
|
|
||||||
s.runMu.Unlock()
|
|
||||||
for _, fn := range fns {
|
|
||||||
fn()
|
|
||||||
}
|
|
||||||
b := readExport(t, h.next(t, 5*time.Second))
|
|
||||||
assert.Contains(t, string(b), "pfx."+name+".count 8 ")
|
|
||||||
assert.Contains(t, string(b), "pfx."+name+".count_ps 2.00 ")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStatsServer_graphiteFailureIsLogged(t *testing.T) {
|
|
||||||
logs := &lockedBuffer{}
|
|
||||||
s, c := newTestStatsServer(t)
|
|
||||||
s.l = test.NewLoggerWithOutput(logs)
|
|
||||||
setStatsConfig(c, map[string]any{"type": "graphite", "interval": "1h", "host": "127.0.0.1:" + freeTCPPort(t)})
|
|
||||||
cfg, err := loadStatsConfig(c)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
s.runMu.Lock()
|
|
||||||
fns, _ := s.buildRuntime(t.Context(), cfg)
|
|
||||||
s.runMu.Unlock()
|
|
||||||
for _, fn := range fns {
|
|
||||||
fn()
|
|
||||||
}
|
|
||||||
assert.Contains(t, logs.String(), "Graphite export failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop abandons the running export, so it goes through Start rather than handing buildRuntime a ctx, and a stop is
|
|
||||||
// not logged as a failure
|
|
||||||
func TestStatsServer_stopAbandonsGraphiteSend(t *testing.T) {
|
|
||||||
bigGraphiteRegistry(metrics.DefaultRegistry, t)
|
|
||||||
h := newGraphiteHost(t, 4096)
|
|
||||||
logs := &lockedBuffer{}
|
|
||||||
s, c := newTestStatsServer(t)
|
|
||||||
s.l = test.NewLoggerWithOutput(logs)
|
|
||||||
setStatsConfig(c, map[string]any{"type": "graphite", "interval": "50ms", "host": h.ln.Addr().String()})
|
|
||||||
require.NoError(t, s.reload(c, true))
|
|
||||||
|
|
||||||
started := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
s.Start()
|
|
||||||
close(started)
|
|
||||||
}()
|
|
||||||
stuck := h.next(t, 30*time.Second)
|
|
||||||
s.Stop()
|
|
||||||
select {
|
|
||||||
case <-started:
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("Start did not return after Stop")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A closed sender resets the connection once it sees this, one still sending just buffers it. Either way the
|
|
||||||
// read below doesn't have to drain the export through the small window to find out
|
|
||||||
_, err := stuck.Write([]byte("x"))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, stuck.SetReadDeadline(time.Now().Add(10*time.Second)))
|
|
||||||
n, err := io.Copy(io.Discard, stuck)
|
|
||||||
var ne net.Error
|
|
||||||
if errors.As(err, &ne) && ne.Timeout() {
|
|
||||||
t.Fatalf("the send kept the connection after Stop, read %d bytes", n)
|
|
||||||
}
|
|
||||||
assert.Less(t, n, int64(1<<20), "the send kept going after Stop")
|
|
||||||
// The capture loop logs on its own goroutine after Start has returned, give it the chance
|
|
||||||
assert.Never(t, func() bool { return strings.Contains(logs.String(), "Graphite export failed") }, 500*time.Millisecond, 10*time.Millisecond, "a stop is not a failure")
|
|
||||||
}
|
|
||||||
+38
-60
@@ -54,24 +54,22 @@ type HandshakeConfig struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type HandshakeManager struct {
|
type HandshakeManager struct {
|
||||||
// Mutex for interacting with the vpnIps and indexes maps.
|
// Mutex for interacting with the vpnIps and indexes maps
|
||||||
// Lock order is hostmap, then this lock, then the lighthouse, then a RemoteList.
|
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
|
|
||||||
vpnIps map[netip.Addr]*HandshakeHostInfo
|
vpnIps map[netip.Addr]*HandshakeHostInfo
|
||||||
indexes map[uint32]*HandshakeHostInfo
|
indexes map[uint32]*HandshakeHostInfo
|
||||||
|
|
||||||
mainHostMap *HostMap
|
mainHostMap *HostMap
|
||||||
lightHouse *LightHouse
|
lightHouse *LightHouse
|
||||||
outside udp.Conn
|
outside udp.Conn
|
||||||
config HandshakeConfig
|
config HandshakeConfig
|
||||||
OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
|
OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
|
||||||
messageMetrics *MessageMetrics
|
messageMetrics *MessageMetrics
|
||||||
metricInitiated metrics.Counter
|
metricInitiated metrics.Counter
|
||||||
metricTimedOut metrics.Counter
|
metricTimedOut metrics.Counter
|
||||||
metricRejectedBlocklisted metrics.Counter
|
f *Interface
|
||||||
f *Interface
|
l *slog.Logger
|
||||||
l *slog.Logger
|
|
||||||
|
|
||||||
// can be used to trigger outbound handshake for the given vpnIp
|
// can be used to trigger outbound handshake for the given vpnIp
|
||||||
trigger chan netip.Addr
|
trigger chan netip.Addr
|
||||||
@@ -119,19 +117,18 @@ func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, s
|
|||||||
|
|
||||||
func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
|
func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
|
||||||
return &HandshakeManager{
|
return &HandshakeManager{
|
||||||
vpnIps: map[netip.Addr]*HandshakeHostInfo{},
|
vpnIps: map[netip.Addr]*HandshakeHostInfo{},
|
||||||
indexes: map[uint32]*HandshakeHostInfo{},
|
indexes: map[uint32]*HandshakeHostInfo{},
|
||||||
mainHostMap: mainHostMap,
|
mainHostMap: mainHostMap,
|
||||||
lightHouse: lightHouse,
|
lightHouse: lightHouse,
|
||||||
outside: outside,
|
outside: outside,
|
||||||
config: config,
|
config: config,
|
||||||
trigger: make(chan netip.Addr, config.triggerBuffer),
|
trigger: make(chan netip.Addr, config.triggerBuffer),
|
||||||
OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
|
OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
|
||||||
messageMetrics: config.messageMetrics,
|
messageMetrics: config.messageMetrics,
|
||||||
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
||||||
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
||||||
metricRejectedBlocklisted: metrics.GetOrRegisterCounter("handshake_manager.rejected.blocklisted", nil),
|
l: l,
|
||||||
l: l,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,6 +259,14 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
|||||||
"style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
|
"style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get a remotes object if we don't already have one.
|
||||||
|
// This is mainly to protect us as this should never be the case
|
||||||
|
// NB ^ This comment doesn't jive. It's how the thing gets initialized.
|
||||||
|
// It's the common path. Should it update every time, in case a future LH query/queries give us more info?
|
||||||
|
if hostinfo.remotes == nil {
|
||||||
|
hostinfo.remotes = hm.lightHouse.QueryCache([]netip.Addr{vpnIp})
|
||||||
|
}
|
||||||
|
|
||||||
remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
|
remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
|
||||||
remotesHaveChanged := !slices.Equal(remotes, hh.lastRemotes)
|
remotesHaveChanged := !slices.Equal(remotes, hh.lastRemotes)
|
||||||
|
|
||||||
@@ -366,9 +371,6 @@ func (hm *HandshakeManager) StartHandshake(vpnAddr netip.Addr, cacheCb func(*Han
|
|||||||
hostinfo := &HostInfo{
|
hostinfo := &HostInfo{
|
||||||
vpnAddrs: []netip.Addr{vpnAddr},
|
vpnAddrs: []netip.Addr{vpnAddr},
|
||||||
HandshakePacket: make(map[uint8][]byte, 0),
|
HandshakePacket: make(map[uint8][]byte, 0),
|
||||||
// Attached here so a pending hostinfo never exists without one: SetRemote dereferences
|
|
||||||
// it, and create-tunnel -address can reach SetRemote before the handshake loop runs.
|
|
||||||
remotes: hm.lightHouse.QueryCache([]netip.Addr{vpnAddr}),
|
|
||||||
relayState: RelayState{
|
relayState: RelayState{
|
||||||
relays: nil,
|
relays: nil,
|
||||||
relayForByAddr: map[netip.Addr]*Relay{},
|
relayForByAddr: map[netip.Addr]*Relay{},
|
||||||
@@ -719,12 +721,7 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
|||||||
|
|
||||||
response, result, err := machine.ProcessPacket(nil, packet)
|
response, result, err := machine.ProcessPacket(nil, packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
level := slog.LevelError
|
f.l.Error("Failed to process handshake packet", "from", via, "error", err)
|
||||||
if errors.Is(err, cert.ErrBlockListed) {
|
|
||||||
level = slog.LevelDebug
|
|
||||||
hm.metricRejectedBlocklisted.Inc(1)
|
|
||||||
}
|
|
||||||
f.l.Log(context.Background(), level, "Failed to process handshake packet", "from", via, "error", err)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -752,14 +749,8 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
connState, err := newConnectionStateFromResult(result)
|
|
||||||
if err != nil {
|
|
||||||
f.l.Error("Discarding handshake with an invalid message index", "error", err, "vpnAddrs", vpnAddrs)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
hostinfo := &HostInfo{
|
hostinfo := &HostInfo{
|
||||||
ConnectionState: connState,
|
ConnectionState: newConnectionStateFromResult(result),
|
||||||
localIndexId: result.LocalIndex,
|
localIndexId: result.LocalIndex,
|
||||||
remoteIndexId: result.RemoteIndex,
|
remoteIndexId: result.RemoteIndex,
|
||||||
vpnAddrs: vpnAddrs,
|
vpnAddrs: vpnAddrs,
|
||||||
@@ -856,9 +847,6 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
|||||||
|
|
||||||
response, result, err := machine.ProcessPacket(nil, packet)
|
response, result, err := machine.ProcessPacket(nil, packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, cert.ErrBlockListed) {
|
|
||||||
hm.metricRejectedBlocklisted.Inc(1)
|
|
||||||
}
|
|
||||||
// Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
|
// Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
|
||||||
if machine.Failed() {
|
if machine.Failed() {
|
||||||
f.l.Warn("Failed to process handshake packet, abandoning",
|
f.l.Warn("Failed to process handshake packet, abandoning",
|
||||||
@@ -880,13 +868,7 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
|
// Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
|
||||||
cs, err := newConnectionStateFromResult(result)
|
hostinfo.ConnectionState = newConnectionStateFromResult(result)
|
||||||
if err != nil {
|
|
||||||
f.l.Error("Discarding handshake with an invalid message index", "error", err, "vpnAddrs", hostinfo.vpnAddrs)
|
|
||||||
hm.DeleteHostInfo(hostinfo)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
hostinfo.ConnectionState = cs
|
|
||||||
|
|
||||||
remoteCert := result.RemoteCert
|
remoteCert := result.RemoteCert
|
||||||
if remoteCert == nil {
|
if remoteCert == nil {
|
||||||
@@ -952,14 +934,13 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
|||||||
|
|
||||||
hm.DeleteHostInfo(hostinfo)
|
hm.DeleteHostInfo(hostinfo)
|
||||||
hm.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
|
hm.StartHandshake(hostinfo.vpnAddrs[0], func(newHH *HandshakeHostInfo) {
|
||||||
|
newHH.hostinfo.remotes = hostinfo.remotes
|
||||||
newHH.hostinfo.remotes.BlockRemote(via)
|
newHH.hostinfo.remotes.BlockRemote(via)
|
||||||
newHH.packetStore = hh.packetStore
|
newHH.packetStore = hh.packetStore
|
||||||
hh.packetStore = []*cachedPacket{}
|
hh.packetStore = []*cachedPacket{}
|
||||||
|
hostinfo.vpnAddrs = vpnAddrs
|
||||||
|
f.sendCloseTunnel(hostinfo)
|
||||||
})
|
})
|
||||||
// sendCloseTunnel may take the hostmap lock, so it must not run under the handshake
|
|
||||||
// manager lock that StartHandshake holds around the callback.
|
|
||||||
hostinfo.vpnAddrs = vpnAddrs
|
|
||||||
f.sendCloseTunnel(hostinfo)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -994,9 +975,6 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
|||||||
nb := make([]byte, 12, 12)
|
nb := make([]byte, 12, 12)
|
||||||
out := make([]byte, mtu)
|
out := make([]byte, mtu)
|
||||||
for _, cp := range hh.packetStore {
|
for _, cp := range hh.packetStore {
|
||||||
// TODO: use a SendBatch here. Each callback lands in
|
|
||||||
// sendNoMetrics -> WriteTo: one syscall per cached packet,
|
|
||||||
// where one sendmmsg could flush the whole store.
|
|
||||||
cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
|
cp.callback(cp.messageType, cp.messageSubType, hostinfo, cp.packet, nb, out)
|
||||||
}
|
}
|
||||||
f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
|
f.cachedPacketMetrics.sent.Inc(int64(len(hh.packetStore)))
|
||||||
@@ -1108,7 +1086,7 @@ func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hos
|
|||||||
// We received a valid handshake on this relay, so make sure the relay
|
// We received a valid handshake on this relay, so make sure the relay
|
||||||
// state reflects that, in case it had been marked Disestablished.
|
// state reflects that, in case it had been marked Disestablished.
|
||||||
via.relayHI.relayState.UpdateRelayForByIdxState(via.relay.LocalIndex, Established)
|
via.relayHI.relayState.UpdateRelayForByIdxState(via.relay.LocalIndex, Established)
|
||||||
f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false, 0)
|
f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
|
||||||
f.l.Info("Handshake message sent", append(logFields, "relay", via.relayHI.vpnAddrs[0])...)
|
f.l.Info("Handshake message sent", append(logFields, "relay", via.relayHI.vpnAddrs[0])...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-157
@@ -1,22 +1,16 @@
|
|||||||
package nebula
|
package nebula
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log/slog"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/flynn/noise"
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
ct "github.com/slackhq/nebula/cert_test"
|
|
||||||
"github.com/slackhq/nebula/handshake"
|
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func Test_NewHandshakeManagerVpnIp(t *testing.T) {
|
func Test_NewHandshakeManagerVpnIp(t *testing.T) {
|
||||||
@@ -48,6 +42,8 @@ func Test_NewHandshakeManagerVpnIp(t *testing.T) {
|
|||||||
i2 := blah.StartHandshake(ip, nil)
|
i2 := blah.StartHandshake(ip, nil)
|
||||||
assert.Same(t, i, i2)
|
assert.Same(t, i, i2)
|
||||||
|
|
||||||
|
i.remotes = NewRemoteList([]netip.Addr{}, nil)
|
||||||
|
|
||||||
// Adding something to pending should not affect the main hostmap
|
// Adding something to pending should not affect the main hostmap
|
||||||
assert.Empty(t, mainHM.Hosts)
|
assert.Empty(t, mainHM.Hosts)
|
||||||
|
|
||||||
@@ -88,7 +84,7 @@ func (mw *mockEncWriter) SendMessageToVpnAddr(_ header.MessageType, _ header.Mes
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mw *mockEncWriter) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
|
func (mw *mockEncWriter) SendVia(_ *HostInfo, _ *Relay, _, _, _ []byte, _ bool) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,153 +235,3 @@ func TestHandleIncomingDispatch(t *testing.T) {
|
|||||||
assert.Empty(t, hm.indexes, "orphan stage-2 must not create state")
|
assert.Empty(t, hm.indexes, "orphan stage-2 must not create state")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBlocklistedHandshakeLogLevelAndCounter(t *testing.T) {
|
|
||||||
ca, _, caKey, _ := ct.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
pool := ct.NewTestCAPool(ca)
|
|
||||||
|
|
||||||
newCredential := func(name, network string) (cert.Certificate, *handshake.Credential) {
|
|
||||||
c, _, rawKey, _ := ct.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey,
|
|
||||||
name, ca.NotBefore(), ca.NotAfter(), []netip.Prefix{netip.MustParsePrefix(network)}, nil, nil)
|
|
||||||
privateKey, _, _, err := cert.UnmarshalPrivateKeyFromPEM(rawKey)
|
|
||||||
require.NoError(t, err)
|
|
||||||
certBytes, err := c.MarshalForHandshakes()
|
|
||||||
require.NoError(t, err)
|
|
||||||
cipherSuite := noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashSHA256)
|
|
||||||
return c, handshake.NewCredential(c, certBytes, privateKey, cipherSuite)
|
|
||||||
}
|
|
||||||
|
|
||||||
initiatorCert, initiatorCredential := newCredential("initiator", "10.0.0.1/24")
|
|
||||||
responderCert, responderCredential := newCredential("responder", "10.0.0.2/24")
|
|
||||||
fingerprint, err := initiatorCert.Fingerprint()
|
|
||||||
require.NoError(t, err)
|
|
||||||
pool.BlocklistFingerprint(fingerprint)
|
|
||||||
|
|
||||||
initiator, err := handshake.NewMachine(cert.Version2,
|
|
||||||
func(cert.Version) *handshake.Credential { return initiatorCredential },
|
|
||||||
func(c cert.Certificate) (*cert.CachedCertificate, error) {
|
|
||||||
return pool.VerifyCertificate(time.Now(), c)
|
|
||||||
},
|
|
||||||
func() (uint32, error) { return 1, nil }, true, header.HandshakeIXPSK0)
|
|
||||||
require.NoError(t, err)
|
|
||||||
packet, err := initiator.Initiate(nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
handler := &capturingHandler{}
|
|
||||||
logger := slog.New(handler)
|
|
||||||
pki := &PKI{}
|
|
||||||
pki.cs.Store(&CertState{initiatingVersion: cert.Version2, v2Credential: responderCredential})
|
|
||||||
pki.caPool.Store(pool)
|
|
||||||
hm := NewHandshakeManager(logger, nil, nil, nil, defaultHandshakeConfig)
|
|
||||||
hm.metricRejectedBlocklisted = metrics.NewCounter()
|
|
||||||
hm.f = &Interface{pki: pki, l: logger}
|
|
||||||
via := ViaSender{UdpAddr: netip.MustParseAddrPort("198.51.100.7:4242")}
|
|
||||||
|
|
||||||
hm.beginHandshake(via, packet, nil)
|
|
||||||
entry := findEntry(t, handler.entries, "Failed to process handshake packet")
|
|
||||||
assert.Equal(t, slog.LevelDebug, entry.Level)
|
|
||||||
require.ErrorIs(t, entry.Attrs["error"].(error), cert.ErrBlockListed)
|
|
||||||
assert.Equal(t, int64(1), hm.metricRejectedBlocklisted.Count())
|
|
||||||
|
|
||||||
handler.entries = nil
|
|
||||||
hm.beginHandshake(via, nil, nil)
|
|
||||||
entry = findEntry(t, handler.entries, "Failed to process handshake packet")
|
|
||||||
assert.Equal(t, slog.LevelError, entry.Level)
|
|
||||||
assert.Equal(t, int64(1), hm.metricRejectedBlocklisted.Count())
|
|
||||||
|
|
||||||
// The initiator sees the same rejection in continueHandshake, after a
|
|
||||||
// responder has accepted its first packet and sent a valid reply.
|
|
||||||
cleanPool := ct.NewTestCAPool(ca)
|
|
||||||
responder, err := handshake.NewMachine(cert.Version2,
|
|
||||||
func(cert.Version) *handshake.Credential { return responderCredential },
|
|
||||||
func(c cert.Certificate) (*cert.CachedCertificate, error) {
|
|
||||||
return cleanPool.VerifyCertificate(time.Now(), c)
|
|
||||||
},
|
|
||||||
func() (uint32, error) { return 2, nil }, false, header.HandshakeIXPSK0)
|
|
||||||
require.NoError(t, err)
|
|
||||||
response, _, err := responder.ProcessPacket(nil, packet)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
responderFingerprint, err := responderCert.Fingerprint()
|
|
||||||
require.NoError(t, err)
|
|
||||||
pool.BlocklistFingerprint(responderFingerprint)
|
|
||||||
|
|
||||||
initiatingHM := NewHandshakeManager(logger, nil, nil, nil, defaultHandshakeConfig)
|
|
||||||
initiatingHM.metricRejectedBlocklisted = metrics.NewCounter()
|
|
||||||
initiatingHM.f = &Interface{l: logger}
|
|
||||||
hh := &HandshakeHostInfo{
|
|
||||||
machine: initiator,
|
|
||||||
hostinfo: &HostInfo{localIndexId: 1, vpnAddrs: []netip.Addr{netip.MustParseAddr("10.0.0.2")}},
|
|
||||||
}
|
|
||||||
initiatingHM.indexes[1] = hh
|
|
||||||
via.IsRelayed = true // skip the remote allow list before certificate validation
|
|
||||||
initiatingHM.continueHandshake(via, hh, response)
|
|
||||||
assert.Equal(t, int64(1), initiatingHM.metricRejectedBlocklisted.Count())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test_PendingHandshakeHasRemotes covers create-tunnel -address: a pending hostinfo must already
|
|
||||||
// carry its RemoteList when StartHandshake runs its callback, so SetRemote there, before the
|
|
||||||
// handshake loop has run, is safe and the address becomes one the handshake is sent to.
|
|
||||||
func Test_PendingHandshakeHasRemotes(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
mainHM := newHostMap(l)
|
|
||||||
preferredRanges := []netip.Prefix{}
|
|
||||||
mainHM.preferredRanges.Store(&preferredRanges)
|
|
||||||
|
|
||||||
hm := NewHandshakeManager(l, mainHM, newTestLighthouse(), &udp.NoopConn{}, defaultHandshakeConfig)
|
|
||||||
|
|
||||||
vpnIp := netip.MustParseAddr("172.1.1.2")
|
|
||||||
remote := netip.MustParseAddrPort("192.168.1.9:4242")
|
|
||||||
|
|
||||||
hi := hm.StartHandshake(vpnIp, func(hh *HandshakeHostInfo) {
|
|
||||||
require.NotNil(t, hh.hostinfo.remotes, "a pending handshake must never be without its RemoteList")
|
|
||||||
hh.hostinfo.SetRemote(remote)
|
|
||||||
})
|
|
||||||
assert.Contains(t, hi.remotes.CopyAddrs(preferredRanges), remote, "the handshake must be sent to the supplied remote")
|
|
||||||
assert.Equal(t, remote, hi.GetRemote())
|
|
||||||
|
|
||||||
// A RemoteList keeps one learned address per host, so a second remote replaces the
|
|
||||||
// first — the same behaviour change-remote has on an established tunnel.
|
|
||||||
other := netip.MustParseAddrPort("192.168.1.10:4242")
|
|
||||||
hi.SetRemote(other)
|
|
||||||
assert.Equal(t, []netip.AddrPort{other}, hi.remotes.CopyAddrs(preferredRanges))
|
|
||||||
assert.Equal(t, other, hi.GetRemote())
|
|
||||||
}
|
|
||||||
|
|
||||||
// newRemotesRaceFixture builds a handshake manager with an established tunnel to vpnAddr whose
|
|
||||||
// RemoteList is the lighthouse's cached list, the state every teardown-during-handshake race starts from.
|
|
||||||
func newRemotesRaceFixture(t *testing.T, vpnAddr netip.Addr) (*HandshakeManager, *Interface, *HostInfo) {
|
|
||||||
t.Helper()
|
|
||||||
l := test.NewLogger()
|
|
||||||
mainHM := newHostMap(l)
|
|
||||||
preferredRanges := []netip.Prefix{}
|
|
||||||
mainHM.preferredRanges.Store(&preferredRanges)
|
|
||||||
|
|
||||||
lh := newTestLighthouse()
|
|
||||||
hm := NewHandshakeManager(l, mainHM, lh, &udp.NoopConn{}, defaultHandshakeConfig)
|
|
||||||
f := &Interface{hostMap: mainHM, lightHouse: lh, handshakeManager: hm, l: l}
|
|
||||||
hm.f = f
|
|
||||||
|
|
||||||
established := &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{vpnAddr},
|
|
||||||
localIndexId: 1,
|
|
||||||
remoteIndexId: 101,
|
|
||||||
remotes: lh.QueryCache([]netip.Addr{vpnAddr}),
|
|
||||||
HandshakePacket: map[uint8][]byte{},
|
|
||||||
}
|
|
||||||
mainHM.Lock()
|
|
||||||
mainHM.unlockedAddHostInfo(established, f)
|
|
||||||
mainHM.Unlock()
|
|
||||||
|
|
||||||
return hm, f, established
|
|
||||||
}
|
|
||||||
|
|
||||||
// With no handshake pending, tearing down the last tunnel still evicts the list.
|
|
||||||
func Test_CloseTunnelEvictsWithoutPendingHandshake(t *testing.T) {
|
|
||||||
vpnAddr := netip.MustParseAddr("172.1.1.2")
|
|
||||||
_, f, established := newRemotesRaceFixture(t, vpnAddr)
|
|
||||||
|
|
||||||
f.closeTunnel(established)
|
|
||||||
assert.NotContains(t, f.hostMap.Hosts, vpnAddr)
|
|
||||||
assert.NotContains(t, f.lightHouse.addrMap, vpnAddr)
|
|
||||||
}
|
|
||||||
+6
-16
@@ -24,11 +24,6 @@ type m = map[string]any
|
|||||||
const (
|
const (
|
||||||
Version uint8 = 1
|
Version uint8 = 1
|
||||||
Len = 16
|
Len = 16
|
||||||
|
|
||||||
// MaxOverhead is the most a payload grows on its way to the underlay.
|
|
||||||
// A relayed packet has two headers and two AEAD tags, one for the inner tunnel and another for the relay tunnel.
|
|
||||||
// Every supported cipher (today) has a 16 byte tag.
|
|
||||||
MaxOverhead = 2 * (Len + 16)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type MessageType uint8
|
type MessageType uint8
|
||||||
@@ -195,18 +190,13 @@ func SubTypeName(t MessageType, s MessageSubType) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func IsValidSubType(t MessageType, s MessageSubType) bool {
|
func IsValidSubType(t MessageType, s MessageSubType) bool {
|
||||||
switch t {
|
if n, ok := subTypeMap[t]; ok {
|
||||||
case Message:
|
if _, ok := (*n)[s]; ok {
|
||||||
return s == MessageNone || s == MessageRelay
|
return true
|
||||||
case Handshake:
|
}
|
||||||
return s == HandshakeIXPSK0
|
|
||||||
case Test:
|
|
||||||
return s == TestReply || s == TestRequest
|
|
||||||
case Control, CloseTunnel, RecvError, LightHouse:
|
|
||||||
return s == 0
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHeader turns bytes into a header
|
// NewHeader turns bytes into a header
|
||||||
|
|||||||
@@ -102,57 +102,6 @@ func TestTypeMap(t *testing.T) {
|
|||||||
}, subTypeMap)
|
}, subTypeMap)
|
||||||
}
|
}
|
||||||
|
|
||||||
// mapIsValidSubType is the pre-refactor, map-driven definition of a valid
|
|
||||||
// subtype. IsValidSubType was reimplemented as an explicit switch; this keeps
|
|
||||||
// the original behavior around so we can prove the switch is equivalent to it.
|
|
||||||
func mapIsValidSubType(t MessageType, s MessageSubType) bool {
|
|
||||||
if n, ok := subTypeMap[t]; ok {
|
|
||||||
if _, ok := (*n)[s]; ok {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIsValidSubType(t *testing.T) {
|
|
||||||
// Explicit intent table: documents exactly which subtypes are valid so the
|
|
||||||
// test stays meaningful even if both the switch and subTypeMap change.
|
|
||||||
assert.True(t, IsValidSubType(Message, MessageNone))
|
|
||||||
assert.True(t, IsValidSubType(Message, MessageRelay))
|
|
||||||
assert.False(t, IsValidSubType(Message, 2))
|
|
||||||
|
|
||||||
assert.True(t, IsValidSubType(Handshake, HandshakeIXPSK0))
|
|
||||||
// HandshakeXXPSK0 is defined but not a wire-valid subtype.
|
|
||||||
assert.False(t, IsValidSubType(Handshake, HandshakeXXPSK0))
|
|
||||||
|
|
||||||
assert.True(t, IsValidSubType(Test, TestRequest))
|
|
||||||
assert.True(t, IsValidSubType(Test, TestReply))
|
|
||||||
assert.False(t, IsValidSubType(Test, 2))
|
|
||||||
|
|
||||||
// These types only ever carry subtype 0.
|
|
||||||
for _, mt := range []MessageType{Control, CloseTunnel, RecvError, LightHouse} {
|
|
||||||
assert.True(t, IsValidSubType(mt, 0), "type %d subtype 0 should be valid", mt)
|
|
||||||
assert.False(t, IsValidSubType(mt, 1), "type %d subtype 1 should be invalid", mt)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unknown/unassigned types are never valid.
|
|
||||||
assert.False(t, IsValidSubType(99, 0))
|
|
||||||
|
|
||||||
// Exhaustive proof of equivalence with the original map-driven logic across
|
|
||||||
// the entire (type, subtype) input space.
|
|
||||||
for ti := 0; ti <= 0xff; ti++ {
|
|
||||||
for si := 0; si <= 0xff; si++ {
|
|
||||||
mt, mst := MessageType(ti), MessageSubType(si)
|
|
||||||
assert.Equalf(t, mapIsValidSubType(mt, mst), IsValidSubType(mt, mst),
|
|
||||||
"IsValidSubType(%d, %d) diverged from map-driven definition", ti, si)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// H method must delegate to the package function.
|
|
||||||
assert.True(t, (&H{Type: Test, Subtype: TestReply}).IsValidSubType())
|
|
||||||
assert.False(t, (&H{Type: Handshake, Subtype: HandshakeXXPSK0}).IsValidSubType())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHeader_String(t *testing.T) {
|
func TestHeader_String(t *testing.T) {
|
||||||
assert.Equal(
|
assert.Equal(
|
||||||
t,
|
t,
|
||||||
|
|||||||
+83
-30
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"slices"
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -17,6 +18,7 @@ import (
|
|||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
|
"github.com/slackhq/nebula/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
|
const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
|
||||||
@@ -236,10 +238,16 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type HostInfo struct {
|
type HostInfo struct {
|
||||||
|
// The first cache line is everything the packet paths touch. Grouping them here means a send or receive
|
||||||
|
// pulls in one line instead of two, which is what the layout looked like when state lived at the end.
|
||||||
|
|
||||||
remote atomic.Pointer[netip.AddrPort]
|
remote atomic.Pointer[netip.AddrPort]
|
||||||
ConnectionState *ConnectionState
|
ConnectionState *ConnectionState
|
||||||
|
|
||||||
// Traffic bits, pendingDeletion, and the rebind epoch we last sent under
|
// state holds everything the hot paths need to touch per packet, in one word: whether we have seen traffic
|
||||||
|
// each way since the connection manager last looked, whether it has given up on us, and the
|
||||||
|
// Interface.rebindEpoch this tunnel last sent under. Keeping the epoch here means it survives the traffic
|
||||||
|
// bits being cleared, so a tunnel that has not sent since a rebind still notices when it does.
|
||||||
state atomic.Uint32
|
state atomic.Uint32
|
||||||
|
|
||||||
promoteCounter atomic.Uint32
|
promoteCounter atomic.Uint32
|
||||||
@@ -252,6 +260,8 @@ type HostInfo struct {
|
|||||||
// vpn networks but were removed because they are not usable
|
// vpn networks but were removed because they are not usable
|
||||||
vpnAddrs []netip.Addr
|
vpnAddrs []netip.Addr
|
||||||
|
|
||||||
|
// Everything below is off the packet path: handshakes, relays, roaming and the connection manager.
|
||||||
|
|
||||||
// networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
|
// networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
|
||||||
networks *bart.Table[NetworkType]
|
networks *bart.Table[NetworkType]
|
||||||
relayState RelayState
|
relayState RelayState
|
||||||
@@ -316,9 +326,9 @@ type cachedPacketMetrics struct {
|
|||||||
func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
|
func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
|
||||||
hm := newHostMap(l)
|
hm := newHostMap(l)
|
||||||
|
|
||||||
hm.reload(c, true, nil)
|
hm.reload(c, true)
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C) {
|
||||||
hm.reload(c, false, r)
|
hm.reload(c, false)
|
||||||
})
|
})
|
||||||
|
|
||||||
l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
|
l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
|
||||||
@@ -337,8 +347,7 @@ func newHostMap(l *slog.Logger) *HostMap {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// r is nil on the initial load
|
func (hm *HostMap) reload(c *config.C, initial bool) {
|
||||||
func (hm *HostMap) reload(c *config.C, initial bool, r *config.Reload) {
|
|
||||||
if initial || c.HasChanged("preferred_ranges") {
|
if initial || c.HasChanged("preferred_ranges") {
|
||||||
var preferredRanges []netip.Prefix
|
var preferredRanges []netip.Prefix
|
||||||
rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
|
rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
|
||||||
@@ -349,9 +358,8 @@ func (hm *HostMap) reload(c *config.C, initial bool, r *config.Reload) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
hm.l.Warn("Failed to parse preferred ranges, ignoring",
|
hm.l.Warn("Failed to parse preferred ranges, ignoring",
|
||||||
"error", err,
|
"error", err,
|
||||||
"range", rawPreferredRange,
|
"range", rawPreferredRanges,
|
||||||
)
|
)
|
||||||
r.Failed()
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -539,17 +547,6 @@ func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
|
|||||||
return final
|
return final
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hm *HostMap) QueryIndexCached(index uint32, cache map[uint32]*HostInfo) *HostInfo {
|
|
||||||
if out, ok := cache[index]; ok {
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
out := hm.QueryIndex(index)
|
|
||||||
if out != nil {
|
|
||||||
cache[index] = out
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
|
func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
|
||||||
hm.RLock()
|
hm.RLock()
|
||||||
if h, ok := hm.Indexes[index]; ok {
|
if h, ok := hm.Indexes[index]; ok {
|
||||||
@@ -766,25 +763,27 @@ func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interfac
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bits within HostInfo.state, everything above stateEpochShift is the epoch
|
// Bits within HostInfo.state. Everything above stateEpochShift is the rebind epoch.
|
||||||
const (
|
const (
|
||||||
stateIn uint32 = 1 << iota
|
stateIn uint32 = 1 << iota
|
||||||
stateOut
|
stateOut
|
||||||
statePendingDeletion
|
statePendingDeletion
|
||||||
|
|
||||||
stateFlags = stateIn | stateOut | statePendingDeletion
|
stateFlags = stateIn | stateOut | statePendingDeletion
|
||||||
// The epoch is the top 29 bits, it would take 2^29 rebinds to wrap and we will never get there
|
|
||||||
stateEpochShift = 3
|
stateEpochShift = 3
|
||||||
)
|
)
|
||||||
|
|
||||||
// markIn records inbound traffic
|
// markIn records inbound traffic. Reading first keeps the cache line shared on the common path, where the bit
|
||||||
|
// is already set.
|
||||||
func (i *HostInfo) markIn() {
|
func (i *HostInfo) markIn() {
|
||||||
if i.state.Load()&stateIn == 0 {
|
if i.state.Load()&stateIn == 0 {
|
||||||
i.state.Or(stateIn)
|
i.state.Or(stateIn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// markOut records a send and reports whether the epoch moved, meaning we want a punch from the far side
|
// markOut records that we sent on this tunnel under the given rebind epoch. It reports whether the epoch moved
|
||||||
|
// since our last send, which means the local network changed and we want the far side to punch at us again.
|
||||||
|
// The common path is a single load that matches and returns.
|
||||||
func (i *HostInfo) markOut(epoch uint32) bool {
|
func (i *HostInfo) markOut(epoch uint32) bool {
|
||||||
e := epoch << stateEpochShift
|
e := epoch << stateEpochShift
|
||||||
for {
|
for {
|
||||||
@@ -799,14 +798,12 @@ func (i *HostInfo) markOut(epoch uint32) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// markOutOnly records a send without consuming the rebind epoch, for paths that cannot act on a requery
|
// sentSinceCheck reports whether anything has been sent since the connection manager last looked.
|
||||||
func (i *HostInfo) markOutOnly() {
|
func (i *HostInfo) sentSinceCheck() bool {
|
||||||
if i.state.Load()&stateOut == 0 {
|
return i.state.Load()&stateOut != 0
|
||||||
i.state.Or(stateOut)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// takeTraffic clears both traffic bits, leaving the epoch alone, and reports what they were
|
// takeTraffic clears both traffic bits, leaving the epoch alone, and reports what they were.
|
||||||
func (i *HostInfo) takeTraffic() (in bool, out bool) {
|
func (i *HostInfo) takeTraffic() (in bool, out bool) {
|
||||||
old := i.state.And(^(stateIn | stateOut))
|
old := i.state.And(^(stateIn | stateOut))
|
||||||
return old&stateIn != 0, old&stateOut != 0
|
return old&stateIn != 0, old&stateOut != 0
|
||||||
@@ -930,3 +927,59 @@ func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
|
|||||||
|
|
||||||
return li
|
return li
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
|
||||||
|
func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
|
||||||
|
//FIXME: This function is pretty garbage
|
||||||
|
var finalAddrs []netip.Addr
|
||||||
|
ifaces, _ := net.Interfaces()
|
||||||
|
for _, i := range ifaces {
|
||||||
|
allow := allowList.AllowName(i.Name)
|
||||||
|
if l.Enabled(context.Background(), logging.LevelTrace) {
|
||||||
|
l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
|
||||||
|
"interfaceName", i.Name,
|
||||||
|
"allow", allow,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !allow {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addrs, _ := i.Addrs()
|
||||||
|
for _, rawAddr := range addrs {
|
||||||
|
var addr netip.Addr
|
||||||
|
switch v := rawAddr.(type) {
|
||||||
|
case *net.IPNet:
|
||||||
|
//continue
|
||||||
|
addr, _ = netip.AddrFromSlice(v.IP)
|
||||||
|
case *net.IPAddr:
|
||||||
|
addr, _ = netip.AddrFromSlice(v.IP)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !addr.IsValid() {
|
||||||
|
if l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
|
l.Debug("addr was invalid", "localAddr", rawAddr)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addr = addr.Unmap()
|
||||||
|
|
||||||
|
if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
|
||||||
|
isAllowed := allowList.Allow(addr)
|
||||||
|
if l.Enabled(context.Background(), logging.LevelTrace) {
|
||||||
|
l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
|
||||||
|
"localAddr", addr,
|
||||||
|
"allowed", isAllowed,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if !isAllowed {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
finalAddrs = append(finalAddrs, addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return finalAddrs
|
||||||
|
}
|
||||||
@@ -401,62 +401,3 @@ func TestHostMap_RelayState(t *testing.T) {
|
|||||||
assert.Equal(t, []netip.Addr{}, h1.relayState.relays)
|
assert.Equal(t, []netip.Addr{}, h1.relayState.relays)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// sentSinceCheck reports whether anything has been sent since the connection manager last looked. Test only:
|
|
||||||
// production reads the out bit through takeTraffic on the connection manager tick.
|
|
||||||
func (i *HostInfo) sentSinceCheck() bool {
|
|
||||||
return i.state.Load()&stateOut != 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHostInfo_markOut(t *testing.T) {
|
|
||||||
h := &HostInfo{}
|
|
||||||
h.markOut(5) // stamped when the tunnel was added
|
|
||||||
|
|
||||||
// A tunnel already on the current epoch has nothing to report, which is what keeps a fresh tunnel from
|
|
||||||
// requerying on its first packet
|
|
||||||
assert.False(t, h.markOut(5), "an unchanged epoch should not report a move")
|
|
||||||
assert.True(t, h.sentSinceCheck(), "the send is still recorded as traffic")
|
|
||||||
|
|
||||||
// A rebind is observed exactly once, so we requery once per rebind
|
|
||||||
assert.True(t, h.markOut(6), "a bumped epoch should report a move")
|
|
||||||
assert.False(t, h.markOut(6), "the epoch move should only be reported once")
|
|
||||||
|
|
||||||
// Traffic and pendingDeletion live in the same word and must survive an epoch change
|
|
||||||
h.setPendingDeletion(true)
|
|
||||||
h.markIn()
|
|
||||||
assert.True(t, h.markOut(7))
|
|
||||||
assert.True(t, h.isPendingDeletion(), "pendingDeletion must survive an epoch change")
|
|
||||||
in, out := h.takeTraffic()
|
|
||||||
assert.True(t, in, "inbound traffic must survive an epoch change")
|
|
||||||
assert.True(t, out)
|
|
||||||
|
|
||||||
// Clearing the traffic bits leaves the epoch alone, otherwise an idle tunnel would requery forever
|
|
||||||
assert.False(t, h.markOut(7), "takeTraffic must not disturb the epoch")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A relayed send records traffic but must leave the rebind epoch for the direct path to consume, otherwise
|
|
||||||
// relaying to a host swallows the requery that gets the far side punching at our new address.
|
|
||||||
func TestHostInfo_markOutOnly(t *testing.T) {
|
|
||||||
h := &HostInfo{}
|
|
||||||
h.markOut(5)
|
|
||||||
|
|
||||||
h.markOutOnly()
|
|
||||||
assert.True(t, h.sentSinceCheck(), "a relayed send is still outbound traffic")
|
|
||||||
assert.False(t, h.markOut(5), "a relayed send must not disturb the epoch")
|
|
||||||
|
|
||||||
assert.True(t, h.markOut(6), "a relayed send must not consume the epoch edge")
|
|
||||||
assert.False(t, h.markOut(6))
|
|
||||||
}
|
|
||||||
|
|
||||||
// A preferred range that doesn't parse is skipped and the rest are used, the reload says one was skipped
|
|
||||||
func TestHostMap_reloadBadPreferredRangeFails(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
c := config.NewC(l)
|
|
||||||
require.NoError(t, c.LoadString("preferred_ranges: [10.0.0.0/8]\n"))
|
|
||||||
hm := NewHostMapFromConfig(l, c)
|
|
||||||
|
|
||||||
res := c.ReloadConfigString("preferred_ranges: [10.0.0.0/8, nope]\n")
|
|
||||||
require.NoError(t, res.Err)
|
|
||||||
assert.True(t, res.Failed)
|
|
||||||
assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}, hm.GetPreferredRanges())
|
|
||||||
}
|
|
||||||
-235
@@ -1,235 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/netip"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
)
|
|
||||||
|
|
||||||
type identityFlags struct {
|
|
||||||
Address string
|
|
||||||
|
|
||||||
// addressSet records that -address was given at all, so a line that left it out is
|
|
||||||
// told to pass it and one that passed it empty is told the value did not parse. Neither
|
|
||||||
// is answered with this node's identity, which is whoami's to report: a program
|
|
||||||
// passing a connection's remote address through must get an error for a value it
|
|
||||||
// failed to fill in, not the daemon's own identity to authorize against.
|
|
||||||
addressSet bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// setAddress is -address's setter. flag.Func rather than StringVar so that presence is
|
|
||||||
// known; its String is empty, which is what a client building a line from the schema
|
|
||||||
// sees as the default.
|
|
||||||
func (f *identityFlags) setAddress(v string) error {
|
|
||||||
f.Address = v
|
|
||||||
f.addressSet = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// hostIdentity is what identity reports: the identity a certificate asserts for a host,
|
|
||||||
// and nothing else. Every field is read from a certificate nebula verified when the
|
|
||||||
// tunnel came up, or from our own, which is what lets a program on this host make an
|
|
||||||
// authorization decision from it, within one limit. Nebula drops an inbound packet
|
|
||||||
// whose source address is not in the sender's certificate, and one with an overlay
|
|
||||||
// source address that arrived through a peer's unsafe network rather than from the node
|
|
||||||
// holding it, so for a connection that arrived on the nebula interface the source
|
|
||||||
// address is the sender's and this is the sender's identity. A connection that arrived
|
|
||||||
// on any other interface with an overlay source address was never checked by nebula at
|
|
||||||
// all, so a program authorizing on this answer should confirm the connection came in
|
|
||||||
// on the nebula interface. The field names are an API: the info API serves this shape
|
|
||||||
// to programs that were not built against nebula.
|
|
||||||
type hostIdentity struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
VpnAddrs []netip.Addr `json:"vpnAddrs"`
|
|
||||||
Networks []netip.Prefix `json:"networks"`
|
|
||||||
UnsafeNetworks []netip.Prefix `json:"unsafeNetworks"`
|
|
||||||
Groups []string `json:"groups"`
|
|
||||||
Fingerprint string `json:"fingerprint"`
|
|
||||||
Issuer string `json:"issuer"`
|
|
||||||
NotBefore time.Time `json:"notBefore"`
|
|
||||||
NotAfter time.Time `json:"notAfter"`
|
|
||||||
CertVersion int `json:"certVersion"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// runIdentity answers for whoever owns the address: this node, when it is one of ours, or
|
|
||||||
// the peer behind an established tunnel. The address is required. This node's own
|
|
||||||
// identity is whoami's to report, so a caller that failed to pass an address is told so
|
|
||||||
// rather than handed an identity it could mistake for its peer's.
|
|
||||||
func runIdentity(ifce *Interface, args *identityFlags, a []string) (commands.Result, error) {
|
|
||||||
// print-cert takes its address as an operand; this takes a flag, because the query
|
|
||||||
// string of the info API names its parameters and an operand has no name there. One
|
|
||||||
// spelling on every surface, so the mistake is named rather than ignored.
|
|
||||||
if len(a) > 0 {
|
|
||||||
return commands.Failed("identity takes the vpn addr as -address, not as an operand: identity -address %s", a[0]), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !args.addressSet {
|
|
||||||
return commands.Failed("No vpn addr was provided, use -address <vpn addr>[:port]; whoami prints this node's own identity"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
vpnAddr, err := parseVpnAddrWithOptionalPort(args.Address)
|
|
||||||
if err != nil {
|
|
||||||
return commands.Failed("The provided vpn addr could not be parsed: %s", args.Address), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
crt, fingerprint := findCertificateForVpnAddr(ifce.pki.getCertState(), ifce.hostMap, vpnAddr)
|
|
||||||
if crt == nil {
|
|
||||||
return commands.NotFound("No active tunnel for vpn addr: %s", vpnAddr), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
id, err := newHostIdentity(crt, fingerprint)
|
|
||||||
if err != nil {
|
|
||||||
return commands.Result{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return commands.Value(id), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// runWhoami answers with this node's own identity, from its own certificate.
|
|
||||||
func runWhoami(ifce *Interface) (commands.Result, error) {
|
|
||||||
crt := ownCertificate(ifce.pki.getCertState())
|
|
||||||
if crt == nil {
|
|
||||||
return commands.Failed("No certificate is loaded"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
id, err := newHostIdentity(crt, "")
|
|
||||||
if err != nil {
|
|
||||||
return commands.Result{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return commands.Value(id), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// textIdentity is the human rendering, shared by every surface.
|
|
||||||
func textIdentity(id hostIdentity, w io.Writer) error {
|
|
||||||
_, err := fmt.Fprintf(w,
|
|
||||||
"name: %s\nvpn addrs: %s\nnetworks: %s\nunsafe networks: %s\ngroups: %s\nfingerprint: %s\nissuer: %s\nnot before: %s\nnot after: %s\ncert version: %d\n",
|
|
||||||
id.Name,
|
|
||||||
joinStringers(id.VpnAddrs),
|
|
||||||
joinStringers(id.Networks),
|
|
||||||
joinStringers(id.UnsafeNetworks),
|
|
||||||
strings.Join(id.Groups, ", "),
|
|
||||||
id.Fingerprint,
|
|
||||||
id.Issuer,
|
|
||||||
id.NotBefore.Format(time.RFC3339),
|
|
||||||
id.NotAfter.Format(time.RFC3339),
|
|
||||||
id.CertVersion,
|
|
||||||
)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func joinStringers[T fmt.Stringer](in []T) string {
|
|
||||||
parts := make([]string, 0, len(in))
|
|
||||||
for _, v := range in {
|
|
||||||
parts = append(parts, v.String())
|
|
||||||
}
|
|
||||||
return strings.Join(parts, ", ")
|
|
||||||
}
|
|
||||||
|
|
||||||
// newHostIdentity reads the identity out of a certificate. fingerprint is the
|
|
||||||
// certificate's when the caller already holds it, as a verified peer certificate does,
|
|
||||||
// and "" to have it hashed here. Slices are always allocated so a host with no groups
|
|
||||||
// reports [] rather than null.
|
|
||||||
func newHostIdentity(crt cert.Certificate, fingerprint string) (hostIdentity, error) {
|
|
||||||
if fingerprint == "" {
|
|
||||||
fp, err := crt.Fingerprint()
|
|
||||||
if err != nil {
|
|
||||||
return hostIdentity{}, err
|
|
||||||
}
|
|
||||||
fingerprint = fp
|
|
||||||
}
|
|
||||||
|
|
||||||
networks, unsafeNetworks, groups := crt.Networks(), crt.UnsafeNetworks(), crt.Groups()
|
|
||||||
id := hostIdentity{
|
|
||||||
Name: crt.Name(),
|
|
||||||
VpnAddrs: make([]netip.Addr, 0, len(networks)),
|
|
||||||
Networks: append(make([]netip.Prefix, 0, len(networks)), networks...),
|
|
||||||
UnsafeNetworks: append(make([]netip.Prefix, 0, len(unsafeNetworks)), unsafeNetworks...),
|
|
||||||
Groups: append(make([]string, 0, len(groups)), groups...),
|
|
||||||
Fingerprint: fingerprint,
|
|
||||||
Issuer: crt.Issuer(),
|
|
||||||
NotBefore: crt.NotBefore(),
|
|
||||||
NotAfter: crt.NotAfter(),
|
|
||||||
CertVersion: int(crt.Version()),
|
|
||||||
}
|
|
||||||
for _, n := range networks {
|
|
||||||
id.VpnAddrs = append(id.VpnAddrs, n.Addr())
|
|
||||||
}
|
|
||||||
|
|
||||||
return id, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ownCertificate is this node's certificate: the v2 one when it is loaded, else the v1.
|
|
||||||
// A v2 certificate is a superset of the v1 and may carry more networks, and it is the
|
|
||||||
// one newCertState builds myVpnAddrsTable from, so an address that matched that table is
|
|
||||||
// always listed in the certificate reported here. It is nil only when no certificate is
|
|
||||||
// loaded, which a running nebula never has.
|
|
||||||
func ownCertificate(cs *CertState) cert.Certificate {
|
|
||||||
if cs == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if crt := cs.getCertificate(cert.Version2); crt != nil {
|
|
||||||
return crt
|
|
||||||
}
|
|
||||||
return cs.getCertificate(cert.Version1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// findCertificateForVpnAddr answers who owns a vpn address: this node, from its own
|
|
||||||
// certificate state, since the hostmap never carries an entry for ourselves, or the peer
|
|
||||||
// behind an established tunnel. The certificate is nil when the address is unknown,
|
|
||||||
// when the tunnel is still pending and when it is mid teardown. A peer's comes with the
|
|
||||||
// fingerprint nebula computed when it verified the certificate; our own comes with "",
|
|
||||||
// since none is kept for it. identity and print-cert go through it, and the lighthouse's
|
|
||||||
// DNS TXT lookup through the two halves, so no surface disagrees about whose address it
|
|
||||||
// is; the TXT record alone keeps answering with the certificate handshakes start with.
|
|
||||||
func findCertificateForVpnAddr(cs *CertState, hostMap *HostMap, ip netip.Addr) (crt cert.Certificate, fingerprint string) {
|
|
||||||
if ownsVpnAddr(cs, ip) {
|
|
||||||
return ownCertificate(cs), ""
|
|
||||||
}
|
|
||||||
return peerCertificateForVpnAddr(hostMap, ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ownsVpnAddr reports whether ip is one of this node's own vpn addresses.
|
|
||||||
func ownsVpnAddr(cs *CertState, ip netip.Addr) bool {
|
|
||||||
return cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
// peerCertificateForVpnAddr is the certificate of the peer behind an established tunnel
|
|
||||||
// to ip, with the fingerprint nebula computed when it verified it, or nil when there is
|
|
||||||
// no such tunnel. See findCertificateForVpnAddr.
|
|
||||||
func peerCertificateForVpnAddr(hostMap *HostMap, ip netip.Addr) (crt cert.Certificate, fingerprint string) {
|
|
||||||
hostinfo := hostMap.QueryVpnAddr(ip)
|
|
||||||
if hostinfo == nil {
|
|
||||||
return nil, ""
|
|
||||||
}
|
|
||||||
|
|
||||||
cc := hostinfo.GetCert()
|
|
||||||
if cc == nil {
|
|
||||||
return nil, ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return cc.Certificate, cc.Fingerprint
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseVpnAddrWithOptionalPort reads a vpn address alone or with a port,
|
|
||||||
// 192.168.100.7:54321 or [fd00::1]:443, so a program can pass a connection's remote
|
|
||||||
// address through as its runtime reported it. A 4in6 address (::ffff:a.b.c.d) is
|
|
||||||
// unmapped, which is how an IPv4 peer arrives on a dual stack listener, and a zone is
|
|
||||||
// dropped, since no vpn address carries one.
|
|
||||||
func parseVpnAddrWithOptionalPort(s string) (netip.Addr, error) {
|
|
||||||
ip, err := netip.ParseAddr(s)
|
|
||||||
if err != nil {
|
|
||||||
ap, err := netip.ParseAddrPort(s)
|
|
||||||
if err != nil {
|
|
||||||
return netip.Addr{}, err
|
|
||||||
}
|
|
||||||
ip = ap.Addr()
|
|
||||||
}
|
|
||||||
|
|
||||||
return ip.Unmap().WithZone(""), nil
|
|
||||||
}
|
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"net/netip"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/cert_test"
|
|
||||||
"github.com/slackhq/nebula/commands"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// identityFixture is an Interface with our own certificate loaded and one peer behind an
|
|
||||||
// established tunnel, which is all identity reads.
|
|
||||||
func identityFixture(t *testing.T) (*Interface, cert.Certificate) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
l := test.NewLogger()
|
|
||||||
me := netip.MustParseAddr("10.0.0.1")
|
|
||||||
peer := netip.MustParsePrefix("10.0.0.2/24")
|
|
||||||
|
|
||||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
peerCert, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "peer", time.Time{}, time.Time{},
|
|
||||||
[]netip.Prefix{peer}, []netip.Prefix{netip.MustParsePrefix("192.168.1.0/24")}, []string{"web", "db"})
|
|
||||||
|
|
||||||
hm := newHostMap(l)
|
|
||||||
hm.Hosts[peer.Addr()] = &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{peer.Addr()},
|
|
||||||
ConnectionState: &ConnectionState{peerCert: &cert.CachedCertificate{Certificate: peerCert}},
|
|
||||||
}
|
|
||||||
// A tunnel still handshaking has no certificate yet, and must not be reported.
|
|
||||||
hm.Hosts[netip.MustParseAddr("10.0.0.3")] = &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{netip.MustParseAddr("10.0.0.3")},
|
|
||||||
ConnectionState: &ConnectionState{},
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Interface{pki: newTestPKI(t, "me", []netip.Addr{me}), hostMap: hm}, peerCert
|
|
||||||
}
|
|
||||||
|
|
||||||
// identity runs the command with -address given as address.
|
|
||||||
func identity(t *testing.T, f *Interface, address string, operands ...string) commands.Result {
|
|
||||||
t.Helper()
|
|
||||||
fs := &identityFlags{}
|
|
||||||
require.NoError(t, fs.setAddress(address))
|
|
||||||
r, err := runIdentity(f, fs, operands)
|
|
||||||
require.NoError(t, err)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// whoami runs the whoami command.
|
|
||||||
func whoami(t *testing.T, f *Interface) commands.Result {
|
|
||||||
t.Helper()
|
|
||||||
r, err := runWhoami(f)
|
|
||||||
require.NoError(t, err)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestWhoamiWithoutACertificateRefuses: no certificate is a refusal with the reason, as
|
|
||||||
// print-cert answers it, not an error a surface collapses to "command failed".
|
|
||||||
func TestWhoamiWithoutACertificateRefuses(t *testing.T) {
|
|
||||||
r := whoami(t, &Interface{pki: &PKI{}})
|
|
||||||
assert.False(t, r.OK)
|
|
||||||
assert.Equal(t, "No certificate is loaded", r.Reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWhoamiReportsThisNode(t *testing.T) {
|
|
||||||
f, _ := identityFixture(t)
|
|
||||||
|
|
||||||
r := whoami(t, f)
|
|
||||||
require.True(t, r.OK)
|
|
||||||
id, ok := r.Value.(hostIdentity)
|
|
||||||
require.True(t, ok, "got %T", r.Value)
|
|
||||||
assert.Equal(t, "me", id.Name)
|
|
||||||
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, id.VpnAddrs)
|
|
||||||
assert.Equal(t, 2, id.CertVersion)
|
|
||||||
assert.NotEmpty(t, id.Fingerprint)
|
|
||||||
assert.NotEmpty(t, id.Issuer)
|
|
||||||
|
|
||||||
// Our own address answers the same way: the hostmap never holds ourselves.
|
|
||||||
self := identity(t, f, "10.0.0.1")
|
|
||||||
assert.Equal(t, id, self.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIdentityReportsAPeerFromItsCertificate(t *testing.T) {
|
|
||||||
f, peerCert := identityFixture(t)
|
|
||||||
|
|
||||||
for _, addr := range []string{
|
|
||||||
"10.0.0.2",
|
|
||||||
"10.0.0.2:54321", // a connection's RemoteAddr, as a server has it
|
|
||||||
"::ffff:10.0.0.2", // the same peer seen through a dual stack listener
|
|
||||||
"[::ffff:10.0.0.2]:8", // and with a port
|
|
||||||
} {
|
|
||||||
r := identity(t, f, addr)
|
|
||||||
require.True(t, r.OK, "%s: %s", addr, r.Reason)
|
|
||||||
id := r.Value.(hostIdentity)
|
|
||||||
assert.Equal(t, "peer", id.Name, addr)
|
|
||||||
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.0.0.2")}, id.VpnAddrs, addr)
|
|
||||||
assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.2/24")}, id.Networks, addr)
|
|
||||||
assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("192.168.1.0/24")}, id.UnsafeNetworks, addr)
|
|
||||||
assert.Equal(t, []string{"web", "db"}, id.Groups, addr)
|
|
||||||
assert.Equal(t, peerCert.Issuer(), id.Issuer, addr)
|
|
||||||
assert.Equal(t, peerCert.NotAfter(), id.NotAfter, addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestIdentityRefusals: the ways a lookup fails are told apart, because a program
|
|
||||||
// deciding whether to let a connection in treats them differently.
|
|
||||||
func TestIdentityRefusals(t *testing.T) {
|
|
||||||
f, _ := identityFixture(t)
|
|
||||||
|
|
||||||
unknown := identity(t, f, "10.0.0.9")
|
|
||||||
assert.False(t, unknown.OK)
|
|
||||||
assert.True(t, unknown.NotFound, "no tunnel is a not found")
|
|
||||||
assert.Equal(t, "No active tunnel for vpn addr: 10.0.0.9", unknown.Reason)
|
|
||||||
|
|
||||||
pending := identity(t, f, "10.0.0.3:1")
|
|
||||||
assert.True(t, pending.NotFound, "a tunnel without a certificate yet is not active")
|
|
||||||
assert.Equal(t, "No active tunnel for vpn addr: 10.0.0.3", pending.Reason, "the reason names the address, not the port")
|
|
||||||
|
|
||||||
garbage := identity(t, f, "not-an-address")
|
|
||||||
assert.False(t, garbage.OK)
|
|
||||||
assert.False(t, garbage.NotFound, "an address that does not parse is the caller's mistake")
|
|
||||||
assert.Equal(t, "The provided vpn addr could not be parsed: not-an-address", garbage.Reason)
|
|
||||||
|
|
||||||
// An address that was given and is empty is a caller that failed to fill it in, and
|
|
||||||
// must not be answered with our own identity.
|
|
||||||
empty := identity(t, f, "")
|
|
||||||
assert.False(t, empty.OK)
|
|
||||||
assert.False(t, empty.NotFound)
|
|
||||||
assert.Equal(t, "The provided vpn addr could not be parsed: ", empty.Reason)
|
|
||||||
|
|
||||||
operand := identity(t, f, "", "10.0.0.2")
|
|
||||||
assert.False(t, operand.OK)
|
|
||||||
assert.Contains(t, operand.Reason, "identity -address 10.0.0.2")
|
|
||||||
|
|
||||||
// No address at all is a caller that forgot the parameter, and is pointed at whoami
|
|
||||||
// rather than handed this node's identity.
|
|
||||||
omitted, err := runIdentity(f, &identityFlags{}, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.False(t, omitted.OK)
|
|
||||||
assert.False(t, omitted.NotFound)
|
|
||||||
assert.Contains(t, omitted.Reason, "-address")
|
|
||||||
assert.Contains(t, omitted.Reason, "whoami")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestOwnCertificatePrefersV2: with both versions loaded, the v2 certificate is the one
|
|
||||||
// myVpnAddrsTable is built from and may carry addresses the v1 does not, so it is the one
|
|
||||||
// whoami and an identity lookup of our own address report, whichever version handshakes
|
|
||||||
// are initiated with.
|
|
||||||
func TestOwnCertificatePrefersV2(t *testing.T) {
|
|
||||||
v4 := netip.MustParsePrefix("10.0.0.1/24")
|
|
||||||
ca1, _, caKey1, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
v1, _, _, _ := cert_test.NewTestCert(cert.Version1, cert.Curve_CURVE25519, ca1, caKey1, "me", time.Time{}, time.Time{}, []netip.Prefix{v4}, nil, nil)
|
|
||||||
ca2, _, caKey2, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
|
||||||
v2, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca2, caKey2, "me", time.Time{}, time.Time{},
|
|
||||||
[]netip.Prefix{v4, netip.MustParsePrefix("fd00::1/64")}, nil, nil)
|
|
||||||
|
|
||||||
assert.Nil(t, ownCertificate(nil))
|
|
||||||
assert.Equal(t, v1, ownCertificate(&CertState{v1Cert: v1, initiatingVersion: cert.Version1}))
|
|
||||||
assert.Equal(t, v2, ownCertificate(&CertState{v2Cert: v2, initiatingVersion: cert.Version2}))
|
|
||||||
assert.Equal(t, v2, ownCertificate(&CertState{v1Cert: v1, v2Cert: v2, initiatingVersion: cert.Version1}),
|
|
||||||
"the initiating version is v1, the reported certificate is still the v2")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestIdentityShapes pins the JSON a program reads and the text a person reads. The
|
|
||||||
// field names are an API served to programs not built against nebula.
|
|
||||||
func TestIdentityShapes(t *testing.T) {
|
|
||||||
f, _ := identityFixture(t)
|
|
||||||
r := identity(t, f, "10.0.0.2")
|
|
||||||
|
|
||||||
b, err := json.Marshal(r.Payload())
|
|
||||||
require.NoError(t, err)
|
|
||||||
var got map[string]any
|
|
||||||
require.NoError(t, json.Unmarshal(b, &got))
|
|
||||||
var keys []string
|
|
||||||
for k := range got {
|
|
||||||
keys = append(keys, k)
|
|
||||||
}
|
|
||||||
assert.ElementsMatch(t, []string{
|
|
||||||
"name", "vpnAddrs", "networks", "unsafeNetworks", "groups",
|
|
||||||
"fingerprint", "issuer", "notBefore", "notAfter", "certVersion",
|
|
||||||
}, keys)
|
|
||||||
|
|
||||||
// Empty lists marshal as [], never null.
|
|
||||||
self := whoami(t, f)
|
|
||||||
b, err = json.Marshal(self.Payload())
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Contains(t, string(b), `"groups":[]`)
|
|
||||||
assert.Contains(t, string(b), `"unsafeNetworks":[]`)
|
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
require.NoError(t, commands.Render(&commands.Command{Name: commands.Identity, Text: commands.Typed(textIdentity)}, r, commands.FormatText, out))
|
|
||||||
assert.Contains(t, out.String(), "name: peer\n")
|
|
||||||
assert.Contains(t, out.String(), "vpn addrs: 10.0.0.2\n")
|
|
||||||
assert.Contains(t, out.String(), "groups: web, db\n")
|
|
||||||
assert.Contains(t, out.String(), "cert version: 2\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParseVpnAddrWithOptionalPort(t *testing.T) {
|
|
||||||
for in, want := range map[string]string{
|
|
||||||
"10.0.0.2": "10.0.0.2",
|
|
||||||
"10.0.0.2:443": "10.0.0.2",
|
|
||||||
"fd00::1": "fd00::1",
|
|
||||||
"[fd00::1]:443": "fd00::1",
|
|
||||||
"::ffff:10.0.0.2": "10.0.0.2",
|
|
||||||
"[::ffff:10.0.0.2]:1": "10.0.0.2",
|
|
||||||
"fe80::1%eth0": "fe80::1",
|
|
||||||
} {
|
|
||||||
got, err := parseVpnAddrWithOptionalPort(in)
|
|
||||||
require.NoError(t, err, in)
|
|
||||||
assert.Equal(t, netip.MustParseAddr(want), got, in)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, in := range []string{"", "10.0.0.2:", ":443", "10.0.0", "example.com:80"} {
|
|
||||||
_, err := parseVpnAddrWithOptionalPort(in)
|
|
||||||
assert.Error(t, err, in)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,34 +2,17 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/iputil"
|
"github.com/slackhq/nebula/iputil"
|
||||||
"github.com/slackhq/nebula/logging"
|
|
||||||
"github.com/slackhq/nebula/noiseutil"
|
"github.com/slackhq/nebula/noiseutil"
|
||||||
"github.com/slackhq/nebula/overlay/batch"
|
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
|
||||||
"github.com/slackhq/nebula/routing"
|
"github.com/slackhq/nebula/routing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
|
||||||
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
|
||||||
// only valid until the next Read on that queue. Every consumer below
|
|
||||||
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
|
||||||
// synchronously; do not retain pkt outside this call. If a future
|
|
||||||
// caller needs to keep the packet, use pkt.Clone() to detach it from
|
|
||||||
// the borrow.
|
|
||||||
//
|
|
||||||
// pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
|
|
||||||
// superpacket. In both cases the L3+L4 headers at the start describe
|
|
||||||
// the same 5-tuple every segment will share, so a single newPacket /
|
|
||||||
// firewall check covers the whole superpacket.
|
|
||||||
packet := pkt.Bytes
|
|
||||||
err := newPacket(packet, false, fwPacket)
|
err := newPacket(packet, false, fwPacket)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
@@ -54,17 +37,7 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
// routes packets from the Nebula addr to the Nebula addr through the Nebula
|
// routes packets from the Nebula addr to the Nebula addr through the Nebula
|
||||||
// TUN device.
|
// TUN device.
|
||||||
if immediatelyForwardToSelf {
|
if immediatelyForwardToSelf {
|
||||||
// Write copies into the kernel queue synchronously, so seg's lifetime ends at return.
|
_, err := f.readers[q].Write(packet)
|
||||||
// A self-forwarded superpacket would be re-handed to the
|
|
||||||
// kernel as one giant blob; segment first so the loopback
|
|
||||||
// path sees one IP datagram per Write.
|
|
||||||
err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
|
||||||
// The kernel may have left the transport checksum for hardware
|
|
||||||
// offload to finish; nothing between here and the tun will.
|
|
||||||
iputil.SetTransportChecksum(seg)
|
|
||||||
_, werr := f.queues[q].Write(seg)
|
|
||||||
return werr
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
f.l.Error("Failed to forward to tun", "error", err)
|
f.l.Error("Failed to forward to tun", "error", err)
|
||||||
}
|
}
|
||||||
@@ -79,24 +52,12 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
|
hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
|
||||||
// borrowed: SegmentSuperpacket builds each segment in the kernel-supplied pkt
|
hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
|
||||||
// bytes underneath. cachePacket explicitly copies its argument (handshake_manager.go cachePacket),
|
|
||||||
// so retaining segments past the loop is safe.
|
|
||||||
err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
|
||||||
hh.cachePacket(f.l, header.Message, 0, seg, f.sendMessageNow, f.cachedPacketMetrics)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil && f.l.Enabled(context.Background(), slog.LevelDebug) {
|
|
||||||
f.l.Debug("Failed to segment superpacket for handshake cache",
|
|
||||||
"error", err,
|
|
||||||
"vpnAddr", fwPacket.RemoteAddr,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if hostinfo == nil {
|
if hostinfo == nil {
|
||||||
f.rejectInside(packet, rejectBuf, q)
|
f.rejectInside(packet, out, q)
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
|
f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
|
||||||
"vpnAddr", fwPacket.RemoteAddr,
|
"vpnAddr", fwPacket.RemoteAddr,
|
||||||
@@ -110,11 +71,12 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||||
if dropReason == nil {
|
if dropReason == nil {
|
||||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
f.rejectInside(packet, rejectBuf, q)
|
f.rejectInside(packet, out, q)
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
||||||
"fwPacket", fwPacket,
|
"fwPacket", fwPacket,
|
||||||
@@ -124,122 +86,6 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
|
|
||||||
if noiseutil.EncryptLockNeeded {
|
|
||||||
ci.writeLock.Lock()
|
|
||||||
}
|
|
||||||
c := ci.messageCounter.Add(1)
|
|
||||||
|
|
||||||
out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
|
|
||||||
|
|
||||||
out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
|
|
||||||
if noiseutil.EncryptLockNeeded {
|
|
||||||
ci.writeLock.Unlock()
|
|
||||||
}
|
|
||||||
if encErr != nil {
|
|
||||||
hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
|
|
||||||
"error", encErr,
|
|
||||||
"udpAddr", hostinfo.GetRemote(),
|
|
||||||
"counter", c,
|
|
||||||
)
|
|
||||||
// Skip this segment; the rest of the superpacket can still go out. TCP will retransmit anything we drop here.
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// sendInsideMessage encrypts a firewall-approved inside packet (or every
|
|
||||||
// segment of a TSO/USO superpacket) into the caller's batch slot for
|
|
||||||
// later sendmmsg flush. Segmentation is fused with encryption here so the
|
|
||||||
// kernel-supplied superpacket bytes never get written into a separate
|
|
||||||
// scratch arena: SegmentSuperpacket builds each segment's plaintext in
|
|
||||||
// segScratch[:segLen] in turn, and we encrypt directly into a fresh SendBatch slot.
|
|
||||||
func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch *batch.SendBatch) {
|
|
||||||
ci := hostinfo.ConnectionState
|
|
||||||
if ci.eKey == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// One traffic-out mark covers every segment of the superpacket; doing it
|
|
||||||
// per segment in sendInsideEncrypt paid an atomic store up to ~45 extra
|
|
||||||
// times per TSO packet, inside writeLock under boring crypto.
|
|
||||||
//
|
|
||||||
// We rebound since this tunnel last sent, ask the lighthouse to get the far side punching at us again
|
|
||||||
if f.connectionManager.Out(hostinfo) {
|
|
||||||
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
|
||||||
hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind epoch",
|
|
||||||
"vpnAddrs", hostinfo.vpnAddrs,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
remote := hostinfo.GetRemote()
|
|
||||||
if !remote.IsValid() { //the relay path
|
|
||||||
//first, find our relay hostinfo:
|
|
||||||
var relayHostInfo *HostInfo
|
|
||||||
var relay *Relay
|
|
||||||
var err error
|
|
||||||
for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
|
|
||||||
relayHostInfo, relay, err = f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
|
|
||||||
if err != nil {
|
|
||||||
hostinfo.relayState.DeleteRelay(relayIP)
|
|
||||||
hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
|
|
||||||
"relay", relayIP,
|
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if relayHostInfo == nil || relay == nil {
|
|
||||||
//failure already logged
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
|
||||||
//relay header + header + plaintext + AEAD tag + relay tag
|
|
||||||
scratch := sendBatch.Reserve(len(seg) + header.MaxOverhead)
|
|
||||||
|
|
||||||
innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
|
|
||||||
if innerPacket == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//now we need to do a relay-encrypt:
|
|
||||||
toSend, err := f.prepareSendVia(relayHostInfo, relay, innerPacket, nb, scratch, true)
|
|
||||||
if err != nil {
|
|
||||||
//already logged
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
sendBatch.Commit(toSend, relayHostInfo.GetRemote())
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
hostinfo.logger(f.l).Error("Failed to segment superpacket for relay send", "error", err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
|
||||||
// header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
|
|
||||||
scratch := sendBatch.Reserve(header.Len + len(seg) + 16)
|
|
||||||
|
|
||||||
out := f.sendInsideEncrypt(hostinfo, ci, seg, scratch, nb)
|
|
||||||
if out == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
sendBatch.Commit(out, remote)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
hostinfo.logger(f.l).Error("Failed to segment superpacket for send", "error", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
|
func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
|
||||||
if !f.firewall.OutboundSendReject {
|
if !f.firewall.OutboundSendReject {
|
||||||
return
|
return
|
||||||
@@ -250,36 +96,33 @@ func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := f.queues[q].Write(out)
|
_, err := f.readers[q].Write(out)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
f.l.Error("Failed to write to tun", "error", err)
|
f.l.Error("Failed to write to tun", "error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, rejectBuf []byte, q int) {
|
func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
|
||||||
if !f.firewall.InboundSendReject {
|
if !f.firewall.InboundSendReject {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// split rejectBuf to make sure we have room to write the plaintext rejection, then encrypt it, without trampling anything
|
out = iputil.CreateRejectPacket(packet, out)
|
||||||
// we can't re-use packet, if we need to send an icmp reject, it won't be long enough.
|
|
||||||
half := len(rejectBuf) / 2
|
|
||||||
encryptBuf := rejectBuf[0:0:half] //the first half of rejectBuf's capacity, len set to 0
|
|
||||||
buildBuf := rejectBuf[half:]
|
|
||||||
|
|
||||||
out := iputil.CreateRejectPacket(packet, buildBuf)
|
|
||||||
if len(out) == 0 {
|
if len(out) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(out) > iputil.MaxRejectPacketSize {
|
if len(out) > iputil.MaxRejectPacketSize {
|
||||||
if f.l.Enabled(context.Background(), slog.LevelInfo) {
|
if f.l.Enabled(context.Background(), slog.LevelInfo) {
|
||||||
f.l.Info("rejectOutside: packet too big, not sending", "packet", packet, "outPacket", out)
|
f.l.Info("rejectOutside: packet too big, not sending",
|
||||||
|
"packet", packet,
|
||||||
|
"outPacket", out,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, encryptBuf, q)
|
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
|
// Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
|
||||||
@@ -373,7 +216,7 @@ func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cac
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
|
func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
|
||||||
fp := &firewall.ParsedPacket{}
|
fp := &firewall.Packet{}
|
||||||
err := newPacket(p, false, fp)
|
err := newPacket(p, false, fp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
|
f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
|
||||||
@@ -381,7 +224,7 @@ func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubTyp
|
|||||||
}
|
}
|
||||||
|
|
||||||
// check if packet is in outbound fw rules
|
// check if packet is in outbound fw rules
|
||||||
dropReason := f.firewall.Drop(fp.Packet, false, hostinfo, f.pki.GetCAPool(), nil)
|
dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
|
||||||
if dropReason != nil {
|
if dropReason != nil {
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
f.l.Debug("dropping cached packet",
|
f.l.Debug("dropping cached packet",
|
||||||
@@ -432,36 +275,29 @@ func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *C
|
|||||||
f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
|
f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dropExhausted records an exhaustion drop and logs once, on the crossing send, for a spent tunnel.
|
// SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
|
||||||
func (f *Interface) dropExhausted(hostinfo *HostInfo, c uint64, msg string) {
|
// to the payload for the ultimate target host, making this a useful method for sending
|
||||||
f.messageMetrics.TxExhausted(1)
|
// handshake messages to peers through relay tunnels.
|
||||||
if c == RejectAfterMessages {
|
// via is the HostInfo through which the message is relayed.
|
||||||
hostinfo.logger(f.l).Error(msg)
|
// ad is the plaintext data to authenticate, but not encrypt
|
||||||
}
|
// nb is a buffer used to store the nonce value, re-used for performance reasons.
|
||||||
}
|
// out is a buffer used to store the result of the Encrypt operation
|
||||||
|
// q indicates which writer to use to send the packet.
|
||||||
func (f *Interface) prepareSendVia(via *HostInfo,
|
func (f *Interface) SendVia(via *HostInfo,
|
||||||
relay *Relay,
|
relay *Relay,
|
||||||
ad,
|
ad,
|
||||||
nb,
|
nb,
|
||||||
out []byte,
|
out []byte,
|
||||||
nocopy bool,
|
nocopy bool,
|
||||||
) ([]byte, error) {
|
) {
|
||||||
if noiseutil.EncryptLockNeeded {
|
if noiseutil.EncryptLockNeeded {
|
||||||
// NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
|
// NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
|
||||||
via.ConnectionState.writeLock.Lock()
|
via.ConnectionState.writeLock.Lock()
|
||||||
}
|
}
|
||||||
c, ok := via.ConnectionState.NextMessageCounter()
|
c := via.ConnectionState.messageCounter.Add(1)
|
||||||
if !ok {
|
|
||||||
if noiseutil.EncryptLockNeeded {
|
|
||||||
via.ConnectionState.writeLock.Unlock()
|
|
||||||
}
|
|
||||||
f.dropExhausted(via, c, "Dropping outbound relay packets, tunnel message counter is exhausted")
|
|
||||||
return nil, fmt.Errorf("tunnel message counter is exhausted")
|
|
||||||
}
|
|
||||||
|
|
||||||
out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
|
out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
|
||||||
f.connectionManager.OutNoRebind(via)
|
f.connectionManager.Out(via)
|
||||||
|
|
||||||
// Authenticate the header and payload, but do not encrypt for this message type.
|
// Authenticate the header and payload, but do not encrypt for this message type.
|
||||||
// The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
|
// The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
|
||||||
@@ -475,7 +311,7 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
|||||||
"headerLen", len(out),
|
"headerLen", len(out),
|
||||||
"cipherOverhead", via.ConnectionState.eKey.Overhead(),
|
"cipherOverhead", via.ConnectionState.eKey.Overhead(),
|
||||||
)
|
)
|
||||||
return nil, io.ErrShortBuffer
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
|
// The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
|
||||||
@@ -495,33 +331,13 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
|||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
|
via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
f.connectionManager.RelayUsed(relay.LocalIndex)
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
|
|
||||||
// to the payload for the ultimate target host, making this a useful method for sending
|
|
||||||
// handshake messages to peers through relay tunnels.
|
|
||||||
// via is the HostInfo through which the message is relayed.
|
|
||||||
// ad is the plaintext data to authenticate, but not encrypt
|
|
||||||
// nb is a buffer used to store the nonce value, re-used for performance reasons.
|
|
||||||
// out is a buffer used to store the result of the Encrypt operation
|
|
||||||
// q indicates which writer to use to send the packet.
|
|
||||||
func (f *Interface) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
|
|
||||||
toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
|
|
||||||
if err != nil {
|
|
||||||
// already logged by prepareSendVia
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
err = f.writers[0].WriteTo(out, via.GetRemote())
|
||||||
err = f.writers[q].WriteTo(toSend, via.GetRemote())
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if l, ok := logging.RateLimited(f.l, f.udpRelayTxErrLimiter); ok {
|
via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
|
||||||
via.logger(l).Info("Failed to WriteTo in sendVia", "error", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
f.connectionManager.RelayUsed(relay.LocalIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
|
func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
|
||||||
@@ -529,47 +345,29 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
||||||
|
|
||||||
// The encrypt appends to out in place and a relayed packet is then wrapped in place,
|
|
||||||
// so out has to fit the whole packet up front or the encrypt reallocates out from under SendVia.
|
|
||||||
// We cap the MTU of tun devices and routes we create ourselves, so only a host that set a bigger MTU than we allow gets here.
|
|
||||||
need := header.Len + len(p) + ci.eKey.Overhead()
|
|
||||||
if useRelay {
|
|
||||||
// The relay tunnel runs the same cipher, and adds its own header and tag
|
|
||||||
need += header.Len + ci.eKey.Overhead()
|
|
||||||
}
|
|
||||||
if cap(out) < need {
|
|
||||||
if l, ok := logging.RateLimited(f.l, f.txOversizeLimiter); ok {
|
|
||||||
hostinfo.logger(l).Error("Dropping outbound packet, out buffer not large enough", "outCap", cap(out), "payloadLen", len(p), "relayed", useRelay)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fullOut := out
|
fullOut := out
|
||||||
|
|
||||||
if useRelay {
|
if useRelay {
|
||||||
|
if len(out) < header.Len {
|
||||||
|
// out always has a capacity of mtu, but not always a length greater than the header.Len.
|
||||||
|
// Grow it to make sure the next operation works.
|
||||||
|
out = out[:header.Len]
|
||||||
|
}
|
||||||
// Save a header's worth of data at the front of the 'out' buffer.
|
// Save a header's worth of data at the front of the 'out' buffer.
|
||||||
out = out[header.Len:header.Len]
|
out = out[header.Len:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if noiseutil.EncryptLockNeeded {
|
if noiseutil.EncryptLockNeeded {
|
||||||
// NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
|
// NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
|
||||||
ci.writeLock.Lock()
|
ci.writeLock.Lock()
|
||||||
}
|
}
|
||||||
c, ok := ci.NextMessageCounter()
|
c := ci.messageCounter.Add(1)
|
||||||
if !ok {
|
|
||||||
if noiseutil.EncryptLockNeeded {
|
|
||||||
ci.writeLock.Unlock()
|
|
||||||
}
|
|
||||||
f.dropExhausted(hostinfo, c, "Dropping outbound packets, tunnel message counter is exhausted")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
//l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
|
//l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
|
||||||
out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
|
out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
|
||||||
// A closing tunnel is torn down right after this, so skip the connection manager entirely: no point recording
|
// We rebound since this tunnel last sent, so the local network moved. Ask the lighthouse to have the far side
|
||||||
// traffic or asking the lighthouse for a punch. Otherwise, if we rebound since this tunnel last sent, ask the
|
// punch at where we are now, which primes their conntrack the same way a handshake would.
|
||||||
// lighthouse to get the far side punching at us again.
|
if f.connectionManager.Out(hostinfo) && t != header.CloseTunnel {
|
||||||
if t != header.CloseTunnel && f.connectionManager.Out(hostinfo) {
|
|
||||||
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
f.l.Debug("Lighthouse update triggered for punch due to rebind epoch",
|
f.l.Debug("Lighthouse update triggered for punch due to rebind epoch",
|
||||||
@@ -595,22 +393,18 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
|||||||
if remote.IsValid() {
|
if remote.IsValid() {
|
||||||
err = f.writers[q].WriteTo(out, remote)
|
err = f.writers[q].WriteTo(out, remote)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if l, ok := logging.RateLimited(f.l, f.udpTxErrLimiter); ok {
|
hostinfo.logger(f.l).Error("Failed to write outgoing packet",
|
||||||
hostinfo.logger(l).Error("Failed to write outgoing packet",
|
"error", err,
|
||||||
"error", err,
|
"udpAddr", remote,
|
||||||
"udpAddr", remote,
|
)
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if hr := hostinfo.GetRemote(); hr.IsValid() {
|
} else if hr := hostinfo.GetRemote(); hr.IsValid() {
|
||||||
err = f.writers[q].WriteTo(out, hr)
|
err = f.writers[q].WriteTo(out, hr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if l, ok := logging.RateLimited(f.l, f.udpTxErrLimiter); ok {
|
hostinfo.logger(f.l).Error("Failed to write outgoing packet",
|
||||||
hostinfo.logger(l).Error("Failed to write outgoing packet",
|
"error", err,
|
||||||
"error", err,
|
"udpAddr", hr,
|
||||||
"udpAddr", hr,
|
)
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Try to send via a relay
|
// Try to send via a relay
|
||||||
@@ -624,7 +418,7 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
|||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true, q)
|
f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-265
@@ -1,265 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"io"
|
|
||||||
"net/netip"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
|
||||||
"github.com/slackhq/nebula/firewall"
|
|
||||||
"github.com/slackhq/nebula/iputil"
|
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
ipv4HeaderLen = 20
|
|
||||||
ipv6HeaderLen = 40
|
|
||||||
)
|
|
||||||
|
|
||||||
// capturingTun is a tio.Queue that records what is written to it. A queue that
|
|
||||||
// discards writes is indistinguishable from a packet that was never forwarded.
|
|
||||||
type capturingTun struct {
|
|
||||||
writes [][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *capturingTun) Read() ([]tio.Packet, error) { return nil, io.EOF }
|
|
||||||
func (c *capturingTun) Close() error { return nil }
|
|
||||||
|
|
||||||
func (c *capturingTun) Write(b []byte) (int, error) {
|
|
||||||
c.writes = append(c.writes, append([]byte(nil), b...))
|
|
||||||
return len(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newSelfForwardInterface(myAddrs ...netip.Addr) (*Interface, *capturingTun) {
|
|
||||||
vpnAddrs := &bart.Lite{}
|
|
||||||
for _, a := range myAddrs {
|
|
||||||
vpnAddrs.Insert(netip.PrefixFrom(a, a.BitLen()))
|
|
||||||
}
|
|
||||||
|
|
||||||
tun := &capturingTun{}
|
|
||||||
return &Interface{
|
|
||||||
l: test.NewLogger(),
|
|
||||||
myVpnAddrsTable: vpnAddrs,
|
|
||||||
myBroadcastAddrsTable: &bart.Lite{},
|
|
||||||
queues: []tio.Queue{tun},
|
|
||||||
}, tun
|
|
||||||
}
|
|
||||||
|
|
||||||
func consumeInside(f *Interface, packet []byte) {
|
|
||||||
f.consumeInsidePacket(tio.Packet{Bytes: packet}, &firewall.ParsedPacket{}, make([]byte, 12), nil, make([]byte, mtu), 0, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// l4Proto describes one upper-layer header for these tests: its IP next-header
|
|
||||||
// value, where its checksum field sits within the header, and how to build a
|
|
||||||
// minimal instance of it.
|
|
||||||
type l4Proto struct {
|
|
||||||
name string
|
|
||||||
nextHdr uint8
|
|
||||||
cksumAt int
|
|
||||||
build func() []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
tcpSyn = l4Proto{"tcp", iputil.IPProtocolTCP, 16, func() []byte {
|
|
||||||
h := make([]byte, 20)
|
|
||||||
binary.BigEndian.PutUint16(h[0:2], 49152)
|
|
||||||
binary.BigEndian.PutUint16(h[2:4], 443)
|
|
||||||
binary.BigEndian.PutUint32(h[4:8], 0x11223344) // sequence
|
|
||||||
h[12] = 5 << 4 // data offset, no options
|
|
||||||
h[13] = 0x02 // SYN
|
|
||||||
binary.BigEndian.PutUint16(h[14:16], 65535) // window
|
|
||||||
return h
|
|
||||||
}}
|
|
||||||
|
|
||||||
udpDatagram = l4Proto{"udp", iputil.IPProtocolUDP, 6, func() []byte {
|
|
||||||
h := make([]byte, 8+4)
|
|
||||||
binary.BigEndian.PutUint16(h[0:2], 49152)
|
|
||||||
binary.BigEndian.PutUint16(h[2:4], 53)
|
|
||||||
binary.BigEndian.PutUint16(h[4:6], uint16(len(h)))
|
|
||||||
copy(h[8:], "ping")
|
|
||||||
return h
|
|
||||||
}}
|
|
||||||
|
|
||||||
icmpEcho = l4Proto{"icmp", iputil.IPProtocolICMP, 2, func() []byte { return echoRequest(8) }}
|
|
||||||
icmpv6Echo = l4Proto{"icmpv6", iputil.IPProtocolICMPv6, 2, func() []byte { return echoRequest(128) }}
|
|
||||||
)
|
|
||||||
|
|
||||||
// echoRequest builds an echo request body. The type differs between ICMP and
|
|
||||||
// ICMPv6, the rest of the header does not.
|
|
||||||
func echoRequest(typ uint8) []byte {
|
|
||||||
h := make([]byte, 8)
|
|
||||||
h[0] = typ
|
|
||||||
binary.BigEndian.PutUint16(h[4:6], 0xbeef) // identifier
|
|
||||||
binary.BigEndian.PutUint16(h[6:8], 1) // sequence
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildIPv6(src, dst netip.Addr, p l4Proto) []byte {
|
|
||||||
l4 := p.build()
|
|
||||||
pkt := make([]byte, ipv6HeaderLen+len(l4))
|
|
||||||
pkt[0] = 0x60
|
|
||||||
binary.BigEndian.PutUint16(pkt[4:6], uint16(len(l4)))
|
|
||||||
pkt[6] = p.nextHdr
|
|
||||||
pkt[7] = 64
|
|
||||||
copy(pkt[8:24], src.AsSlice())
|
|
||||||
copy(pkt[24:40], dst.AsSlice())
|
|
||||||
copy(pkt[ipv6HeaderLen:], l4)
|
|
||||||
if l4 := pkt[ipv6HeaderLen:]; p.nextHdr == iputil.IPProtocolTCP || p.nextHdr == iputil.IPProtocolUDP {
|
|
||||||
sum := ipv6PseudoheaderSum(src, dst, uint32(p.nextHdr), uint32(len(l4)))
|
|
||||||
binary.BigEndian.PutUint16(l4[p.cksumAt:], ^fold(sumBytes(l4, sum)))
|
|
||||||
}
|
|
||||||
return pkt
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildIPv4(src, dst netip.Addr, p l4Proto) []byte {
|
|
||||||
l4 := p.build()
|
|
||||||
pkt := make([]byte, ipv4HeaderLen+len(l4))
|
|
||||||
pkt[0] = 0x45
|
|
||||||
binary.BigEndian.PutUint16(pkt[2:4], uint16(len(pkt)))
|
|
||||||
pkt[8] = 64
|
|
||||||
pkt[9] = p.nextHdr
|
|
||||||
copy(pkt[12:16], src.AsSlice())
|
|
||||||
copy(pkt[16:20], dst.AsSlice())
|
|
||||||
copy(pkt[ipv4HeaderLen:], l4)
|
|
||||||
if l4 := pkt[ipv4HeaderLen:]; p.nextHdr == iputil.IPProtocolTCP || p.nextHdr == iputil.IPProtocolUDP {
|
|
||||||
sum := sumBytes(pkt[12:20], uint32(p.nextHdr)+uint32(len(l4)))
|
|
||||||
binary.BigEndian.PutUint16(l4[p.cksumAt:], ^fold(sumBytes(l4, sum)))
|
|
||||||
}
|
|
||||||
return pkt
|
|
||||||
}
|
|
||||||
|
|
||||||
// ipv6PseudoheaderSum is the RFC 2460 section 8.1 pseudo-header sum: source,
|
|
||||||
// destination, a 32 bit upper-layer packet length and a 32 bit zero-padded next
|
|
||||||
// header. Kept local to the test so these assertions do not check nebula's
|
|
||||||
// checksum code against itself.
|
|
||||||
func ipv6PseudoheaderSum(src, dst netip.Addr, nextHeader, length uint32) uint32 {
|
|
||||||
var csum uint32
|
|
||||||
s, d := src.AsSlice(), dst.AsSlice()
|
|
||||||
for i := 0; i < 16; i += 2 {
|
|
||||||
csum += uint32(s[i])<<8 | uint32(s[i+1])
|
|
||||||
csum += uint32(d[i])<<8 | uint32(d[i+1])
|
|
||||||
}
|
|
||||||
return csum + length + nextHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
func sumBytes(b []byte, csum uint32) uint32 {
|
|
||||||
for i := 0; i+1 < len(b); i += 2 {
|
|
||||||
csum += uint32(b[i])<<8 | uint32(b[i+1])
|
|
||||||
}
|
|
||||||
if len(b)%2 == 1 {
|
|
||||||
csum += uint32(b[len(b)-1]) << 8
|
|
||||||
}
|
|
||||||
return csum
|
|
||||||
}
|
|
||||||
|
|
||||||
func fold(csum uint32) uint16 {
|
|
||||||
for csum > 0xffff {
|
|
||||||
csum = (csum >> 16) + (csum & 0xffff)
|
|
||||||
}
|
|
||||||
return uint16(csum)
|
|
||||||
}
|
|
||||||
|
|
||||||
// l4ChecksumValid6 verifies an IPv6 upper-layer checksum the way a receiver
|
|
||||||
// does: the pseudo-header plus the whole upper-layer segment, checksum field
|
|
||||||
// included, folds to 0xffff. The next header field is the upper-layer protocol
|
|
||||||
// only while there are no extension headers, which is all this file builds.
|
|
||||||
func l4ChecksumValid6(pkt []byte) bool {
|
|
||||||
src, _ := netip.AddrFromSlice(pkt[8:24])
|
|
||||||
dst, _ := netip.AddrFromSlice(pkt[24:40])
|
|
||||||
l4 := pkt[ipv6HeaderLen:]
|
|
||||||
return fold(sumBytes(l4, ipv6PseudoheaderSum(src, dst, uint32(pkt[6]), uint32(len(l4))))) == 0xffff
|
|
||||||
}
|
|
||||||
|
|
||||||
// l4ChecksumValid4 is the IPv4 counterpart: the RFC 793/768 pseudo-header is
|
|
||||||
// source, destination, a zero byte, the protocol and the upper-layer length.
|
|
||||||
func l4ChecksumValid4(pkt []byte) bool {
|
|
||||||
ihl := int(pkt[0]&0x0f) << 2
|
|
||||||
l4 := pkt[ihl:]
|
|
||||||
return fold(sumBytes(l4, sumBytes(pkt[12:20], uint32(pkt[9])+uint32(len(l4))))) == 0xffff
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestConsumeInsidePacketSelfTraffic covers the self-addressed branch of
|
|
||||||
// consumeInsidePacket, taken where immediatelyForwardToSelf is set (see
|
|
||||||
// inside_bsd.go): the packet goes straight back to the tun, ahead of the
|
|
||||||
// firewall and the handshake.
|
|
||||||
func TestConsumeInsidePacketSelfTraffic(t *testing.T) {
|
|
||||||
v4 := netip.MustParseAddr("100.100.1.42")
|
|
||||||
v6 := netip.MustParseAddr("fd00::42")
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
addr netip.Addr
|
|
||||||
pkt []byte
|
|
||||||
}{
|
|
||||||
{"ipv4/tcp", v4, buildIPv4(v4, v4, tcpSyn)},
|
|
||||||
{"ipv4/udp", v4, buildIPv4(v4, v4, udpDatagram)},
|
|
||||||
{"ipv4/icmp", v4, buildIPv4(v4, v4, icmpEcho)},
|
|
||||||
{"ipv6/tcp", v6, buildIPv6(v6, v6, tcpSyn)},
|
|
||||||
{"ipv6/udp", v6, buildIPv6(v6, v6, udpDatagram)},
|
|
||||||
{"ipv6/icmpv6", v6, buildIPv6(v6, v6, icmpv6Echo)},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
f, tun := newSelfForwardInterface(tt.addr)
|
|
||||||
// consumeInsidePacket writes through the slice it is handed, so a
|
|
||||||
// packet that arrived with a valid checksum must come back out of
|
|
||||||
// bytes taken before the call, unchanged.
|
|
||||||
want := append([]byte(nil), tt.pkt...)
|
|
||||||
consumeInside(f, tt.pkt)
|
|
||||||
|
|
||||||
if immediatelyForwardToSelf {
|
|
||||||
require.Len(t, tun.writes, 1)
|
|
||||||
assert.Equal(t, want, tun.writes[0])
|
|
||||||
} else {
|
|
||||||
assert.Empty(t, tun.writes, "self traffic reaches the tun over loopback here and must be dropped")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestConsumeInsidePacketSelfTrafficChecksum shows that the self-forward
|
|
||||||
// returns the bytes it was handed, so a packet that arrived with a wrong
|
|
||||||
// upper-layer checksum is written back with that same wrong checksum and the
|
|
||||||
// kernel drops it on re-entry.
|
|
||||||
//
|
|
||||||
// This is how a macOS host loses TCP and UDP to its own IPv6 overlay address:
|
|
||||||
// the kernel writes only the pseudo-header sum into the checksum field and
|
|
||||||
// defers completion to hardware offload, state that does not survive the
|
|
||||||
// crossing into userspace. Which kernels do this, for which protocols and IP
|
|
||||||
// versions, is a property of the kernel and belongs to a test against a live
|
|
||||||
// one; here the checksum is simply wrong, and the forward must make it right.
|
|
||||||
func TestConsumeInsidePacketSelfTrafficChecksum(t *testing.T) {
|
|
||||||
if !immediatelyForwardToSelf {
|
|
||||||
t.Skip("self traffic never reaches the tun on this platform")
|
|
||||||
}
|
|
||||||
versions := []struct {
|
|
||||||
name string
|
|
||||||
addr netip.Addr
|
|
||||||
build func(src, dst netip.Addr, p l4Proto) []byte
|
|
||||||
l4At int
|
|
||||||
valid func(pkt []byte) bool
|
|
||||||
}{
|
|
||||||
{"v4", netip.MustParseAddr("100.100.1.42"), buildIPv4, ipv4HeaderLen, l4ChecksumValid4},
|
|
||||||
{"v6", netip.MustParseAddr("fd00::42"), buildIPv6, ipv6HeaderLen, l4ChecksumValid6},
|
|
||||||
}
|
|
||||||
for _, v := range versions {
|
|
||||||
for _, p := range []l4Proto{tcpSyn, udpDatagram} {
|
|
||||||
t.Run(v.name+"/"+p.name, func(t *testing.T) {
|
|
||||||
pkt := v.build(v.addr, v.addr, p)
|
|
||||||
binary.BigEndian.PutUint16(pkt[v.l4At+p.cksumAt:], 0x1234)
|
|
||||||
require.False(t, v.valid(pkt), "the packet under test must start with a wrong checksum")
|
|
||||||
f, tun := newSelfForwardInterface(v.addr)
|
|
||||||
consumeInside(f, pkt)
|
|
||||||
require.Len(t, tun.writes, 1)
|
|
||||||
assert.True(t, v.valid(tun.writes[0]),
|
|
||||||
"a forwarded %s packet must carry a valid checksum, got 0x%04x",
|
|
||||||
p.name, binary.BigEndian.Uint16(tun.writes[0][v.l4At+p.cksumAt:]))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+84
-265
@@ -2,12 +2,11 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/fips140"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"runtime"
|
|
||||||
"slices"
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -15,16 +14,12 @@ import (
|
|||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"github.com/rcrowley/go-metrics"
|
"github.com/rcrowley/go-metrics"
|
||||||
"github.com/slackhq/nebula/util"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/overlay"
|
"github.com/slackhq/nebula/overlay"
|
||||||
"github.com/slackhq/nebula/overlay/batch"
|
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
|
||||||
"github.com/slackhq/nebula/ratelimit"
|
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -54,19 +49,7 @@ type InterfaceConfig struct {
|
|||||||
reQueryWait time.Duration
|
reQueryWait time.Duration
|
||||||
|
|
||||||
ConntrackCacheTimeout time.Duration
|
ConntrackCacheTimeout time.Duration
|
||||||
|
l *slog.Logger
|
||||||
// CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
|
|
||||||
// should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
|
|
||||||
// shorter lists than `routines` cycle. Empty list keeps the default
|
|
||||||
// pin-to-(i % NumCPU) behavior. Only consulted when PinThreads is true.
|
|
||||||
CpuAffinity []int
|
|
||||||
// PinThreads controls whether each TUN reader OS thread is pinned to a
|
|
||||||
// single CPU (via tun.pin_threads, default true). Pinning keeps each
|
|
||||||
// goroutine's sendmmsg on one XPS-selected NIC TX ring so per-flow
|
|
||||||
// packets stay ordered on the wire.
|
|
||||||
PinThreads bool
|
|
||||||
|
|
||||||
l *slog.Logger
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Interface struct {
|
type Interface struct {
|
||||||
@@ -90,16 +73,7 @@ type Interface struct {
|
|||||||
routines int
|
routines int
|
||||||
disconnectInvalid atomic.Bool
|
disconnectInvalid atomic.Bool
|
||||||
closed atomic.Bool
|
closed atomic.Bool
|
||||||
// cpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
|
relayManager *relayManager
|
||||||
// should pin to. Queue i pins to cpuAffinity[i % len(cpuAffinity)].
|
|
||||||
// Empty falls back to the default pin-to-(allowed CPU) behavior.
|
|
||||||
// Only consulted when pinThreads is true.
|
|
||||||
cpuAffinity []int
|
|
||||||
// pinThreads controls whether listenIn pins each TUN reader OS thread to
|
|
||||||
// a CPU at all (tun.pin_threads, default true). When false, threads are
|
|
||||||
// left free to migrate as on stock nebula.
|
|
||||||
pinThreads bool
|
|
||||||
relayManager *relayManager
|
|
||||||
|
|
||||||
tryPromoteEvery atomic.Uint32
|
tryPromoteEvery atomic.Uint32
|
||||||
reQueryEvery atomic.Uint32
|
reQueryEvery atomic.Uint32
|
||||||
@@ -108,7 +82,9 @@ type Interface struct {
|
|||||||
sendRecvErrorConfig recvErrorConfig
|
sendRecvErrorConfig recvErrorConfig
|
||||||
acceptRecvErrorConfig recvErrorConfig
|
acceptRecvErrorConfig recvErrorConfig
|
||||||
|
|
||||||
// Bumped on every udp rebind, tunnels compare it to decide they need a punch from the far side
|
// rebindEpoch bumps every time the udp listener is rebound, which means the local network moved. Tunnels
|
||||||
|
// compare it against their own copy to decide they need a punch from the far side. Read on every send, only
|
||||||
|
// written on a rebind, so the cache line stays shared across the routines.
|
||||||
rebindEpoch atomic.Uint32
|
rebindEpoch atomic.Uint32
|
||||||
version string
|
version string
|
||||||
|
|
||||||
@@ -116,20 +92,8 @@ type Interface struct {
|
|||||||
|
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
writers []udp.Conn
|
writers []udp.Conn
|
||||||
queues []tio.Queue
|
readers []io.ReadWriteCloser
|
||||||
// batchers is one per tun queue, wrapping queues[i]. readOutsidePackets
|
wg sync.WaitGroup
|
||||||
// commits plaintext into the batcher; the plaintext is decrypted
|
|
||||||
// in place inside the UDP receive buffers, so listenOut must call Flush
|
|
||||||
// at the end of each UDP recvmmsg batch, before those buffers are
|
|
||||||
// reused (every udp.Conn ListenOut guarantees that ordering).
|
|
||||||
batchers []*batch.MultiCoalescer
|
|
||||||
wg sync.WaitGroup
|
|
||||||
// readers covers just the listenIn and listenOut goroutines, wg also holds the construction token Close releases
|
|
||||||
readers sync.WaitGroup
|
|
||||||
|
|
||||||
udpTxErrLimiter *ratelimit.Limiter // udp direct transmit error log limiter
|
|
||||||
udpRelayTxErrLimiter *ratelimit.Limiter // udp relay transmit error log limiter
|
|
||||||
txOversizeLimiter *ratelimit.Limiter // oversized outbound packet drop log limiter
|
|
||||||
|
|
||||||
// fatalErr holds the first unexpected reader error that caused shutdown.
|
// fatalErr holds the first unexpected reader error that caused shutdown.
|
||||||
// nil means "no fatal error" (yet)
|
// nil means "no fatal error" (yet)
|
||||||
@@ -140,13 +104,18 @@ type Interface struct {
|
|||||||
metricHandshakes metrics.Histogram
|
metricHandshakes metrics.Histogram
|
||||||
messageMetrics *MessageMetrics
|
messageMetrics *MessageMetrics
|
||||||
cachedPacketMetrics *cachedPacketMetrics
|
cachedPacketMetrics *cachedPacketMetrics
|
||||||
metricTxDropped metrics.Counter
|
|
||||||
|
|
||||||
l *slog.Logger
|
l *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
type EncWriter interface {
|
type EncWriter interface {
|
||||||
SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int)
|
SendVia(via *HostInfo,
|
||||||
|
relay *Relay,
|
||||||
|
ad,
|
||||||
|
nb,
|
||||||
|
out []byte,
|
||||||
|
nocopy bool,
|
||||||
|
)
|
||||||
SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
|
SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte)
|
||||||
SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
|
SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte)
|
||||||
Handshake(vpnAddr netip.Addr)
|
Handshake(vpnAddr netip.Addr)
|
||||||
@@ -205,23 +174,6 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
return nil, errors.New("no connection manager")
|
return nil, errors.New("no connection manager")
|
||||||
}
|
}
|
||||||
|
|
||||||
udpTxErrLimiter, err := ratelimit.New(1, time.Second)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
udpRelayTxErrLimiter, err := ratelimit.New(1, time.Second)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
txOversizeLimiter, err := ratelimit.New(1, time.Second)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.routines <= 1 {
|
|
||||||
c.PinThreads = false //pinning is not useful unless there's more than one tun reader
|
|
||||||
}
|
|
||||||
|
|
||||||
cs := c.pki.getCertState()
|
cs := c.pki.getCertState()
|
||||||
ifce := &Interface{
|
ifce := &Interface{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
@@ -239,7 +191,7 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
routines: c.routines,
|
routines: c.routines,
|
||||||
version: c.version,
|
version: c.version,
|
||||||
writers: make([]udp.Conn, c.routines),
|
writers: make([]udp.Conn, c.routines),
|
||||||
batchers: make([]*batch.MultiCoalescer, c.routines),
|
readers: make([]io.ReadWriteCloser, c.routines),
|
||||||
myVpnNetworks: cs.myVpnNetworks,
|
myVpnNetworks: cs.myVpnNetworks,
|
||||||
myVpnNetworksTable: cs.myVpnNetworksTable,
|
myVpnNetworksTable: cs.myVpnNetworksTable,
|
||||||
myVpnAddrs: cs.myVpnAddrs,
|
myVpnAddrs: cs.myVpnAddrs,
|
||||||
@@ -248,14 +200,8 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
relayManager: c.relayManager,
|
relayManager: c.relayManager,
|
||||||
connectionManager: c.connectionManager,
|
connectionManager: c.connectionManager,
|
||||||
conntrackCacheTimeout: c.ConntrackCacheTimeout,
|
conntrackCacheTimeout: c.ConntrackCacheTimeout,
|
||||||
cpuAffinity: c.CpuAffinity,
|
|
||||||
pinThreads: c.PinThreads,
|
|
||||||
udpTxErrLimiter: udpTxErrLimiter,
|
|
||||||
udpRelayTxErrLimiter: udpRelayTxErrLimiter,
|
|
||||||
txOversizeLimiter: txOversizeLimiter,
|
|
||||||
|
|
||||||
metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
|
metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
|
||||||
metricTxDropped: metrics.GetOrRegisterCounter("udp.tx.dropped", nil),
|
|
||||||
messageMetrics: c.MessageMetrics,
|
messageMetrics: c.MessageMetrics,
|
||||||
cachedPacketMetrics: &cachedPacketMetrics{
|
cachedPacketMetrics: &cachedPacketMetrics{
|
||||||
sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
|
sent: metrics.GetOrRegisterCounter("hostinfo.cached_packets.sent", nil),
|
||||||
@@ -294,41 +240,27 @@ func (f *Interface) activate() error {
|
|||||||
"build", f.version,
|
"build", f.version,
|
||||||
"udpAddr", addr,
|
"udpAddr", addr,
|
||||||
"boringcrypto", boringEnabled(),
|
"boringcrypto", boringEnabled(),
|
||||||
"fips140Version", fips140.Version(),
|
|
||||||
"fips140Enabled", fips140.Enabled(),
|
|
||||||
"fips140Enforced", fips140.Enforced(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if f.routines > 1 && !f.outside.SupportsMultipleReaders() {
|
if f.routines > 1 {
|
||||||
f.routines = 1
|
if !f.inside.SupportsMultiqueue() || !f.outside.SupportsMultipleReaders() {
|
||||||
f.l.Warn("multiple udp readers are not supported on this platform, falling back to a single routine")
|
f.routines = 1
|
||||||
|
f.l.Warn("routines is not supported on this platform, falling back to a single routine")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare the tun queues. A device that can't open that many hands back
|
|
||||||
// fewer (a single queue on platforms without multiqueue support) and we
|
|
||||||
// size the reader routines to what we actually got.
|
|
||||||
queues, err := f.inside.Queues(f.routines)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if len(queues) < f.routines {
|
|
||||||
// TODO: this clamp is only safe because it is unreachable when the
|
|
||||||
// udp side has multiple readers (linux Queues opens exactly n or
|
|
||||||
// errors; every other platform already clamped routines to 1 above).
|
|
||||||
// If a platform ever returns fewer queues than routines with
|
|
||||||
// SO_REUSEPORT sockets already bound, the surplus sockets get no
|
|
||||||
// listenOut and the kernel blackholes every flow it hashes to them —
|
|
||||||
// fail loudly or close the extra sockets instead.
|
|
||||||
f.l.Warn("tun multiqueue is not supported on this platform, falling back to fewer routines",
|
|
||||||
"requested", f.routines, "opened", len(queues))
|
|
||||||
f.routines = len(queues)
|
|
||||||
}
|
|
||||||
f.queues = queues
|
|
||||||
|
|
||||||
metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
|
metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
|
||||||
|
|
||||||
for i := range f.queues {
|
// Prepare n tun queues
|
||||||
f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l)
|
var reader io.ReadWriteCloser = f.inside
|
||||||
|
for i := 0; i < f.routines; i++ {
|
||||||
|
if i > 0 {
|
||||||
|
reader, err = f.inside.NewMultiQueueReader()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.readers[i] = reader
|
||||||
}
|
}
|
||||||
|
|
||||||
// On error the caller owns the cleanup, Control.Start cancels the service context
|
// On error the caller owns the cleanup, Control.Start cancels the service context
|
||||||
@@ -343,19 +275,15 @@ func (f *Interface) activate() error {
|
|||||||
func (f *Interface) run() {
|
func (f *Interface) run() {
|
||||||
// Launch n queues to read packets from udp
|
// Launch n queues to read packets from udp
|
||||||
for i := 0; i < f.routines; i++ {
|
for i := 0; i < f.routines; i++ {
|
||||||
f.readers.Add(1)
|
|
||||||
f.wg.Go(func() {
|
f.wg.Go(func() {
|
||||||
defer f.readers.Done()
|
|
||||||
f.listenOut(i)
|
f.listenOut(i)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Launch n queues to read packets from tun dev
|
// Launch n queues to read packets from tun dev
|
||||||
for i := 0; i < f.routines; i++ {
|
for i := 0; i < f.routines; i++ {
|
||||||
f.readers.Add(1)
|
|
||||||
f.wg.Go(func() {
|
f.wg.Go(func() {
|
||||||
defer f.readers.Done()
|
f.listenIn(f.readers[i], i)
|
||||||
f.listenIn(f.queues[i], i)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -380,31 +308,6 @@ func (f *Interface) onFatal(err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type rxContext struct {
|
|
||||||
q int
|
|
||||||
scratch []byte
|
|
||||||
// nb is a re-usable nonce buffer for decrypt calls to use
|
|
||||||
nb []byte
|
|
||||||
h *header.H
|
|
||||||
fwPacket *firewall.ParsedPacket
|
|
||||||
hostmapCache map[uint32]*HostInfo
|
|
||||||
lhh *LightHouseHandler
|
|
||||||
ctCache *firewall.ConntrackCacheTicker
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRxContext(f *Interface, q int) *rxContext {
|
|
||||||
return &rxContext{
|
|
||||||
q: q,
|
|
||||||
scratch: make([]byte, mtu),
|
|
||||||
nb: make([]byte, 12, 12),
|
|
||||||
h: &header.H{},
|
|
||||||
fwPacket: &firewall.ParsedPacket{},
|
|
||||||
hostmapCache: map[uint32]*HostInfo{},
|
|
||||||
lhh: f.lightHouse.NewRequestHandler(),
|
|
||||||
ctCache: firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Interface) listenOut(i int) {
|
func (f *Interface) listenOut(i int) {
|
||||||
var li udp.Conn
|
var li udp.Conn
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
@@ -413,20 +316,16 @@ func (f *Interface) listenOut(i int) {
|
|||||||
li = f.outside
|
li = f.outside
|
||||||
}
|
}
|
||||||
|
|
||||||
rxc := newRxContext(f, i)
|
ctCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
|
||||||
|
lhh := f.lightHouse.NewRequestHandler()
|
||||||
|
plaintext := make([]byte, udp.MTU)
|
||||||
|
h := &header.H{}
|
||||||
|
fwPacket := &firewall.Packet{}
|
||||||
|
nb := make([]byte, 12, 12)
|
||||||
|
|
||||||
listener := func(fromUdpAddr netip.AddrPort, payload []byte) {
|
err := li.ListenOut(func(fromUdpAddr netip.AddrPort, payload []byte) {
|
||||||
f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, payload, rxc)
|
f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, plaintext[:0], payload, h, fwPacket, lhh, nb, i, ctCache.Get())
|
||||||
}
|
})
|
||||||
|
|
||||||
flusher := func() {
|
|
||||||
if err := f.batchers[i].Flush(); err != nil {
|
|
||||||
f.l.Error("Failed to flush tun coalescer", "error", err)
|
|
||||||
}
|
|
||||||
clear(rxc.hostmapCache)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := li.ListenOut(listener, flusher)
|
|
||||||
|
|
||||||
// An error after teardown began is shutdown noise, the closed flag covers resources
|
// An error after teardown began is shutdown noise, the closed flag covers resources
|
||||||
// Close releases itself and the cancelled ctx covers ones torn down by their owners
|
// Close releases itself and the cancelled ctx covers ones torn down by their owners
|
||||||
@@ -439,42 +338,16 @@ func (f *Interface) listenOut(i int) {
|
|||||||
f.l.Debug("underlay reader is done", "reader", i)
|
f.l.Debug("underlay reader is done", "reader", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) pinThisThread(i int) {
|
func (f *Interface) listenIn(reader io.ReadWriteCloser, i int) {
|
||||||
var cpu int
|
packet := make([]byte, mtu)
|
||||||
if n := len(f.cpuAffinity); n > 0 {
|
out := make([]byte, mtu)
|
||||||
// Explicit tun.cpu_affinity list wins; parseCpuAffinity already
|
fwPacket := &firewall.Packet{}
|
||||||
// validated the entries against the allowed CPU set.
|
|
||||||
cpu = f.cpuAffinity[i%n]
|
|
||||||
} else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
|
|
||||||
// Default: spread queues across the CPUs we're actually allowed to
|
|
||||||
// run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
|
|
||||||
// i % NumCPU would pick unrunnable IDs and every pin would fail.
|
|
||||||
cpu = allowed[i%len(allowed)]
|
|
||||||
} else {
|
|
||||||
cpu = i % runtime.NumCPU()
|
|
||||||
}
|
|
||||||
if err := util.PinThreadToCPU(cpu); err != nil {
|
|
||||||
f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Interface) listenIn(queue tio.Queue, i int) {
|
|
||||||
// Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
|
|
||||||
// same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
|
|
||||||
if f.pinThreads {
|
|
||||||
f.pinThisThread(i)
|
|
||||||
}
|
|
||||||
|
|
||||||
rejectBuf := make([]byte, mtu)
|
|
||||||
arenaSize := batch.SendBatchCap * (udp.MTU + 32)
|
|
||||||
sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
|
|
||||||
fwPacket := &firewall.ParsedPacket{}
|
|
||||||
nb := make([]byte, 12, 12)
|
nb := make([]byte, 12, 12)
|
||||||
|
|
||||||
conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
|
conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
pkts, err := queue.Read()
|
n, err := reader.Read(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Same shutdown noise handling as listenOut
|
// Same shutdown noise handling as listenOut
|
||||||
if !f.closed.Load() && f.ctx.Err() == nil {
|
if !f.closed.Load() && f.ctx.Err() == nil {
|
||||||
@@ -484,42 +357,18 @@ func (f *Interface) listenIn(queue tio.Queue, i int) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, pkt := range pkts {
|
f.consumeInsidePacket(packet[:n], fwPacket, nb, out, i, conntrackCache.Get())
|
||||||
f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
|
|
||||||
// Flush incrementally once a full sendmmsg batch has
|
|
||||||
// accumulated so the first packets of a deep read drain
|
|
||||||
// hit the wire while the rest are still being encrypted.
|
|
||||||
if sb.Len() >= batch.SendBatchCap {
|
|
||||||
f.flushSendBatch(sb, i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
f.flushSendBatch(sb, i)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
f.l.Debug("overlay reader is done", "reader", i)
|
f.l.Debug("overlay reader is done", "reader", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
// flushSendBatch drains sb to the underlay and accounts for anything it could not deliver. A shortfall means
|
|
||||||
// specific destinations were undeliverable (a stale remote, a reject rule), which the backend logs per peer at
|
|
||||||
// debug; here it is only a counter, so one unreachable peer cannot spam a log line per batch.
|
|
||||||
func (f *Interface) flushSendBatch(sb *batch.SendBatch, q int) {
|
|
||||||
queued := sb.Len()
|
|
||||||
written, err := sb.Flush()
|
|
||||||
if err != nil {
|
|
||||||
f.l.Error("Failed to write outgoing batch", "error", err, "writer", q)
|
|
||||||
}
|
|
||||||
if dropped := queued - written; dropped > 0 {
|
|
||||||
f.metricTxDropped.Inc(int64(dropped))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
|
func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
|
||||||
c.RegisterReloadCallback(f.reloadFirewall)
|
c.RegisterReloadCallback(f.reloadFirewall)
|
||||||
for _, reload := range []func(*config.C){
|
c.RegisterReloadCallback(f.reloadSendRecvError)
|
||||||
f.reloadSendRecvError, f.reloadAcceptRecvError, f.reloadDisconnectInvalid, f.reloadMisc,
|
c.RegisterReloadCallback(f.reloadAcceptRecvError)
|
||||||
} {
|
c.RegisterReloadCallback(f.reloadDisconnectInvalid)
|
||||||
c.RegisterReloadCallback(func(c *config.C, _ *config.Reload) { reload(c) })
|
c.RegisterReloadCallback(f.reloadMisc)
|
||||||
}
|
|
||||||
|
|
||||||
for _, udpConn := range f.writers {
|
for _, udpConn := range f.writers {
|
||||||
c.RegisterReloadCallback(udpConn.ReloadConfig)
|
c.RegisterReloadCallback(udpConn.ReloadConfig)
|
||||||
@@ -536,19 +385,18 @@ func (f *Interface) reloadDisconnectInvalid(c *config.C) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
func (f *Interface) reloadFirewall(c *config.C) {
|
||||||
cs := f.pki.getCertState()
|
cs := f.pki.getCertState()
|
||||||
curCert := cs.getCertificate(cert.Version2)
|
curCert := cs.getCertificate(cert.Version2)
|
||||||
if curCert == nil {
|
if curCert == nil {
|
||||||
curCert = cs.getCertificate(cert.Version1)
|
curCert = cs.getCertificate(cert.Version1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compare with what the running firewall was built from, not the last config, so a firewall that failed to build
|
// The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
|
||||||
// is tried again. The cert is the one this reload brought, PKI registers its reload callback before this one
|
// Check to see if that set has changed, and if so, rebuild the firewall.
|
||||||
src := c.Render("firewall")
|
certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
|
||||||
if src != "" && src == f.firewall.source && curCert != nil &&
|
|
||||||
slices.Equal(curCert.Networks(), f.firewall.assignedNetworks) &&
|
if !c.HasChanged("firewall") && !certUnsafeChanged {
|
||||||
slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks) {
|
|
||||||
f.l.Debug("No firewall config change detected")
|
f.l.Debug("No firewall config change detected")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -556,7 +404,6 @@ func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
|||||||
fw, err := NewFirewallFromConfig(f.l, cs, c)
|
fw, err := NewFirewallFromConfig(f.l, cs, c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
f.l.Error("Error while creating firewall during reload", "error", err)
|
f.l.Error("Error while creating firewall during reload", "error", err)
|
||||||
r.Failed()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -654,15 +501,17 @@ func (f *Interface) reloadMisc(c *config.C) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// statsEmitter updates the interface's gauges, the stats server runs it on its capture loop.
|
func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
|
||||||
func (f *Interface) statsEmitter() func() {
|
ticker := time.NewTicker(i)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
udpStats := udp.NewUDPStatsEmitter(f.writers)
|
udpStats := udp.NewUDPStatsEmitter(f.writers)
|
||||||
|
|
||||||
certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
|
certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
|
||||||
certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
|
certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
|
||||||
certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
|
certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
|
||||||
|
|
||||||
return func() {
|
emit := func() {
|
||||||
f.firewall.EmitStats()
|
f.firewall.EmitStats()
|
||||||
f.handshakeManager.EmitStats()
|
f.handshakeManager.EmitStats()
|
||||||
udpStats()
|
udpStats()
|
||||||
@@ -679,6 +528,19 @@ func (f *Interface) statsEmitter() func() {
|
|||||||
certMaxVersion.Update(int64(certState.v1Cert.Version()))
|
certMaxVersion.Update(int64(certState.v1Cert.Version()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prime gauges so a Prometheus scrape that lands before the first tick
|
||||||
|
// sees real values instead of the zero defaults (issue #907).
|
||||||
|
emit()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
emit()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
|
func (f *Interface) GetHostInfo(vpnIp netip.Addr) *HostInfo {
|
||||||
@@ -689,14 +551,6 @@ func (f *Interface) GetCertState() *CertState {
|
|||||||
return f.pki.getCertState()
|
return f.pki.getCertState()
|
||||||
}
|
}
|
||||||
|
|
||||||
// shutdowner is a udp.Conn or overlay.Device whose readers can be woken without releasing their fds
|
|
||||||
type shutdowner interface {
|
|
||||||
Shutdown() error
|
|
||||||
}
|
|
||||||
|
|
||||||
// readerShutdownTimeout bounds how long Close waits on woken readers before releasing their fds anyway
|
|
||||||
const readerShutdownTimeout = 5 * time.Second
|
|
||||||
|
|
||||||
// Close releases the interface's resources: the udp sockets and the tun device.
|
// Close releases the interface's resources: the udp sockets and the tun device.
|
||||||
// It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
|
// It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
|
||||||
// calls after the first return nil without doing anything.
|
// calls after the first return nil without doing anything.
|
||||||
@@ -706,55 +560,20 @@ func (f *Interface) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var errs []error
|
var errs []error
|
||||||
closeUdp := func(i int, u udp.Conn) {
|
|
||||||
if err := u.Close(); err != nil {
|
// Release the udp readers
|
||||||
|
for i, u := range f.writers {
|
||||||
|
err := u.Close()
|
||||||
|
if err != nil {
|
||||||
f.l.Error("Error while closing udp socket", "error", err, "writer", i)
|
f.l.Error("Error while closing udp socket", "error", err, "writer", i)
|
||||||
errs = append(errs, err)
|
errs = append(errs, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
closeTun := func() {
|
|
||||||
if err := f.inside.Close(); err != nil {
|
|
||||||
errs = append(errs, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wake every reader before releasing any fd, one that loops back into a syscall on a reused fd number never wakes.
|
// Release the tun device (closing the tun also closes all readers)
|
||||||
// Anything without Shutdown is closed right away, as before.
|
closeErr := f.inside.Close()
|
||||||
var deferred []func()
|
if closeErr != nil {
|
||||||
for i, u := range f.writers {
|
errs = append(errs, closeErr)
|
||||||
if s, ok := u.(shutdowner); ok {
|
|
||||||
if err := s.Shutdown(); err != nil {
|
|
||||||
f.l.Error("Error while shutting down udp socket", "error", err, "writer", i)
|
|
||||||
errs = append(errs, err)
|
|
||||||
}
|
|
||||||
deferred = append(deferred, func() { closeUdp(i, u) })
|
|
||||||
} else {
|
|
||||||
closeUdp(i, u)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if s, ok := f.inside.(shutdowner); ok {
|
|
||||||
if err := s.Shutdown(); err != nil {
|
|
||||||
errs = append(errs, err)
|
|
||||||
}
|
|
||||||
deferred = append(deferred, closeTun)
|
|
||||||
} else {
|
|
||||||
closeTun()
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(deferred) > 0 {
|
|
||||||
readersDone := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
f.readers.Wait()
|
|
||||||
close(readersDone)
|
|
||||||
}()
|
|
||||||
select {
|
|
||||||
case <-readersDone:
|
|
||||||
case <-time.After(readerShutdownTimeout):
|
|
||||||
f.l.Warn("Readers did not stop, closing their fds anyway", "timeout", readerShutdownTimeout)
|
|
||||||
}
|
|
||||||
for _, closeFn := range deferred {
|
|
||||||
closeFn()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Release the construction token so waiters know the resources are gone
|
// Release the construction token so waiters know the resources are gone
|
||||||
|
|||||||
+14
-5
@@ -3,6 +3,7 @@
|
|||||||
package nebula
|
package nebula
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -17,8 +18,11 @@ import (
|
|||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Priming before the first tick (issue #907) is Start's job, see TestStatsServer_Start_primes.
|
// Test_emitStats_primesGauges covers issue #907: a Prometheus scrape that
|
||||||
func Test_statsEmitter_setsGauges(t *testing.T) {
|
// landed before the first ticker fire used to read 0 for the cert gauges.
|
||||||
|
// emitStats now primes the gauges before entering the ticker loop. We assert
|
||||||
|
// the gauge is zero before the first call and non-zero after.
|
||||||
|
func Test_emitStats_primesGauges(t *testing.T) {
|
||||||
defer metrics.DefaultRegistry.UnregisterAll()
|
defer metrics.DefaultRegistry.UnregisterAll()
|
||||||
|
|
||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
@@ -52,12 +56,17 @@ func Test_statsEmitter_setsGauges(t *testing.T) {
|
|||||||
ifce.pki.cs.Store(cs)
|
ifce.pki.cs.Store(cs)
|
||||||
|
|
||||||
ttlGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
|
ttlGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
|
||||||
require.Zero(t, ttlGauge.Value(), "gauge should be zero before the emitter runs")
|
require.Zero(t, ttlGauge.Value(), "gauge should be zero before emitStats runs")
|
||||||
|
|
||||||
ifce.statsEmitter()()
|
// Pre-cancel the context so emitStats returns after priming the gauges
|
||||||
|
// without ever reading from ticker.C. The one hour interval is just a
|
||||||
|
// belt-and-suspenders, the test does not expect the ticker to fire.
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
ifce.emitStats(ctx, time.Hour)
|
||||||
|
|
||||||
ttl := ttlGauge.Value()
|
ttl := ttlGauge.Value()
|
||||||
assert.Positive(t, ttl, "ttl gauge should be set by one run of the emitter")
|
assert.Positive(t, ttl, "ttl gauge should be primed by emitStats before its first tick")
|
||||||
assert.LessOrEqual(t, ttl, int64(3600))
|
assert.LessOrEqual(t, ttl, int64(3600))
|
||||||
assert.Equal(t, int64(cert.Version1), metrics.GetOrRegisterGauge("certificate.initiating_version", nil).Value())
|
assert.Equal(t, int64(cert.Version1), metrics.GetOrRegisterGauge("certificate.initiating_version", nil).Value())
|
||||||
assert.Equal(t, int64(cert.Version1), metrics.GetOrRegisterGauge("certificate.max_version", nil).Value())
|
assert.Equal(t, int64(cert.Version1), metrics.GetOrRegisterGauge("certificate.max_version", nil).Value())
|
||||||
|
|||||||
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user