mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 11:56:52 +01:00
Compare commits
81
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
357b129749 | ||
|
|
8a4bd8b10f | ||
|
|
b426843f88 | ||
|
|
cda3710d5a | ||
|
|
c26871fe08 | ||
|
|
7daacc6a48 | ||
|
|
428dad94b3 | ||
|
|
5bf666dd90 | ||
|
|
49207da077 | ||
|
|
bbc49669b7 | ||
|
|
915495d5f4 | ||
|
|
a203d044bb | ||
|
|
316bf87780 | ||
|
|
1a0ac25db0 | ||
|
|
42597dda7d | ||
|
|
afbdc87ed9 | ||
|
|
94372f4f51 | ||
|
|
42280f04ce | ||
|
|
11c1917387 | ||
|
|
5ba7aff4b3 | ||
|
|
8a2de9b1b5 | ||
|
|
a8c52f5c13 | ||
|
|
13af8dd6f3 | ||
|
|
5bb0622192 | ||
|
|
f3705cbb67 | ||
|
|
94be454f4f | ||
|
|
5f26c1a7e5 | ||
|
|
d47c8c71f1 | ||
|
|
f57539a163 | ||
|
|
8d8ae0f744 | ||
|
|
f9b0853476 | ||
|
|
d5062dacf0 | ||
|
|
7cfa47d569 | ||
|
|
e20569ce51 | ||
|
|
9651ffdb0d | ||
|
|
3a45c01656 | ||
|
|
019cc46a7f | ||
|
|
cf3f315cd3 | ||
|
|
3fc627e08d | ||
|
|
abff1a4555 | ||
|
|
227134a1d5 | ||
|
|
232bacfdd0 | ||
|
|
4e1ef9cd73 | ||
|
|
614e0ea3aa | ||
|
|
2999fc0b6a | ||
|
|
f474b534e1 | ||
|
|
0dc8a28d1f | ||
|
|
89178f45ba | ||
|
|
6a72e1c304 | ||
|
|
e50f8128f4 | ||
|
|
dd8f660c0a | ||
|
|
ec3304e3a9 | ||
|
|
aaa2ff7fff | ||
|
|
657f6ad044 | ||
|
|
19e04db115 | ||
|
|
9c5d701648 | ||
|
|
edc3c5e018 | ||
|
|
b8b159a486 | ||
|
|
49e35d1283 | ||
|
|
6fcb926334 | ||
|
|
28d82f7b8a | ||
|
|
f15d10fc54 | ||
|
|
bfe7790848 | ||
|
|
e7b4e094b9 | ||
|
|
6740518403 | ||
|
|
5cbf029d06 | ||
|
|
368855c2e8 | ||
|
|
6d124d0441 | ||
|
|
72bf111209 | ||
|
|
1617897043 | ||
|
|
f8775bb6ca | ||
|
|
15f0f0d5d0 | ||
|
|
7902ce674e | ||
|
|
c2fbe215e6 | ||
|
|
94ac6db4ca | ||
|
|
a60350e34e | ||
|
|
58f3b6fda7 | ||
|
|
a99699e370 | ||
|
|
3615a79b8b | ||
|
|
147c202c27 | ||
|
|
e290a6892f |
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
# Goldens are compared byte for byte, so they must come out of git the way they went in.
|
||||||
|
*.golden -text
|
||||||
@@ -43,8 +43,15 @@ runs:
|
|||||||
with:
|
with:
|
||||||
role-to-assume: ${{ inputs.role }}
|
role-to-assume: ${{ inputs.role }}
|
||||||
aws-region: ${{ inputs.region }}
|
aws-region: ${{ inputs.region }}
|
||||||
# Default is 12 retries to ride out IAM trust-policy propagation; once
|
# An STS secret key with special characters does not survive the
|
||||||
# the role is stable we want a real misconfiguration to fail fast.
|
# pwsh -> make -> MSYS sh -> aws.exe chain, and SigV4 then signs with a
|
||||||
|
# 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
|
||||||
|
|||||||
Executable
+142
@@ -0,0 +1,142 @@
|
|||||||
|
#!/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 -
|
||||||
@@ -12,9 +12,9 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
@@ -38,9 +38,9 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
@@ -73,27 +73,81 @@ jobs:
|
|||||||
build-darwin:
|
build-darwin:
|
||||||
name: Build Universal Darwin
|
name: Build Universal Darwin
|
||||||
env:
|
env:
|
||||||
HAS_SIGNING_CREDS: ${{ secrets.AC_USERNAME != '' }}
|
HAS_SIGNING_CREDS: ${{ secrets.APPLE_SIGNING_ROLE_ARN != '' }}
|
||||||
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@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
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: ${{ secrets.APPLE_DEVELOPER_CERTIFICATE_P12_BASE64 }}
|
p12-file-base64: ${{ env.SIGNING_P12_BASE64 }}
|
||||||
p12-password: ${{ secrets.APPLE_DEVELOPER_CERTIFICATE_PASSWORD }}
|
p12-password: ${{ env.SIGNING_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
|
||||||
@@ -102,17 +156,34 @@ 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
|
||||||
|
|
||||||
if [ -n "$AC_USERNAME" ]; then
|
# Unset in a fork, which has no credentials to sign with
|
||||||
codesign -s "10BC1FDDEB6CE753550156C0669109FAC49E4D1E" -f -v --timestamp --options=runtime -i "net.defined.nebula" ./release/nebula
|
if [ -n "$SIGNING_IDENTITY_SHA1" ]; then
|
||||||
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" ./release/nebula
|
||||||
|
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 "$AC_USERNAME" ]; then
|
if [ -n "$ASC_P8" ]; then
|
||||||
xcrun notarytool submit ./release/nebula-darwin.zip --team-id "576H3XS7FP" --apple-id "$AC_USERNAME" --password "$AC_PASSWORD" --wait
|
xcrun notarytool submit ./release/nebula-darwin.zip --key "$ASC_P8" --key-id "$ASC_KEY_ID" --issuer "$ASC_ISSUER_ID" --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:
|
||||||
|
|||||||
@@ -32,9 +32,9 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: add hashicorp source
|
- name: add hashicorp source
|
||||||
@@ -64,9 +64,9 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: add hashicorp source
|
- name: add hashicorp source
|
||||||
@@ -90,15 +90,15 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
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@v3
|
- uses: Vampire/setup-wsl@v7
|
||||||
with:
|
with:
|
||||||
distribution: Ubuntu-24.04
|
distribution: Ubuntu-24.04
|
||||||
additional-packages: iputils-ping iproute2
|
additional-packages: iputils-ping iproute2
|
||||||
|
|||||||
+34
-33
@@ -20,44 +20,45 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
|
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-docker CGO_ENABLED=1 BUILD_ARGS=-race
|
run: make bin
|
||||||
|
|
||||||
- name: setup docker image
|
- name: run smoke-self
|
||||||
working-directory: ./.github/workflows/smoke
|
working-directory: ./.github/workflows/smoke
|
||||||
run: ./build.sh
|
run: ./smoke-self.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
|
||||||
Executable
+130
@@ -0,0 +1,130 @@
|
|||||||
|
#!/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,15 +51,19 @@ 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" -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,$Ip6_1/64" -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" -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,$Ip6_2/64" -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.
|
||||||
@@ -82,7 +86,7 @@ tun:
|
|||||||
drop_local_broadcast: false
|
drop_local_broadcast: false
|
||||||
drop_multicast: false
|
drop_multicast: false
|
||||||
tx_queue: 500
|
tx_queue: 500
|
||||||
mtu: 1300
|
mtu: $Mtu
|
||||||
network_category: private
|
network_category: private
|
||||||
logging:
|
logging:
|
||||||
level: info
|
level: info
|
||||||
@@ -126,7 +130,7 @@ tun:
|
|||||||
drop_local_broadcast: false
|
drop_local_broadcast: false
|
||||||
drop_multicast: false
|
drop_multicast: false
|
||||||
tx_queue: 500
|
tx_queue: 500
|
||||||
mtu: 1300
|
mtu: $Mtu
|
||||||
logging:
|
logging:
|
||||||
level: info
|
level: info
|
||||||
format: text
|
format: text
|
||||||
@@ -169,7 +173,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; 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; { 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"
|
||||||
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
|
||||||
@@ -214,6 +218,16 @@ 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"
|
||||||
@@ -221,6 +235,13 @@ 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"
|
||||||
@@ -234,6 +255,28 @@ 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.'
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-10
@@ -20,9 +20,9 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
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.5
|
version: v2.14
|
||||||
|
|
||||||
test:
|
test:
|
||||||
name: Test ${{ matrix.name }}
|
name: Test ${{ matrix.name }}
|
||||||
@@ -58,9 +58,14 @@ jobs:
|
|||||||
e2e-cmd: make e2evv
|
e2e-cmd: make e2evv
|
||||||
- name: linux-boringcrypto
|
- name: linux-boringcrypto
|
||||||
os: ubuntu-latest
|
os: ubuntu-latest
|
||||||
build-cmd: make bin-boringcrypto
|
build-cmd: make boringcrypto
|
||||||
test-cmd: make test-boringcrypto
|
test-cmd: make boringcrypto test
|
||||||
e2e-cmd: make e2e GOEXPERIMENT=boringcrypto CGO_ENABLED=1 TEST_ENV="TEST_LOGS=1" TEST_FLAGS="-v -ldflags -checklinkname=0"
|
e2e-cmd: make boringcrypto e2evv
|
||||||
|
- 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
|
||||||
@@ -80,9 +85,9 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
@@ -125,9 +130,9 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- uses: actions/setup-go@v6
|
- uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version: '1.25'
|
go-version: '1.27'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Build ${{ matrix.name }}
|
- name: Build ${{ matrix.name }}
|
||||||
|
|||||||
+124
-1
@@ -7,6 +7,127 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|
||||||
|
- 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
|
||||||
|
|
||||||
|
See the [v1.11.0](https://github.com/slackhq/nebula/milestone/25?closed=1) milestone for a complete list of changes.
|
||||||
|
|
||||||
|
### Breaking
|
||||||
|
|
||||||
|
- Logging has switched from logrus to Go's structured `slog`. Log output changes: levels are upper case
|
||||||
|
(`level=INFO`), trace prints as `level=DEBUG-4`, timestamps are always RFC3339Nano and `logging.timestamp_format`
|
||||||
|
is ignored, and some messages were reworded. Review any log parsing before upgrading. This is also an API break
|
||||||
|
for embedders, as constructors now take a `*slog.Logger`. (#1672, #1734, #1621)
|
||||||
|
- `firewall.inbound_action` and `firewall.outbound_action` (used to set reject vs. drop policy) were each being
|
||||||
|
applied to the opposite direction, that is now corrected. This only affects how blocked packets are answered, not
|
||||||
|
which packets the firewall allows or denies. If you set either of these you are getting the behavior of the other
|
||||||
|
one today and likely want to swap them before upgrading. (#1798)
|
||||||
|
- On Windows, Nebula now installs WFP PERMIT filters for the nebula adapter and the listener port by default. WFP
|
||||||
|
sits below Windows Defender Firewall, so any WDF inbound rules you rely on for either will no longer apply. Set
|
||||||
|
`tun.windows_bypass_wdf` and `listen.windows_bypass_wdf` to false to leave WDF in charge. (#1710)
|
||||||
|
- On Windows, the nebula device is now set to the `private` network category instead of whatever Windows decided,
|
||||||
|
which is usually `Public`. This makes the host firewall less restrictive on the overlay. Set
|
||||||
|
`tun.network_category` to `unset` to keep the old behavior. (#1710)
|
||||||
|
- Reject packets for non-TCP now use ICMP code 13, communication administratively prohibited, instead of code 3,
|
||||||
|
port unreachable. Anything keying off the old code needs updating. (#1766, #1768)
|
||||||
|
- The SSH debug server's profiling commands are now confined to `sshd.sandbox_dir`, which defaults to
|
||||||
|
`$TMP/nebula-debug`. Relative paths resolve inside it and absolute paths outside it are rejected, so anything
|
||||||
|
scripting `start-cpu-profile`, `save-heap-profile`, or `save-mutex-profile` with a path elsewhere needs the
|
||||||
|
directory set. The directory is not created for you. (#1622)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Sign the Windows release binaries. (#1718)
|
||||||
|
- Generate IPv6 reject packets, matching the existing IPv4 behavior. (#1766, #1767, #1768)
|
||||||
|
- Accept `-` in `nebula-cert` to read from stdin or write to stdout. (#1714)
|
||||||
|
- Search for both `config.yml` and `config.yaml` in service and command line modes. (#1717)
|
||||||
|
- Add version labels to the Docker/OCI images. (#1772)
|
||||||
|
- Rebind the listener and re-query lighthouses on macOS when the underlay network changes, so devices moving
|
||||||
|
between wifi and wired or between networks recover without waiting for dead tunnel detection. Controlled by
|
||||||
|
`listen.rebind_on_network_change` (default `true`, not reloadable). (#1816)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Reload the firewall when the unsafe networks in the certificate change. (#1719)
|
||||||
|
- Reconfigure, start, and stop the stats listener on a config reload instead of requiring a restart. (#1670)
|
||||||
|
- Update a static host's addresses when they change on reload. (#1713)
|
||||||
|
- Don't require a port on ICMP firewall rules. (#1609)
|
||||||
|
- Connection track ICMP traffic. (#1602)
|
||||||
|
- Return `NODATA` instead of `NXDOMAIN` from the DNS server for a name that exists but has no record of the
|
||||||
|
requested type, so clients that query `AAAA` first (busybox/Alpine) fall through to `A`. (#1668)
|
||||||
|
- Record the local host's details in the DNS server. (#1716)
|
||||||
|
- Install Windows unsafe routes as link routes. (#1709)
|
||||||
|
- Reduce relay handshake log spam, and only log a handshake send error at error level when the remote list
|
||||||
|
changes. (#1733, #1765, #1810)
|
||||||
|
- Start, stop, and reload subsystems (DNS, stats, conntrack, ssh, punchy) cleanly without leaking goroutines. (#1640, #1654, #1661, #1667, #1669, #1708, #1806, #1815)
|
||||||
|
- `Control` is now safe to stop and wait on from any lifecycle state, and a new `Control.Wait` blocks until nebula
|
||||||
|
has fully stopped and returns the first fatal reader error. Failed starts release the udp sockets and tun fd
|
||||||
|
instead of leaking them. (#1794)
|
||||||
|
- Trigger an immediate lighthouse update when reconnecting to or adding a lighthouse instead of waiting for the next update tick. (#1645)
|
||||||
|
- Bring the Darwin and OpenBSD tun implementations in line with the other BSDs. (#1703)
|
||||||
|
- Update to build against go v1.26. (#1818)
|
||||||
|
- Various dependency updates. (#1586, #1587, #1604, #1617, #1618, #1627, #1628, #1629, #1652, #1664, #1665, #1697, #1721, #1732, #1742, #1743, #1750, #1763, #1771, #1782, #1800, #1807)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fix a data race on a host's remote address that could send packets to the wrong address during a roam. (#1773)
|
||||||
|
- Fix tunnels that could permanently escape connection manager monitoring. (#1752)
|
||||||
|
- Fix a crash when reloading the SSH server's trusted keys. (#1787)
|
||||||
|
- Fix hostmap corruption when a host has multiple overlay addresses. Each address now gets its own list instead of
|
||||||
|
a single shared chain, which also fixes two latent bugs on the add and makePrimary paths. (#1788, #1790)
|
||||||
|
- Apply `remote_allow_list` IPv4 rules to 4-in-6 mapped addresses. (#1786)
|
||||||
|
- Don't panic in the DNS server on a short or empty query name. (#1635)
|
||||||
|
- Advance the replay window on relayed packets so a relay drops replayed frames instead of re-forwarding them. (#1751)
|
||||||
|
- Fix a race in relay state handling. (#1753)
|
||||||
|
- Lock replay window updates so concurrent readers can't corrupt it. (#1802)
|
||||||
|
- Reject malformed handshakes more reliably, including invalid ed25519 key lengths. (#1601, #1756)
|
||||||
|
- Properly handle `closetunnel` packets. (#1638)
|
||||||
|
- Fix an IPv6 extension-header length overflow that could make the firewall parse the wrong protocol and ports. (#1789)
|
||||||
|
- Fix relay re-establishment when a handshake arrives over a relay entry that a one-sided teardown left
|
||||||
|
`Disestablished`, which silently dropped every send until dead tunnel detection forced a re-handshake. (#1805)
|
||||||
|
- Don't build new relay state on a tunnel that was just discarded. (#1796)
|
||||||
|
- Don't delete the wrong pending hostinfo in the handshake manager. (#1811)
|
||||||
|
- Don't call the packet reader after a UDP error on Darwin. (#1755)
|
||||||
|
- Open the FreeBSD tun device non blocking. (#1666)
|
||||||
|
|
||||||
## [1.10.3] - 2026-02-06
|
## [1.10.3] - 2026-02-06
|
||||||
|
|
||||||
### Security
|
### Security
|
||||||
@@ -788,7 +909,9 @@ created.)
|
|||||||
|
|
||||||
- Initial public release.
|
- Initial public release.
|
||||||
|
|
||||||
[Unreleased]: https://github.com/slackhq/nebula/compare/v1.10.3...HEAD
|
[Unreleased]: https://github.com/slackhq/nebula/compare/v1.11.1...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,6 +72,17 @@ 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
|
||||||
|
|
||||||
@@ -137,6 +148,8 @@ 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
|
||||||
@@ -157,6 +170,9 @@ 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
|
||||||
@@ -166,12 +182,12 @@ debug: BUILD_ARGS += -tags debug
|
|||||||
debug: bin
|
debug: bin
|
||||||
|
|
||||||
bin:
|
bin:
|
||||||
go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula${NEBULA_CMD_SUFFIX} ${NEBULA_CMD_PATH}
|
$(GOENV) go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula${NEBULA_CMD_SUFFIX} ${NEBULA_CMD_PATH}
|
||||||
go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula-cert${NEBULA_CMD_SUFFIX} ./cmd/nebula-cert
|
$(GOENV) go build $(BUILD_ARGS) -ldflags "$(LDFLAGS)" -o ./nebula-cert${NEBULA_CMD_SUFFIX} ./cmd/nebula-cert
|
||||||
|
|
||||||
install:
|
install:
|
||||||
go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ${NEBULA_CMD_PATH}
|
$(GOENV) go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ${NEBULA_CMD_PATH}
|
||||||
go install $(BUILD_ARGS) -ldflags "$(LDFLAGS)" ./cmd/nebula-cert
|
$(GOENV) 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 -, ,$*))
|
||||||
@@ -182,8 +198,11 @@ 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
|
|
||||||
build/linux-arm64-boringcrypto/%: LDFLAGS += -checklinkname=0
|
# fips140
|
||||||
|
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 -, , $*)) \
|
||||||
@@ -214,10 +233,7 @@ vet:
|
|||||||
go vet $(VET_FLAGS) -v ./...
|
go vet $(VET_FLAGS) -v ./...
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -v ./...
|
$(TEST_ENV) go test $(TEST_FLAGS) -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 ./...
|
||||||
@@ -226,11 +242,14 @@ 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=.
|
||||||
@@ -260,29 +279,75 @@ 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
|
||||||
cd .github/workflows/smoke/ && ./build.sh
|
# This is so we can limit `fips140` smoke test to just P256 curve.
|
||||||
cd .github/workflows/smoke/ && ./smoke.sh
|
if [ "$(CURVE)" != "P256" ]; then cd .github/workflows/smoke/ && $(GOENV) ./build.sh; fi
|
||||||
cd .github/workflows/smoke/ && NAME="smoke-p256" CURVE="P256" ./build.sh
|
if [ "$(CURVE)" != "P256" ]; then cd .github/workflows/smoke/ && $(GOENV) ./smoke.sh; fi
|
||||||
cd .github/workflows/smoke/ && NAME="smoke-p256" ./smoke.sh
|
cd .github/workflows/smoke/ && $(GOENV) NAME="smoke-p256" CURVE="P256" ./build.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/ && ./build-relay.sh
|
cd .github/workflows/smoke/ && $(GOENV) ./build-relay.sh
|
||||||
cd .github/workflows/smoke/ && ./smoke-relay.sh
|
cd .github/workflows/smoke/ && $(GOENV) ./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-docker-race: BUILD_ARGS = -race
|
smoke-self: bin
|
||||||
smoke-docker-race: CGO_ENABLED = 1
|
cd .github/workflows/smoke/ && ./smoke-self.sh
|
||||||
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 debug build-test-mobile e2e e2ev e2evv e2evvv e2evvvv proto release service smoke-docker smoke-docker-race test test-cov-html 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 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/%
|
||||||
.DEFAULT_GOAL := bin
|
.DEFAULT_GOAL := bin
|
||||||
@@ -145,17 +145,27 @@ 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 BoringCrypto
|
## Curve P256 and FIPS 140-3 mode
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
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:
|
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).
|
||||||
|
|
||||||
|
```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,13 +79,7 @@ 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 := uint64(64) - bit
|
take := min(min(uint64(64)-bit, remaining), b.length-pos)
|
||||||
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
|
||||||
@@ -189,10 +183,7 @@ 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 := i
|
end := min(i, b.current+b.length)
|
||||||
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
|
||||||
|
|
||||||
|
|||||||
+10
-1
@@ -389,7 +389,16 @@ func (c *certificateV2) fromTBSCertificate(t *TBSCertificate) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *certificateV2) validate() error {
|
func (c *certificateV2) validate() error {
|
||||||
// Empty names are allowed
|
// Mirror the name and group rules in unmarshalDetails so signing fails instead of producing an unparseable certificate
|
||||||
|
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
|
||||||
|
|||||||
+46
-1
@@ -6,6 +6,7 @@ import (
|
|||||||
"crypto/elliptic"
|
"crypto/elliptic"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -120,7 +121,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 := 0; i < 1000; i++ {
|
for i := range 1000 {
|
||||||
if i&1 == 1 {
|
if i&1 == 1 {
|
||||||
tbs.Version = Version1
|
tbs.Version = Version1
|
||||||
} else {
|
} else {
|
||||||
@@ -135,3 +136,47 @@ 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)
|
||||||
|
}
|
||||||
+34
-7
@@ -3,11 +3,14 @@ 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"
|
||||||
@@ -43,7 +46,28 @@ 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")
|
||||||
@@ -55,11 +79,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", 2*1024*1024, "Optional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase")
|
cf.argonMemory = cf.set.Uint("argon-memory", defaultArgonMemory, "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", 1, "Optional: Argon2 iterations 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.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", "25519", "EdDSA/ECDSA Curve (25519, P256)")
|
cf.curve = cf.set.String("curve", defaultCurve(), "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")
|
||||||
@@ -127,7 +151,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.Split(*cf.groups, ",") {
|
for rg := range strings.SplitSeq(*cf.groups, ",") {
|
||||||
g := strings.TrimSpace(rg)
|
g := strings.TrimSpace(rg)
|
||||||
if g != "" {
|
if g != "" {
|
||||||
groups = append(groups, g)
|
groups = append(groups, g)
|
||||||
@@ -147,7 +171,7 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *cf.networks != "" {
|
if *cf.networks != "" {
|
||||||
for _, rs := range strings.Split(*cf.networks, ",") {
|
for rs := range strings.SplitSeq(*cf.networks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -169,7 +193,7 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *cf.unsafeNetworks != "" {
|
if *cf.unsafeNetworks != "" {
|
||||||
for _, rs := range strings.Split(*cf.unsafeNetworks, ",") {
|
for rs := range strings.SplitSeq(*cf.unsafeNetworks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -197,7 +221,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 i := 0; i < 5; i++ {
|
for range 5 {
|
||||||
errOut.Write([]byte("Enter passphrase: "))
|
errOut.Write([]byte("Enter passphrase: "))
|
||||||
passphrase, err = pr.ReadPassword()
|
passphrase, err = pr.ReadPassword()
|
||||||
|
|
||||||
@@ -244,6 +268,9 @@ 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,5 +1,4 @@
|
|||||||
//go:build !windows
|
//go:build !windows
|
||||||
// +build !windows
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@@ -7,7 +6,9 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"errors"
|
"errors"
|
||||||
|
"math/bits"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -22,6 +23,18 @@ 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(
|
||||||
@@ -29,9 +42,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 1)\n"+
|
" \tOptional: Argon2 iterations parameter used for encrypted private key passphrase (default "+defaultArgonIterations+")\n"+
|
||||||
" -argon-memory uint\n"+
|
" -argon-memory uint\n"+
|
||||||
" \tOptional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase (default 2097152)\n"+
|
" \tOptional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase (default "+defaultArgonMemory+")\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"+
|
||||||
@@ -188,10 +201,16 @@ 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(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(2*1024*1024), ned.EncryptionMetadata.Argon2Parameters.Memory)
|
||||||
assert.Equal(t, uint8(4), ned.EncryptionMetadata.Argon2Parameters.Parallelism)
|
|
||||||
assert.Equal(t, uint32(1), ned.EncryptionMetadata.Argon2Parameters.Iterations)
|
assert.Equal(t, uint32(1), ned.EncryptionMetadata.Argon2Parameters.Iterations)
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, uint8(4), ned.EncryptionMetadata.Argon2Parameters.Parallelism)
|
||||||
|
|
||||||
// verify the key is valid and decrypt-able
|
// verify the key is valid and decrypt-able
|
||||||
var curve cert.Curve
|
var curve cert.Curve
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build fips140enforce
|
||||||
|
|
||||||
|
//go:debug fips140=only
|
||||||
|
|
||||||
|
package main
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/fips140"
|
||||||
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -24,7 +26,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", "25519", "ECDH Curve (25519, P256)")
|
cf.curve = cf.set.String("curve", defaultCurve(), "ECDH Curve (25519, P256)")
|
||||||
cf.p11url = p11Flag(cf.set)
|
cf.p11url = p11Flag(cf.set)
|
||||||
return &cf
|
return &cf
|
||||||
}
|
}
|
||||||
@@ -61,6 +63,9 @@ 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,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/ecdh"
|
"crypto/ecdh"
|
||||||
|
"crypto/fips140"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
@@ -145,7 +146,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 i := 0; i < 5; i++ {
|
for range 5 {
|
||||||
errOut.Write([]byte("Enter passphrase: "))
|
errOut.Write([]byte("Enter passphrase: "))
|
||||||
passphrase, err = pr.ReadPassword()
|
passphrase, err = pr.ReadPassword()
|
||||||
|
|
||||||
@@ -202,7 +203,7 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *sf.networks != "" {
|
if *sf.networks != "" {
|
||||||
for _, rs := range strings.Split(*sf.networks, ",") {
|
for rs := range strings.SplitSeq(*sf.networks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -227,7 +228,7 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if *sf.unsafeNetworks != "" {
|
if *sf.unsafeNetworks != "" {
|
||||||
for _, rs := range strings.Split(*sf.unsafeNetworks, ",") {
|
for rs := range strings.SplitSeq(*sf.unsafeNetworks, ",") {
|
||||||
rs := strings.Trim(rs, " ")
|
rs := strings.Trim(rs, " ")
|
||||||
if rs != "" {
|
if rs != "" {
|
||||||
n, err := netip.ParsePrefix(rs)
|
n, err := netip.ParsePrefix(rs)
|
||||||
@@ -246,7 +247,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.Split(*sf.groups, ",") {
|
for rg := range strings.SplitSeq(*sf.groups, ",") {
|
||||||
g := strings.TrimSpace(rg)
|
g := strings.TrimSpace(rg)
|
||||||
if g != "" {
|
if g != "" {
|
||||||
groups = append(groups, g)
|
groups = append(groups, g)
|
||||||
@@ -268,6 +269,10 @@ 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,5 +1,4 @@
|
|||||||
//go:build !windows
|
//go:build !windows
|
||||||
// +build !windows
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build fips140enforce
|
||||||
|
|
||||||
|
//go:debug fips140=only
|
||||||
|
|
||||||
|
package main
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build !windows
|
//go:build !windows
|
||||||
// +build !windows
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
@@ -85,9 +85,10 @@ 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) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
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()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -34,9 +34,10 @@ 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) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
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()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
//go:build linux && !android && !e2e_testing
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula"
|
||||||
|
"github.com/slackhq/nebula/cert"
|
||||||
|
cert_test "github.com/slackhq/nebula/cert_test"
|
||||||
|
"github.com/slackhq/nebula/config"
|
||||||
|
"github.com/slackhq/nebula/test"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestControlStopClosesOnTimer reproduces the dnclient lifecycle: nebula runs as
|
||||||
|
// a library, and on a config update dnclient calls Stop() in-process to tear the
|
||||||
|
// old instance down before starting a new one. This boots a real nebula (real
|
||||||
|
// blocking UDP sockets, tun disabled), lets it run, then Stop()s it on a timer
|
||||||
|
// and asserts it actually closes. If the reader goroutines parked in recvmmsg
|
||||||
|
// don't wake on Close(), Wait() blocks forever and this fails with a goroutine
|
||||||
|
// dump instead of relying on a process signal to unstick them.
|
||||||
|
func TestControlStopClosesOnTimer(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
|
before := time.Now().Add(-time.Hour)
|
||||||
|
after := time.Now().Add(time.Hour)
|
||||||
|
ca, _, caKey, caPEM := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, before, after, nil, nil, nil)
|
||||||
|
networks := []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}
|
||||||
|
_, _, keyPEM, certPEM := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "close-on-timer", before, after, networks, nil, nil)
|
||||||
|
|
||||||
|
caPath := filepath.Join(dir, "ca.pem")
|
||||||
|
certPath := filepath.Join(dir, "cert.pem")
|
||||||
|
keyPath := filepath.Join(dir, "key.pem")
|
||||||
|
require.NoError(t, os.WriteFile(caPath, caPEM, 0o600))
|
||||||
|
require.NoError(t, os.WriteFile(certPath, certPEM, 0o600))
|
||||||
|
require.NoError(t, os.WriteFile(keyPath, keyPEM, 0o600))
|
||||||
|
|
||||||
|
// tun disabled so no device/root is needed; routines: 2 so we exercise the
|
||||||
|
// multi-socket (SO_REUSEPORT) teardown, which is where dnclient runs.
|
||||||
|
configBody := fmt.Sprintf(`
|
||||||
|
pki:
|
||||||
|
ca: %s
|
||||||
|
cert: %s
|
||||||
|
key: %s
|
||||||
|
listen:
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 0
|
||||||
|
tun:
|
||||||
|
disabled: true
|
||||||
|
firewall:
|
||||||
|
outbound:
|
||||||
|
- port: any
|
||||||
|
proto: any
|
||||||
|
host: any
|
||||||
|
inbound:
|
||||||
|
- port: any
|
||||||
|
proto: any
|
||||||
|
host: any
|
||||||
|
routines: 2
|
||||||
|
`, caPath, certPath, keyPath)
|
||||||
|
require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yml"), []byte(configBody), 0o600))
|
||||||
|
|
||||||
|
c := config.NewC(l)
|
||||||
|
require.NoError(t, c.Load(dir))
|
||||||
|
|
||||||
|
ctrl, err := nebula.Main(c, false, "close-on-timer", l, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, ctrl.Start())
|
||||||
|
|
||||||
|
// Run like a live nebula, then close on a timer, exactly as dnclient does.
|
||||||
|
<-time.NewTimer(5 * time.Second).C
|
||||||
|
|
||||||
|
stopped := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
ctrl.Stop() // closes the udp sockets (shutdown(2)) and the tun
|
||||||
|
ctrl.Wait() // blocks until every reader goroutine has returned
|
||||||
|
close(stopped)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-stopped:
|
||||||
|
t.Log("nebula closed cleanly on timer")
|
||||||
|
case <-time.After(10 * time.Second):
|
||||||
|
buf := make([]byte, 1<<20)
|
||||||
|
n := runtime.Stack(buf, true)
|
||||||
|
t.Fatalf("nebula did NOT close within 10s of Stop(): a blocking reader never woke\n%s", buf[:n])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build fips140enforce
|
||||||
|
|
||||||
|
//go:debug fips140=only
|
||||||
|
|
||||||
|
package main
|
||||||
+2
-1
@@ -71,9 +71,10 @@ 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) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
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()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build !linux
|
//go:build !linux
|
||||||
// +build !linux
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
+710
@@ -0,0 +1,710 @@
|
|||||||
|
package nebula
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"maps"
|
||||||
|
"net/netip"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/commands"
|
||||||
|
"github.com/slackhq/nebula/config"
|
||||||
|
"github.com/slackhq/nebula/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The commands nebula serves. attachCommands builds the one registry every surface
|
||||||
|
// reads. See the commands package for what a Command is.
|
||||||
|
|
||||||
|
type listHostMapFlags struct {
|
||||||
|
Json bool
|
||||||
|
Pretty bool
|
||||||
|
ByIndex bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// listHostMapFlagSet is the flag set list-hostmap and list-pending-hostmap share.
|
||||||
|
func listHostMapFlagSet() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := listHostMapFlags{}
|
||||||
|
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||||
|
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||||
|
fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
|
||||||
|
return fl, &s
|
||||||
|
}
|
||||||
|
|
||||||
|
type printCertFlags struct {
|
||||||
|
Json bool
|
||||||
|
Pretty bool
|
||||||
|
Raw bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type printTunnelFlags struct {
|
||||||
|
Pretty bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type changeRemoteFlags struct {
|
||||||
|
Address string
|
||||||
|
}
|
||||||
|
|
||||||
|
type closeTunnelFlags struct {
|
||||||
|
LocalOnly bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type createTunnelFlags struct {
|
||||||
|
Address string
|
||||||
|
}
|
||||||
|
|
||||||
|
type deviceInfoFlags struct {
|
||||||
|
Json bool
|
||||||
|
Pretty bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachCommands(l *slog.Logger, c *config.C, reg *commands.Registry, f *Interface) {
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.ListHostmap,
|
||||||
|
ShortDescription: "List all known previously connected hosts",
|
||||||
|
Flags: listHostMapFlagSet,
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return listHostMapCommand(f.hostMap, fs, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.ListPendingHostmap,
|
||||||
|
ShortDescription: "List all handshaking hosts",
|
||||||
|
Flags: listHostMapFlagSet,
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return listHostMapCommand(f.handshakeManager, fs, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.ListLighthouseAddrmap,
|
||||||
|
ShortDescription: "List all lighthouse map entries",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := listHostMapFlags{}
|
||||||
|
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||||
|
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return listLighthouseAddrmapCommand(f.lightHouse, fs, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.Reload,
|
||||||
|
ShortDescription: "Reloads configuration from disk, same as sending HUP to the process",
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return reloadCommand(l, c, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.LogLevel,
|
||||||
|
ShortDescription: "Gets or sets the current log level",
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return logLevelCommand(l, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.LogFormat,
|
||||||
|
ShortDescription: "Gets or sets the current log format",
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return logFormatCommand(l, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.Version,
|
||||||
|
ShortDescription: "Prints the currently running version of nebula",
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return versionCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.DeviceInfo,
|
||||||
|
ShortDescription: "Prints information about the network device.",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := deviceInfoFlags{}
|
||||||
|
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||||
|
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return deviceInfoCommand(f, fs, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.PrintCert,
|
||||||
|
ShortDescription: "Prints the current certificate being used or the certificate for the provided vpn addr",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := printCertFlags{}
|
||||||
|
fl.BoolVar(&s.Json, "json", false, "outputs as json")
|
||||||
|
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||||
|
fl.BoolVar(&s.Raw, "raw", false, "raw prints the PEM encoded certificate, not compatible with -json or -pretty")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return printCertCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.PrintTunnel,
|
||||||
|
ShortDescription: "Prints json details about a tunnel for the provided vpn addr",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := printTunnelFlags{}
|
||||||
|
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return printTunnelCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.PrintRelays,
|
||||||
|
ShortDescription: "Prints json details about all relay info",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := printTunnelFlags{}
|
||||||
|
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return printRelaysCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.ChangeRemote,
|
||||||
|
ShortDescription: "Changes the remote address used in the tunnel for the provided vpn addr",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := changeRemoteFlags{}
|
||||||
|
fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return changeRemoteCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&commands.Command{
|
||||||
|
Name: commands.CloseTunnel,
|
||||||
|
ShortDescription: "Closes a tunnel for the provided vpn addr",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := closeTunnelFlags{}
|
||||||
|
fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return closeTunnelCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
reg.Register(&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.",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
s := createTunnelFlags{}
|
||||||
|
fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
|
||||||
|
return fl, &s
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return createTunnelCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
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.",
|
||||||
|
Callback: func(fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return queryLighthouseCommand(f, fs, a, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func listHostMapCommand(hl controlHostLister, a any, w commands.StringWriter) error {
|
||||||
|
fs, ok := a.(*listHostMapFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *listHostMapFlags but was %T", a)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
})
|
||||||
|
|
||||||
|
if fs.Json || fs.Pretty {
|
||||||
|
js := json.NewEncoder(w.GetWriter())
|
||||||
|
if fs.Pretty {
|
||||||
|
js.SetIndent("", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := js.Encode(hm); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
for _, v := range hm {
|
||||||
|
err := w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddrs, v.RemoteAddrs))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func listLighthouseAddrmapCommand(lightHouse *LightHouse, a any, w commands.StringWriter) error {
|
||||||
|
fs, ok := a.(*listHostMapFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *listHostMapFlags but was %T", a)
|
||||||
|
}
|
||||||
|
|
||||||
|
type lighthouseInfo struct {
|
||||||
|
VpnAddr string `json:"vpnAddr"`
|
||||||
|
Addrs *CacheMap `json:"addrs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
})
|
||||||
|
|
||||||
|
if fs.Json || fs.Pretty {
|
||||||
|
js := json.NewEncoder(w.GetWriter())
|
||||||
|
if fs.Pretty {
|
||||||
|
js.SetIndent("", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := js.Encode(addrMap); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
for _, v := range addrMap {
|
||||||
|
b, err := json.Marshal(v.Addrs)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddr, string(b)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseVpnAddr parses the vpn address a command takes as its first operand, failing to w
|
||||||
|
// when there is none or it does not parse. noun is how the command's messages name it,
|
||||||
|
// "vpn address" or "vpn addr", which the output golden pins per command.
|
||||||
|
func parseVpnAddr(a []string, noun string, w commands.StringWriter) (netip.Addr, error) {
|
||||||
|
if len(a) == 0 {
|
||||||
|
return netip.Addr{}, commands.Fail(w, "No vpn address was provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
vpnAddr, err := netip.ParseAddr(a[0])
|
||||||
|
if err != nil {
|
||||||
|
return netip.Addr{}, commands.Fail(w, fmt.Sprintf("The provided %s could not be parsed: %s", noun, a[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return vpnAddr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func versionCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
return w.WriteLine(ifce.version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func queryLighthouseCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
vpnAddr, err := parseVpnAddr(a, "vpn address", w)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var cm *CacheMap
|
||||||
|
rl := ifce.lightHouse.Query(vpnAddr)
|
||||||
|
if rl != nil {
|
||||||
|
cm = rl.CopyCache()
|
||||||
|
}
|
||||||
|
return json.NewEncoder(w.GetWriter()).Encode(cm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeTunnelCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
flags, ok := fs.(*closeTunnelFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *closeTunnelFlags but was %T", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
vpnAddr, err := parseVpnAddr(a, "vpn address", w)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||||
|
if hostInfo == nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if !flags.LocalOnly {
|
||||||
|
ifce.sendCloseTunnel(hostInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
ifce.closeTunnel(hostInfo)
|
||||||
|
return w.WriteLine("Closed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTunnelCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
flags, ok := fs.(*createTunnelFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *createTunnelFlags but was %T", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
vpnAddr, err := parseVpnAddr(a, "vpn address", w)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||||
|
if hostInfo != nil {
|
||||||
|
return commands.Fail(w, "Tunnel already exists")
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo = ifce.handshakeManager.QueryVpnAddr(vpnAddr)
|
||||||
|
if hostInfo != nil {
|
||||||
|
return commands.Fail(w, "Tunnel already handshaking")
|
||||||
|
}
|
||||||
|
|
||||||
|
var addr netip.AddrPort
|
||||||
|
if flags.Address != "" {
|
||||||
|
addr, err = netip.ParseAddrPort(flags.Address)
|
||||||
|
if err != nil {
|
||||||
|
return commands.Fail(w, "Address could not be parsed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 w.WriteLine("Created")
|
||||||
|
}
|
||||||
|
|
||||||
|
func changeRemoteCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
flags, ok := fs.(*changeRemoteFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *changeRemoteFlags but was %T", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
vpnAddr, err := parseVpnAddr(a, "vpn address", w)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if flags.Address == "" {
|
||||||
|
return commands.Fail(w, "No address was provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := netip.ParseAddrPort(flags.Address)
|
||||||
|
if err != nil {
|
||||||
|
return commands.Fail(w, "Address could not be parsed")
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||||
|
if hostInfo == nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo.SetRemote(addr)
|
||||||
|
return w.WriteLine("Changed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func logLevelCommand(l *slog.Logger, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
ctrl, ok := l.Handler().(interface {
|
||||||
|
GetLevel() slog.Level
|
||||||
|
SetLevel(slog.Level)
|
||||||
|
})
|
||||||
|
if !ok {
|
||||||
|
return commands.Fail(w, "Log level is not reconfigurable on this logger")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(a) == 0 {
|
||||||
|
return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
|
||||||
|
}
|
||||||
|
|
||||||
|
level, err := logging.ParseLevel(strings.ToLower(a[0]))
|
||||||
|
if err != nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Unknown log level %s. Possible log levels: trace, debug, info, warn, error", a))
|
||||||
|
}
|
||||||
|
|
||||||
|
ctrl.SetLevel(level)
|
||||||
|
return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logFormatCommand(l *slog.Logger, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
ctrl, ok := l.Handler().(interface {
|
||||||
|
GetFormat() string
|
||||||
|
SetFormat(string) error
|
||||||
|
})
|
||||||
|
if !ok {
|
||||||
|
return commands.Fail(w, "Log format is not reconfigurable on this logger")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(a) == 0 {
|
||||||
|
return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ctrl.SetFormat(strings.ToLower(a[0])); err != nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Unable to set log format: %s", err))
|
||||||
|
}
|
||||||
|
return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func printCertCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
args, ok := fs.(*printCertFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *printCertFlags but was %T", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
cert := ifce.pki.getCertState().GetDefaultCertificate()
|
||||||
|
if len(a) > 0 {
|
||||||
|
vpnAddr, err := parseVpnAddr(a, "vpn addr", w)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||||
|
if hostInfo == nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
cert = hostInfo.GetCert().Certificate
|
||||||
|
}
|
||||||
|
|
||||||
|
if args.Json || args.Pretty {
|
||||||
|
b, err := cert.MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Unable to marshal the certificate: %s", err))
|
||||||
|
}
|
||||||
|
|
||||||
|
if args.Pretty {
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if err := json.Indent(buf, b, "", " "); err != nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Unable to marshal the certificate: %s", err))
|
||||||
|
}
|
||||||
|
b = buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
return w.WriteBytes(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
if args.Raw {
|
||||||
|
b, err := cert.MarshalPEM()
|
||||||
|
if err != nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Unable to marshal the certificate: %s", err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return w.WriteBytes(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
return w.WriteLine(cert.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func printRelaysCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
args, ok := fs.(*printTunnelFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *printTunnelFlags but was %T", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
ifce.hostMap.RLock()
|
||||||
|
relays := maps.Clone(ifce.hostMap.Relays)
|
||||||
|
ifce.hostMap.RUnlock()
|
||||||
|
|
||||||
|
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 CmdOutput struct {
|
||||||
|
Relays []*RelayOutput
|
||||||
|
}
|
||||||
|
|
||||||
|
co := CmdOutput{}
|
||||||
|
|
||||||
|
enc := json.NewEncoder(w.GetWriter())
|
||||||
|
|
||||||
|
if args.Pretty {
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
|
||||||
|
s := ""
|
||||||
|
switch r.State {
|
||||||
|
case Requested:
|
||||||
|
s = "requested"
|
||||||
|
case Established:
|
||||||
|
s = "established"
|
||||||
|
default:
|
||||||
|
s = "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
rf.LocalIndex = r.LocalIndex
|
||||||
|
rf.RemoteIndex = r.RemoteIndex
|
||||||
|
rf.PeerAddr = r.PeerAddr
|
||||||
|
rf.Type = t
|
||||||
|
rf.State = s
|
||||||
|
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 enc.Encode(co)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printTunnelCommand(ifce *Interface, fs any, a []string, w commands.StringWriter) error {
|
||||||
|
args, ok := fs.(*printTunnelFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected *printTunnelFlags but was %T", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
vpnAddr, err := parseVpnAddr(a, "vpn addr", w)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||||
|
if hostInfo == nil {
|
||||||
|
return commands.Fail(w, fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
enc := json.NewEncoder(w.GetWriter())
|
||||||
|
if args.Pretty {
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func deviceInfoCommand(ifce *Interface, fs any, w commands.StringWriter) error {
|
||||||
|
flags, ok := fs.(*deviceInfoFlags)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("internal error: expected flags to be deviceInfoFlags but was %+v", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Cidr []netip.Prefix `json:"cidr"`
|
||||||
|
}{
|
||||||
|
Name: ifce.inside.Name(),
|
||||||
|
Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(data.Cidr, ifce.inside.Networks())
|
||||||
|
|
||||||
|
if flags.Json || flags.Pretty {
|
||||||
|
js := json.NewEncoder(w.GetWriter())
|
||||||
|
if flags.Pretty {
|
||||||
|
js.SetIndent("", " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
return js.Encode(data)
|
||||||
|
} else {
|
||||||
|
return w.WriteLine(fmt.Sprintf("name=%v cidr=%v", data.Name, data.Cidr))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// reloadCommand reloads the config and writes the result to the client. It reloads even if the client has gone away
|
||||||
|
func reloadCommand(l *slog.Logger, c *config.C, w commands.StringWriter) error {
|
||||||
|
writeErr := w.WriteLine("Reloading config")
|
||||||
|
res := c.ReloadConfig()
|
||||||
|
res.Log(l)
|
||||||
|
if err := w.WriteLine(res.String()); writeErr == nil {
|
||||||
|
writeErr = err
|
||||||
|
}
|
||||||
|
if writeErr != nil {
|
||||||
|
return writeErr
|
||||||
|
}
|
||||||
|
if res.Err != nil || res.Failed {
|
||||||
|
return &commands.Failure{Msg: res.String()}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package commands
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
type CommandFlags func() (*flag.FlagSet, any)
|
||||||
|
|
||||||
|
// CommandCallback is called when your command should execute.
|
||||||
|
// fs will be a pointer to the struct provided by Command.Flags callback, if there was one. -h and -help are reserved
|
||||||
|
// and handled automatically for you.
|
||||||
|
// a will be any unconsumed arguments, if no Command.Flags was available this will be all the flags passed in.
|
||||||
|
// w is the writer to use when sending messages back to the client.
|
||||||
|
// An error returned by the callback is handed back to whoever dispatched the command, which reports a failure: exit
|
||||||
|
// status 1 over ssh. The error is not shown to the user. For a failure the user caused or can act on, write the
|
||||||
|
// message and return it as a *Failure, which Fail does in one step; the surface then reports the failure without
|
||||||
|
// logging what the user was already told. Any other error is logged by the surface as well.
|
||||||
|
type CommandCallback func(fs any, a []string, w StringWriter) error
|
||||||
|
|
||||||
|
type Command struct {
|
||||||
|
Name Name
|
||||||
|
ShortDescription string
|
||||||
|
Help string
|
||||||
|
|
||||||
|
Flags CommandFlags
|
||||||
|
Callback CommandCallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failure is the error a command returns for a failure it has already explained to the user:
|
||||||
|
// the message it wrote is the whole story. A surface reports it as a failure and does not
|
||||||
|
// log it.
|
||||||
|
type Failure struct {
|
||||||
|
Msg string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Failure) Error() string {
|
||||||
|
return f.Msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fail writes msg to w and returns it as a *Failure, so a command reports a failure to the
|
||||||
|
// user and to its surface in one line. If the write itself fails, that error is returned
|
||||||
|
// instead: the user was not told anything.
|
||||||
|
func Fail(w StringWriter, msg string) error {
|
||||||
|
if err := w.WriteLine(msg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return &Failure{Msg: msg}
|
||||||
|
}
|
||||||
|
|
||||||
|
func execCommand(c *Command, args []string, w StringWriter) error {
|
||||||
|
var (
|
||||||
|
fl *flag.FlagSet
|
||||||
|
fs any
|
||||||
|
)
|
||||||
|
|
||||||
|
if c.Flags != nil {
|
||||||
|
fl, fs = c.Flags()
|
||||||
|
if fl != nil {
|
||||||
|
// SetOutput() here in case fl.Parse dumps usage.
|
||||||
|
fl.SetOutput(w.GetWriter())
|
||||||
|
err := fl.Parse(args)
|
||||||
|
if err != nil {
|
||||||
|
// fl.Parse has dumped error information to the user via the w writer.
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
args = fl.Args()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Callback(fs, args, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkHelpArgs(args []string) bool {
|
||||||
|
for _, a := range args {
|
||||||
|
if a == "-h" || a == "-help" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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"
|
||||||
|
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"
|
||||||
|
)
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
package commands
|
||||||
|
|
||||||
|
import (
|
||||||
|
"cmp"
|
||||||
|
"fmt"
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/anmitsu/go-shlex"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Registry holds a set of commands. New is the only way to make one.
|
||||||
|
//
|
||||||
|
// It is safe for concurrent use. Commands may be registered while a surface is serving
|
||||||
|
// from the registry: the ssh server clones it per session, and a clone may overlap a
|
||||||
|
// Register.
|
||||||
|
type Registry struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
commands map[Name]*Command
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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",
|
||||||
|
Callback: func(a any, args []string, w StringWriter) error {
|
||||||
|
return r.help(args, w)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register adds a command that can be run by a user. A command registered under a name
|
||||||
|
// already held replaces it; see Clone for what that means for Help.
|
||||||
|
func (r *Registry) Register(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.
|
||||||
|
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, with help bound to the copy: a
|
||||||
|
// command registered on the clone alone is listed and described there, and one the
|
||||||
|
// clone withholds is not. That rebinding replaces whatever was registered under Help on
|
||||||
|
// the source, built-in or not.
|
||||||
|
func (r *Registry) Clone() *Registry {
|
||||||
|
r.mu.RLock()
|
||||||
|
c := &Registry{commands: maps.Clone(r.commands)}
|
||||||
|
r.mu.RUnlock()
|
||||||
|
c.registerHelp()
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispatch parses a command line and runs it, reporting problems to w. The error is for
|
||||||
|
// the caller to log, not to show; see CommandCallback.
|
||||||
|
func (r *Registry) Dispatch(line string, w StringWriter) error {
|
||||||
|
// A line shlex cannot split, an unbalanced quote.
|
||||||
|
args, err := shlex.Split(line, true)
|
||||||
|
if err != nil {
|
||||||
|
return Fail(w, "could not parse the command line: "+err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.DispatchArgs(args, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DispatchArgs runs an already tokenized command line. The error is as for Dispatch.
|
||||||
|
func (r *Registry) DispatchArgs(args []string, w StringWriter) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
r.dumpCommands(w)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c := r.Get(Name(args[0]))
|
||||||
|
if c == nil {
|
||||||
|
// Only the first word was looked up, so only it is named.
|
||||||
|
msg := fmt.Sprintf("did not understand: %s", args[0])
|
||||||
|
if err := w.WriteLine(msg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
r.dumpCommands(w)
|
||||||
|
return &Failure{Msg: msg}
|
||||||
|
}
|
||||||
|
|
||||||
|
if checkHelpArgs(args) {
|
||||||
|
// Through the registered help command, so -h and `help <name>` are one path.
|
||||||
|
return execCommand(r.Get(Help), []string{string(c.Name)}, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
return execCommand(c, args[1:], w)
|
||||||
|
}
|
||||||
|
|
||||||
|
// dumpCommands writes the list of available commands to w.
|
||||||
|
func (r *Registry) dumpCommands(w StringWriter) {
|
||||||
|
err := w.WriteLine("Available commands:")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// In the order All gives, which is the display order.
|
||||||
|
cmds := make([]string, 0)
|
||||||
|
for _, l := range r.All() {
|
||||||
|
cmds = append(cmds, fmt.Sprintf("%s - %s", l.Name, l.ShortDescription))
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = w.Write(strings.Join(cmds, "\n") + "\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// help writes the command list, or usage for the single command named in a.
|
||||||
|
func (r *Registry) help(a []string, w StringWriter) error {
|
||||||
|
// Just typed help
|
||||||
|
if len(a) == 0 {
|
||||||
|
r.dumpCommands(w)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// We are printing a specific commands help text
|
||||||
|
cmd := r.Get(Name(a[0]))
|
||||||
|
if cmd == nil {
|
||||||
|
return Fail(w, "Command not available "+a[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := w.WriteLine(fmt.Sprintf("%s - %s", cmd.Name, cmd.ShortDescription)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if cmd.Help != "" {
|
||||||
|
if err := w.WriteLine(fmt.Sprintf(" %s", cmd.Help)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if cmd.Flags != nil {
|
||||||
|
fs, _ := cmd.Flags()
|
||||||
|
if fs != nil {
|
||||||
|
fs.SetOutput(w.GetWriter())
|
||||||
|
fs.PrintDefaults()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package commands
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testRegistry() *Registry {
|
||||||
|
r := New()
|
||||||
|
r.Register(&Command{
|
||||||
|
Name: "served",
|
||||||
|
ShortDescription: "a command this surface serves",
|
||||||
|
Callback: func(fs any, a []string, w StringWriter) error {
|
||||||
|
return w.WriteLine("read " + strings.Join(a, ","))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
r.Register(&Command{
|
||||||
|
Name: "withheld",
|
||||||
|
ShortDescription: "a command this surface withholds",
|
||||||
|
Callback: func(fs any, a []string, w StringWriter) error {
|
||||||
|
return w.WriteLine("wrote")
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFlagUsageGoesToTheWriter pins that a parse failure's usage lands on the command's
|
||||||
|
// writer.
|
||||||
|
func TestFlagUsageGoesToTheWriter(t *testing.T) {
|
||||||
|
r := New()
|
||||||
|
r.Register(&Command{
|
||||||
|
Name: "emit",
|
||||||
|
ShortDescription: "emits",
|
||||||
|
Flags: func() (*flag.FlagSet, any) {
|
||||||
|
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||||
|
fl.Bool("json", false, "emit json")
|
||||||
|
return fl, nil
|
||||||
|
},
|
||||||
|
Callback: func(fs any, a []string, w StringWriter) error { return nil },
|
||||||
|
})
|
||||||
|
|
||||||
|
merged := &bytes.Buffer{}
|
||||||
|
require.Error(t, r.DispatchArgs([]string{"emit", "-nope"}, NewStringWriter(merged)))
|
||||||
|
assert.Contains(t, merged.String(), "flag provided but not defined")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDispatchReportsUnparseableLine: a line shlex rejects, an unbalanced quote, is a
|
||||||
|
// failure the user is told about.
|
||||||
|
func TestDispatchReportsUnparseableLine(t *testing.T) {
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
err := testRegistry().Dispatch(`served "unterminated`, NewStringWriter(out))
|
||||||
|
|
||||||
|
var f *Failure
|
||||||
|
require.ErrorAs(t, err, &f)
|
||||||
|
assert.Equal(t, f.Msg+"\n", out.String())
|
||||||
|
assert.Contains(t, out.String(), "could not parse the command line: ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFailTellsTheUserAndTheSurface: Fail writes the message and returns it as a Failure;
|
||||||
|
// when the write fails, the user heard nothing, so the write error is what comes back.
|
||||||
|
func TestFailTellsTheUserAndTheSurface(t *testing.T) {
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
err := Fail(NewStringWriter(out), "no such tunnel")
|
||||||
|
var f *Failure
|
||||||
|
require.ErrorAs(t, err, &f)
|
||||||
|
assert.Equal(t, "no such tunnel", f.Msg)
|
||||||
|
assert.Equal(t, "no such tunnel\n", out.String())
|
||||||
|
|
||||||
|
err = Fail(NewStringWriter(failingWriter{}), "no such tunnel")
|
||||||
|
require.EqualError(t, err, "gone")
|
||||||
|
assert.NotErrorAs(t, err, &f)
|
||||||
|
}
|
||||||
|
|
||||||
|
type failingWriter struct{}
|
||||||
|
|
||||||
|
func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("gone") }
|
||||||
|
|
||||||
|
// TestAllSortsByName: registration order does not matter.
|
||||||
|
func TestAllSortsByName(t *testing.T) {
|
||||||
|
r := New()
|
||||||
|
for _, n := range []Name{"zz", Version, "aa", ChangeRemote} {
|
||||||
|
r.Register(&Command{Name: n})
|
||||||
|
}
|
||||||
|
|
||||||
|
var got []Name
|
||||||
|
for _, c := range r.All() {
|
||||||
|
got = append(got, c.Name)
|
||||||
|
}
|
||||||
|
assert.Equal(t, []Name{"aa", ChangeRemote, Help, Version, "zz"}, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHelpFlagAgreesWithHelpCommand pins that -h answers through the registered help
|
||||||
|
// command, and that help on a clone describes the clone: a command registered only there
|
||||||
|
// is known to both -h and `help <name>`, and one withheld from it is known to neither.
|
||||||
|
func TestHelpFlagAgreesWithHelpCommand(t *testing.T) {
|
||||||
|
r := testRegistry()
|
||||||
|
c := r.Clone()
|
||||||
|
c.Register(&Command{
|
||||||
|
Name: Logout,
|
||||||
|
ShortDescription: "ends the session",
|
||||||
|
Callback: func(fs any, a []string, w StringWriter) error { return nil },
|
||||||
|
})
|
||||||
|
|
||||||
|
flag := &bytes.Buffer{}
|
||||||
|
c.Dispatch("logout -h", NewStringWriter(flag))
|
||||||
|
cmd := &bytes.Buffer{}
|
||||||
|
c.Dispatch("help logout", NewStringWriter(cmd))
|
||||||
|
assert.Equal(t, cmd.String(), flag.String())
|
||||||
|
assert.Equal(t, "logout - ends the session\n", flag.String())
|
||||||
|
|
||||||
|
// The source never learns of it.
|
||||||
|
src := &bytes.Buffer{}
|
||||||
|
r.Dispatch("help logout", NewStringWriter(src))
|
||||||
|
assert.Equal(t, "Command not available logout\n", src.String())
|
||||||
|
|
||||||
|
// And a command both hold is described either way.
|
||||||
|
flag.Reset()
|
||||||
|
c.Dispatch("served -h", NewStringWriter(flag))
|
||||||
|
assert.Equal(t, "served - a command this surface serves\n", flag.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCloneHelpListsTheClone: the command list help prints is the clone's, so a clone
|
||||||
|
// that withholds a command does not name it, and the source still does.
|
||||||
|
func TestCloneHelpListsTheClone(t *testing.T) {
|
||||||
|
r := testRegistry()
|
||||||
|
c := New()
|
||||||
|
c.Register(r.Get("served"))
|
||||||
|
c = c.Clone()
|
||||||
|
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
c.Dispatch("help", NewStringWriter(out))
|
||||||
|
assert.Equal(t, "Available commands:\n"+
|
||||||
|
"help - prints available commands or help <command> for specific usage info\n"+
|
||||||
|
"served - a command this surface serves\n\n", out.String())
|
||||||
|
|
||||||
|
out.Reset()
|
||||||
|
c.Dispatch("help withheld", NewStringWriter(out))
|
||||||
|
assert.Equal(t, "Command not available withheld\n", out.String())
|
||||||
|
|
||||||
|
out.Reset()
|
||||||
|
r.Dispatch("help withheld", NewStringWriter(out))
|
||||||
|
assert.Equal(t, "withheld - a command this surface withholds\n", out.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDispatchReturnsTheCommandsError: what the callback returns reaches the caller, so
|
||||||
|
// a surface can log it.
|
||||||
|
func TestDispatchReturnsTheCommandsError(t *testing.T) {
|
||||||
|
r := New()
|
||||||
|
r.Register(&Command{
|
||||||
|
Name: "fails",
|
||||||
|
Callback: func(fs any, a []string, w StringWriter) error {
|
||||||
|
return errors.New("boom")
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
require.EqualError(t, r.Dispatch("fails", NewStringWriter(out)), "boom")
|
||||||
|
assert.Empty(t, out.String(), "a command's own error is not shown; the command speaks for itself")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUnknownCommandNamesTheWord: only the first word is looked up, so only it is
|
||||||
|
// reported, followed by the command list, and the line is a failure to the surface.
|
||||||
|
func TestUnknownCommandNamesTheWord(t *testing.T) {
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
err := testRegistry().Dispatch(`nope "with args"`, NewStringWriter(out))
|
||||||
|
var f *Failure
|
||||||
|
require.ErrorAs(t, err, &f)
|
||||||
|
assert.Equal(t, "did not understand: nope", f.Msg)
|
||||||
|
assert.True(t, strings.HasPrefix(out.String(), "did not understand: nope\nAvailable commands:\n"), out.String())
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
package sshd
|
package commands
|
||||||
|
|
||||||
import "io"
|
import "io"
|
||||||
|
|
||||||
|
// StringWriter is how a command talks back to whoever invoked it: one stream, which the
|
||||||
|
// ssh surface points at its channel.
|
||||||
type StringWriter interface {
|
type StringWriter interface {
|
||||||
WriteLine(string) error
|
WriteLine(string) error
|
||||||
Write(string) error
|
Write(string) error
|
||||||
@@ -13,6 +15,11 @@ type stringWriter struct {
|
|||||||
w io.Writer
|
w io.Writer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewStringWriter returns a StringWriter that writes to w.
|
||||||
|
func NewStringWriter(w io.Writer) StringWriter {
|
||||||
|
return &stringWriter{w: w}
|
||||||
|
}
|
||||||
|
|
||||||
func (w *stringWriter) WriteLine(s string) error {
|
func (w *stringWriter) WriteLine(s string) error {
|
||||||
return w.Write(s + "\n")
|
return w.Write(s + "\n")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package nebula
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"net/netip"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"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 reported to the user
|
||||||
|
// as a failure, rather than returned bare, which over ssh was silence.
|
||||||
|
func TestLogFormatRefusalIsShown(t *testing.T) {
|
||||||
|
l := logging.NewLogger(io.Discard)
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
w := commands.NewStringWriter(out)
|
||||||
|
|
||||||
|
var f *commands.Failure
|
||||||
|
require.ErrorAs(t, logFormatCommand(l, nil, []string{"bogus"}, w), &f)
|
||||||
|
assert.Equal(t, "Unable to set log format: unknown log format `bogus`. possible formats: [text json]\n", out.String())
|
||||||
|
|
||||||
|
out.Reset()
|
||||||
|
require.NoError(t, logFormatCommand(l, nil, []string{"JSON"}, w))
|
||||||
|
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}
|
||||||
|
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
require.NoError(t, printRelaysCommand(ifce, &printTunnelFlags{}, nil, commands.NewStringWriter(out)))
|
||||||
|
assert.JSONEq(t, `{"Relays":[{"NebulaAddr":"10.0.0.1","RelayForAddrs":[{"Error":"could not find hostinfo","Type":"","State":"","PeerAddr":"","LocalIndex":0,"RemoteIndex":0,"RelayedThrough":null}]}]}`, out.String())
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
out.Reset()
|
||||||
|
require.NoError(t, printRelaysCommand(ifce, &printTunnelFlags{}, nil, commands.NewStringWriter(out)))
|
||||||
|
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}]}]}`, out.String())
|
||||||
|
|
||||||
|
// And an index mismatch names it.
|
||||||
|
hm.Relays[7] = hi
|
||||||
|
delete(hm.Relays, 1)
|
||||||
|
out.Reset()
|
||||||
|
require.NoError(t, printRelaysCommand(ifce, &printTunnelFlags{}, nil, commands.NewStringWriter(out)))
|
||||||
|
assert.Contains(t, out.String(), `"Error":"hostmap LocalIndex '7' does not match RelayState LocalIndex"`)
|
||||||
|
}
|
||||||
+38
-32
@@ -5,6 +5,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"maps"
|
||||||
"math"
|
"math"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
@@ -25,9 +26,12 @@ 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)
|
callbacks []func(*C, *Reload)
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewC(l *slog.Logger) *C {
|
func NewC(l *slog.Logger) *C {
|
||||||
@@ -71,8 +75,9 @@ 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.
|
||||||
func (c *C) RegisterReloadCallback(f func(*C)) {
|
// Use r to report anything that failed or needs a restart to apply.
|
||||||
|
func (c *C) RegisterReloadCallback(f func(c *C, r *Reload)) {
|
||||||
c.callbacks = append(c.callbacks, f)
|
c.callbacks = append(c.callbacks, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,54 +148,55 @@ 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()
|
c.ReloadConfig().Log(c.l)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *C) ReloadConfig() {
|
// ReloadConfig reloads the config from the path provided to Load and runs every registered callback. A config that
|
||||||
|
// 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)
|
||||||
for k, v := range c.Settings {
|
maps.Copy(c.oldSettings, 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}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := c.Load(c.path)
|
return c.runCallbacks()
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *C) ReloadConfigString(raw string) error {
|
// ReloadConfigString is ReloadConfig for a config held in memory rather than on disk.
|
||||||
|
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)
|
||||||
for k, v := range c.Settings {
|
maps.Copy(c.oldSettings, 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}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := c.LoadString(raw)
|
return c.runCallbacks()
|
||||||
if err != nil {
|
}
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
|
func (c *C) runCallbacks() ReloadResult {
|
||||||
|
r := &Reload{c: c}
|
||||||
for _, v := range c.callbacks {
|
for _, v := range c.callbacks {
|
||||||
v(c)
|
v(c, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
if r.restart {
|
||||||
|
c.needsRestart = true
|
||||||
|
}
|
||||||
|
return ReloadResult{Failed: r.failed, RestartRequired: c.needsRestart, RestartKeys: r.keys}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -216,7 +222,7 @@ func (c *C) GetStringSlice(k string, d []string) []string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
v := make([]string, len(rv))
|
v := make([]string, len(rv))
|
||||||
for i := 0; i < len(v); i++ {
|
for i := range v {
|
||||||
v[i] = fmt.Sprintf("%v", rv[i])
|
v[i] = fmt.Sprintf("%v", rv[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,8 +316,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.Split(k, ".")
|
parts := strings.SplitSeq(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
|
||||||
@@ -394,7 +400,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 err
|
return fmt.Errorf("%s: %w", path, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// We need to use WithAppendSlice so that firewall rules in separate
|
// We need to use WithAppendSlice so that firewall rules in separate
|
||||||
|
|||||||
@@ -19,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), "yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `invalid...` into map[string]interface {}")
|
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 {}")
|
||||||
|
|
||||||
// simple multi config merge
|
// simple multi config merge
|
||||||
c = NewC(l)
|
c = NewC(l)
|
||||||
@@ -129,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) {
|
c.RegisterReloadCallback(func(c *C, _ *Reload) {
|
||||||
done <- true
|
done <- true
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
+38
-13
@@ -57,7 +57,8 @@ 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) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
|
r.RestartRequiredIfChanged("timers.connection_alive_interval", "timers.pending_deletion_interval")
|
||||||
cm.reload(c, false)
|
cm.reload(c, false)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -105,11 +106,18 @@ func (cm *connectionManager) getInactivityTimeout() time.Duration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cm *connectionManager) In(h *HostInfo) {
|
func (cm *connectionManager) In(h *HostInfo) {
|
||||||
h.in.Store(true)
|
h.markIn()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cm *connectionManager) Out(h *HostInfo) {
|
// OutNoRebind records outbound traffic without consuming the rebind epoch, for relayed sends: the direct path
|
||||||
h.out.Store(true)
|
// 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 {
|
||||||
|
return h.markOut(cm.intf.rebindEpoch.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cm *connectionManager) RelayUsed(localIndex uint32) {
|
func (cm *connectionManager) RelayUsed(localIndex uint32) {
|
||||||
@@ -128,8 +136,7 @@ func (cm *connectionManager) RelayUsed(localIndex uint32) {
|
|||||||
// getAndResetTrafficCheck returns if there was any inbound or outbound traffic within the last tick and
|
// getAndResetTrafficCheck returns if there was any inbound or outbound traffic within the last tick and
|
||||||
// resets the state for this local index
|
// resets the state for this local index
|
||||||
func (cm *connectionManager) getAndResetTrafficCheck(h *HostInfo, now time.Time) (bool, bool) {
|
func (cm *connectionManager) getAndResetTrafficCheck(h *HostInfo, now time.Time) (bool, bool) {
|
||||||
in := h.in.Swap(false)
|
in, out := h.takeTraffic()
|
||||||
out := h.out.Swap(false)
|
|
||||||
if in || out {
|
if in || out {
|
||||||
h.lastUsed = now
|
h.lastUsed = now
|
||||||
}
|
}
|
||||||
@@ -168,10 +175,8 @@ func (cm *connectionManager) doTrafficCheck(localIndex uint32, p, nb, out []byte
|
|||||||
|
|
||||||
switch decision {
|
switch decision {
|
||||||
case deleteTunnel:
|
case deleteTunnel:
|
||||||
if cm.hostMap.DeleteHostInfo(hostinfo) {
|
// Local delete only, clearing the lighthouse cache if this was the last hostinfo for the vpn addr
|
||||||
// Only clearing the lighthouse cache if this is the last hostinfo for this vpn ip in the hostmap
|
cm.intf.closeTunnel(hostinfo)
|
||||||
cm.intf.lightHouse.DeleteVpnAddrs(hostinfo.vpnAddrs)
|
|
||||||
}
|
|
||||||
|
|
||||||
case closeTunnel:
|
case closeTunnel:
|
||||||
cm.intf.sendCloseTunnel(hostinfo)
|
cm.intf.sendCloseTunnel(hostinfo)
|
||||||
@@ -323,6 +328,12 @@ 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 {
|
||||||
@@ -340,7 +351,7 @@ func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Tim
|
|||||||
"tunnelCheck", m{"state": "alive", "method": "passive"},
|
"tunnelCheck", m{"state": "alive", "method": "passive"},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
hostinfo.pendingDeletion.Store(false)
|
hostinfo.setPendingDeletion(false)
|
||||||
|
|
||||||
if mainHostInfo {
|
if mainHostInfo {
|
||||||
decision = tryRehandshake
|
decision = tryRehandshake
|
||||||
@@ -363,7 +374,7 @@ func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Tim
|
|||||||
return decision, hostinfo, primary
|
return decision, hostinfo, primary
|
||||||
}
|
}
|
||||||
|
|
||||||
if hostinfo.pendingDeletion.Load() {
|
if hostinfo.isPendingDeletion() {
|
||||||
// We have already sent a test packet and nothing was returned, this hostinfo is dead
|
// We have already sent a test packet and nothing was returned, this hostinfo is dead
|
||||||
hostinfo.logger(cm.l).Info("Tunnel status",
|
hostinfo.logger(cm.l).Info("Tunnel status",
|
||||||
"tunnelCheck", m{"state": "dead", "method": "active"},
|
"tunnelCheck", m{"state": "dead", "method": "active"},
|
||||||
@@ -414,7 +425,7 @@ func (cm *connectionManager) makeTrafficDecision(localIndex uint32, now time.Tim
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
hostinfo.pendingDeletion.Store(true)
|
hostinfo.setPendingDeletion(true)
|
||||||
cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
|
cm.trafficTimer.Add(hostinfo.localIndexId, cm.pendingDeletionInterval)
|
||||||
return decision, hostinfo, nil
|
return decision, hostinfo, nil
|
||||||
}
|
}
|
||||||
@@ -448,6 +459,11 @@ 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
|
||||||
@@ -544,6 +560,15 @@ 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
|
||||||
}
|
}
|
||||||
|
|||||||
+113
-36
@@ -7,6 +7,7 @@ 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"
|
||||||
@@ -21,10 +22,13 @@ 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{}{}
|
||||||
|
|
||||||
|
lh.localAddrsFn = func(*LocalAllowList) []netip.Addr { return nil }
|
||||||
lh.lighthouses.Store(&lighthouses)
|
lh.lighthouses.Store(&lighthouses)
|
||||||
lh.staticList.Store(&staticList)
|
lh.staticList.Store(&staticList)
|
||||||
|
|
||||||
@@ -85,25 +89,25 @@ func Test_NewConnectionManagerTest(t *testing.T) {
|
|||||||
// We saw traffic out to vpnIp
|
// We saw traffic out to vpnIp
|
||||||
nc.Out(hostinfo)
|
nc.Out(hostinfo)
|
||||||
nc.In(hostinfo)
|
nc.In(hostinfo)
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
assert.True(t, hostinfo.out.Load())
|
assert.True(t, hostinfo.sentSinceCheck())
|
||||||
assert.True(t, hostinfo.in.Load())
|
assert.True(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
|
|
||||||
// Do a traffic check tick, should not be pending deletion but should not have any in/out packets recorded
|
// Do a traffic check tick, should not be pending deletion but should not have any in/out packets recorded
|
||||||
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
|
|
||||||
// Do another traffic check tick, this host should be pending deletion now
|
// Do another traffic check tick, this host should be pending deletion now
|
||||||
nc.Out(hostinfo)
|
nc.Out(hostinfo)
|
||||||
assert.True(t, hostinfo.out.Load())
|
assert.True(t, hostinfo.sentSinceCheck())
|
||||||
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
||||||
assert.True(t, hostinfo.pendingDeletion.Load())
|
assert.True(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
|
|
||||||
@@ -167,37 +171,110 @@ func Test_NewConnectionManagerTest2(t *testing.T) {
|
|||||||
// We saw traffic out to vpnIp
|
// We saw traffic out to vpnIp
|
||||||
nc.Out(hostinfo)
|
nc.Out(hostinfo)
|
||||||
nc.In(hostinfo)
|
nc.In(hostinfo)
|
||||||
assert.True(t, hostinfo.in.Load())
|
assert.True(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
assert.True(t, hostinfo.out.Load())
|
assert.True(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
|
|
||||||
// Do a traffic check tick, should not be pending deletion but should not have any in/out packets recorded
|
// Do a traffic check tick, should not be pending deletion but should not have any in/out packets recorded
|
||||||
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
|
|
||||||
// Do another traffic check tick, this host should be pending deletion now
|
// Do another traffic check tick, this host should be pending deletion now
|
||||||
nc.Out(hostinfo)
|
nc.Out(hostinfo)
|
||||||
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
||||||
assert.True(t, hostinfo.pendingDeletion.Load())
|
assert.True(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
|
|
||||||
// We saw traffic, should no longer be pending deletion
|
// We saw traffic, should no longer be pending deletion
|
||||||
nc.In(hostinfo)
|
nc.In(hostinfo)
|
||||||
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
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")
|
||||||
@@ -252,31 +329,31 @@ func Test_NewConnectionManager_DisconnectInactive(t *testing.T) {
|
|||||||
// Do a traffic check tick, in and out should be cleared but should not be pending deletion
|
// Do a traffic check tick, in and out should be cleared but should not be pending deletion
|
||||||
nc.Out(hostinfo)
|
nc.Out(hostinfo)
|
||||||
nc.In(hostinfo)
|
nc.In(hostinfo)
|
||||||
assert.True(t, hostinfo.out.Load())
|
assert.True(t, hostinfo.sentSinceCheck())
|
||||||
assert.True(t, hostinfo.in.Load())
|
assert.True(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
decision, _, _ := nc.makeTrafficDecision(hostinfo.localIndexId, now)
|
decision, _, _ := nc.makeTrafficDecision(hostinfo.localIndexId, now)
|
||||||
assert.Equal(t, tryRehandshake, decision)
|
assert.Equal(t, tryRehandshake, decision)
|
||||||
assert.Equal(t, now, hostinfo.lastUsed)
|
assert.Equal(t, now, hostinfo.lastUsed)
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
|
|
||||||
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Second*5))
|
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Second*5))
|
||||||
assert.Equal(t, doNothing, decision)
|
assert.Equal(t, doNothing, decision)
|
||||||
assert.Equal(t, now, hostinfo.lastUsed)
|
assert.Equal(t, now, hostinfo.lastUsed)
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
|
|
||||||
// Do another traffic check tick, should still not be pending deletion
|
// Do another traffic check tick, should still not be pending deletion
|
||||||
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Second*10))
|
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Second*10))
|
||||||
assert.Equal(t, doNothing, decision)
|
assert.Equal(t, doNothing, decision)
|
||||||
assert.Equal(t, now, hostinfo.lastUsed)
|
assert.Equal(t, now, hostinfo.lastUsed)
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
|
|
||||||
@@ -284,9 +361,9 @@ func Test_NewConnectionManager_DisconnectInactive(t *testing.T) {
|
|||||||
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Minute*10))
|
decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Minute*10))
|
||||||
assert.Equal(t, closeTunnel, decision)
|
assert.Equal(t, closeTunnel, decision)
|
||||||
assert.Equal(t, now, hostinfo.lastUsed)
|
assert.Equal(t, now, hostinfo.lastUsed)
|
||||||
assert.False(t, hostinfo.pendingDeletion.Load())
|
assert.False(t, hostinfo.isPendingDeletion())
|
||||||
assert.False(t, hostinfo.out.Load())
|
assert.False(t, hostinfo.sentSinceCheck())
|
||||||
assert.False(t, hostinfo.in.Load())
|
assert.False(t, (hostinfo.state.Load()&stateIn != 0))
|
||||||
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
|
||||||
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
|
||||||
}
|
}
|
||||||
|
|||||||
+95
-3
@@ -2,15 +2,37 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/handshake"
|
"github.com/slackhq/nebula/handshake"
|
||||||
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/noiseutil"
|
"github.com/slackhq/nebula/noiseutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
const ReplayWindow = 8192
|
const (
|
||||||
|
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
|
||||||
@@ -20,14 +42,22 @@ type ConnectionState struct {
|
|||||||
initiator bool
|
initiator bool
|
||||||
messageCounter atomic.Uint64
|
messageCounter atomic.Uint64
|
||||||
window *Bits
|
window *Bits
|
||||||
|
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 {
|
func newConnectionStateFromResult(r *handshake.Result) (*ConnectionState, error) {
|
||||||
|
// 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,
|
||||||
@@ -35,12 +65,13 @@ func newConnectionStateFromResult(r *handshake.Result) *ConnectionState {
|
|||||||
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
|
return ci, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
|
func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
|
||||||
@@ -51,6 +82,67 @@ 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) {
|
||||||
|
cs.decryptLock.Lock()
|
||||||
|
result := cs.window.Check(l, messageCounter)
|
||||||
|
cs.decryptLock.Unlock()
|
||||||
|
if !result {
|
||||||
|
return nil, ErrAlreadySeen
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := cs.dKey.DecryptDanger(packet[header.Len:header.Len], packet[:header.Len], packet[header.Len:], messageCounter, nb)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cs.decryptLock.Lock()
|
||||||
|
result = cs.window.Update(l, messageCounter)
|
||||||
|
cs.decryptLock.Unlock()
|
||||||
|
if !result {
|
||||||
|
return nil, ErrAlreadySeen
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *ConnectionState) VerifyRelay(l *slog.Logger, messageCounter uint64, packet []byte, nb []byte) error {
|
||||||
|
cs.decryptLock.Lock()
|
||||||
|
result := cs.window.Check(l, messageCounter)
|
||||||
|
cs.decryptLock.Unlock()
|
||||||
|
if !result {
|
||||||
|
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()]
|
||||||
|
signatureValue := packet[len(packet)-cs.dKey.Overhead():]
|
||||||
|
_, err := cs.dKey.DecryptDanger(nil, signedPayload, signatureValue, messageCounter, nb)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cs.decryptLock.Lock()
|
||||||
|
result = cs.window.Update(l, messageCounter)
|
||||||
|
cs.decryptLock.Unlock()
|
||||||
|
if !result {
|
||||||
|
return ErrAlreadySeen
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+199
-2
@@ -2,14 +2,20 @@ 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"
|
||||||
)
|
)
|
||||||
@@ -79,11 +85,193 @@ 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 := newConnectionStateFromResult(initR)
|
ci, err := 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)
|
||||||
@@ -102,8 +290,17 @@ 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 := newConnectionStateFromResult(respR)
|
ci, err := 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)
|
||||||
|
|||||||
+20
-3
@@ -11,6 +11,7 @@ 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"
|
||||||
)
|
)
|
||||||
@@ -47,12 +48,14 @@ 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()
|
||||||
statsStart func()
|
statsStart func()
|
||||||
dnsStart func()
|
dnsStart func()
|
||||||
lighthouseStart func()
|
lighthouseStart func()
|
||||||
|
networkChangeStart func(rebind func())
|
||||||
connectionManagerStart func(context.Context)
|
connectionManagerStart func(context.Context)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,6 +107,9 @@ func (c *Control) Start() error {
|
|||||||
if c.dnsStart != nil {
|
if c.dnsStart != nil {
|
||||||
go c.dnsStart()
|
go c.dnsStart()
|
||||||
}
|
}
|
||||||
|
if c.networkChangeStart != nil {
|
||||||
|
go c.networkChangeStart(c.RebindUDPServer)
|
||||||
|
}
|
||||||
if c.connectionManagerStart != nil {
|
if c.connectionManagerStart != nil {
|
||||||
go c.connectionManagerStart(c.ctx)
|
go c.connectionManagerStart(c.ctx)
|
||||||
}
|
}
|
||||||
@@ -111,7 +117,7 @@ func (c *Control) Start() error {
|
|||||||
c.lighthouseStart()
|
c.lighthouseStart()
|
||||||
}
|
}
|
||||||
|
|
||||||
c.f.triggerShutdown = c.Stop
|
c.f.triggerShutdown = func() { go c.Stop() }
|
||||||
|
|
||||||
// Start reading packets.
|
// Start reading packets.
|
||||||
c.f.run()
|
c.f.run()
|
||||||
@@ -198,13 +204,17 @@ func (c *Control) RebindUDPServer() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = c.f.outside.Rebind()
|
// A failure here means we are likely still pinned to the interface we came up on, so the rest of this is
|
||||||
|
// unlikely to help. Say so instead of silently carrying on as if we rebound.
|
||||||
|
if err := c.f.outside.Rebind(); err != nil {
|
||||||
|
c.l.Error("Failed to rebind udp socket", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
// Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
|
// Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
|
||||||
c.f.lightHouse.SendUpdate()
|
c.f.lightHouse.SendUpdate()
|
||||||
|
|
||||||
// Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
|
// Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
|
||||||
c.f.rebindCount++
|
c.f.rebindEpoch.Add(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
|
// ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
|
||||||
@@ -364,6 +374,13 @@ 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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.RxBatcher, 1),
|
batchers: make([]*batch.MultiCoalescer, 1),
|
||||||
routines: 1,
|
routines: 1,
|
||||||
hostMap: newHostMap(l),
|
hostMap: newHostMap(l),
|
||||||
lightHouse: lh,
|
lightHouse: lh,
|
||||||
@@ -148,10 +148,10 @@ func (c *fakeConn) Rebind() error { c.rebinds++; ret
|
|||||||
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, _ func()) 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(_ [][]byte, _ []netip.AddrPort, _ []byte) error {
|
func (c *fakeConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
|
||||||
return nil
|
return len(bufs), nil
|
||||||
}
|
}
|
||||||
func (c *fakeConn) ReloadConfig(_ *config.C) {}
|
func (c *fakeConn) ReloadConfig(_ *config.C, _ *config.Reload) {}
|
||||||
func (c *fakeConn) SupportsMultipleReaders() bool { return true }
|
func (c *fakeConn) SupportsMultipleReaders() bool { return true }
|
||||||
func (c *fakeConn) Close() error { c.closed = true; return nil }
|
func (c *fakeConn) Close() error { c.closed = true; return nil }
|
||||||
|
|
||||||
@@ -177,7 +177,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.RxBatcher, 2),
|
batchers: make([]*batch.MultiCoalescer, 2),
|
||||||
routines: 2,
|
routines: 2,
|
||||||
l: test.NewLogger(),
|
l: test.NewLogger(),
|
||||||
}
|
}
|
||||||
@@ -247,7 +247,7 @@ func TestControl_ConcurrentStopAndStart(t *testing.T) {
|
|||||||
c, _, _ := newReadyControl(t)
|
c, _, _ := newReadyControl(t)
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
for i := 0; i < 2; i++ {
|
for range 2 {
|
||||||
wg.Go(func() { c.Stop() })
|
wg.Go(func() { c.Stop() })
|
||||||
}
|
}
|
||||||
wg.Go(func() { _ = c.Start() })
|
wg.Go(func() { _ = c.Start() })
|
||||||
|
|||||||
+23
-1
@@ -108,7 +108,29 @@ func (c *Control) GetVpnAddrs() []netip.Addr {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Control) GetUDPAddr() netip.AddrPort {
|
func (c *Control) GetUDPAddr() netip.AddrPort {
|
||||||
return c.f.outside.(*udp.TesterConn).Addr
|
return c.f.outside.(*udp.TesterConn).GetAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUDPAddr moves this node to a new underlay address, standing in for a laptop waking up on a different
|
||||||
|
// network. Register the new address with the router as well or nothing will route back.
|
||||||
|
func (c *Control) SetUDPAddr(addr netip.AddrPort) {
|
||||||
|
c.f.outside.(*udp.TesterConn).SetAddr(addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetLocalAddrsFn replaces underlay address discovery so a test can advertise its simulated address instead of
|
||||||
|
// whatever this machine's NICs happen to be. Call it before Start, SendUpdate reads it from the update worker.
|
||||||
|
func (c *Control) SetLocalAddrsFn(fn func(*LocalAllowList) []netip.Addr) {
|
||||||
|
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 {
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
// 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
//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)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
//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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//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, ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
//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
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
//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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//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)
|
||||||
|
}
|
||||||
+64
-27
@@ -38,8 +38,8 @@ type dnsServer struct {
|
|||||||
|
|
||||||
serverMu sync.Mutex
|
serverMu sync.Mutex
|
||||||
server *dns.Server
|
server *dns.Server
|
||||||
// started is closed once `server` has finished binding (or after
|
// started is closed once `server` is serving (or after serve returns
|
||||||
// ListenAndServe returns on a bind failure). Stop waits on it before
|
// without ever starting). Stop waits on it before
|
||||||
// calling Shutdown to avoid the miekg/dns "server not started" race
|
// calling Shutdown to avoid the miekg/dns "server not started" race
|
||||||
// where a Shutdown that arrives before bind completes is silently
|
// where a Shutdown that arrives before bind completes is silently
|
||||||
// ignored, leaving the listener running forever.
|
// ignored, leaving the listener running forever.
|
||||||
@@ -69,9 +69,10 @@ 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) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
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()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -83,7 +84,7 @@ func newDnsServerFromConfig(ctx context.Context, l *slog.Logger, pki *PKI, hostM
|
|||||||
}
|
}
|
||||||
|
|
||||||
// reload applies the latest config and reconciles the running state with it:
|
// reload applies the latest config and reconciles the running state with it:
|
||||||
// - enabled toggled on -> spawn a runner
|
// - enabled toggled on -> bind, then serve in the background
|
||||||
// - enabled toggled off -> stop the runner
|
// - enabled toggled off -> stop the runner
|
||||||
// - listen address changed (while running) -> restart on the new address
|
// - listen address changed (while running) -> restart on the new address
|
||||||
// - everything else -> no-op
|
// - everything else -> no-op
|
||||||
@@ -97,8 +98,7 @@ func (d *dnsServer) reload(c *config.C, initial bool) error {
|
|||||||
newAddr := getDnsServerAddr(c)
|
newAddr := getDnsServerAddr(c)
|
||||||
|
|
||||||
d.serverMu.Lock()
|
d.serverMu.Lock()
|
||||||
running := d.server
|
running := d.server != nil
|
||||||
runningStarted := d.started
|
|
||||||
sameAddr := d.addr == newAddr
|
sameAddr := d.addr == newAddr
|
||||||
d.addr = newAddr
|
d.addr = newAddr
|
||||||
d.enabled.Store(enabled)
|
d.enabled.Store(enabled)
|
||||||
@@ -112,7 +112,7 @@ func (d *dnsServer) reload(c *config.C, initial bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !enabled {
|
if !enabled {
|
||||||
if running != nil {
|
if running {
|
||||||
d.Stop()
|
d.Stop()
|
||||||
}
|
}
|
||||||
// Drop any records that accumulated while enabled; a later re-enable
|
// Drop any records that accumulated while enabled; a later re-enable
|
||||||
@@ -121,13 +121,20 @@ func (d *dnsServer) reload(c *config.C, initial bool) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if running == nil {
|
if running && !sameAddr {
|
||||||
// Was disabled (or never started); bring it up now.
|
// Stop clears the slot before shutting down, otherwise the listen below can find the dying server and refuse
|
||||||
go d.Start()
|
d.Stop()
|
||||||
} else if !sameAddr {
|
running = false
|
||||||
d.shutdownServer(running, runningStarted, "reload")
|
}
|
||||||
// Old Start goroutine has now exited; bring up a fresh listener on the new address.
|
if !running {
|
||||||
go d.Start()
|
// Bind here rather than in the background, so a reload that can't listen says so
|
||||||
|
server, started, err := d.listen()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if server != nil {
|
||||||
|
go d.serve(server, started)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refresh the self entry every enabled reload so cert renewals that change our name or VPN addresses are picked up.
|
// Refresh the self entry every enabled reload so cert renewals that change our name or VPN addresses are picked up.
|
||||||
@@ -156,28 +163,50 @@ func (d *dnsServer) shutdownServer(srv *dns.Server, started chan struct{}, reaso
|
|||||||
// Must be invoked after the tun device is active so that lighthouse.dns.host
|
// Must be invoked after the tun device is active so that lighthouse.dns.host
|
||||||
// may bind to a nebula IP.
|
// may bind to a nebula IP.
|
||||||
func (d *dnsServer) Start() {
|
func (d *dnsServer) Start() {
|
||||||
if !d.enabled.Load() {
|
server, started, err := d.listen()
|
||||||
|
if err != nil {
|
||||||
|
d.l.Warn("Failed to run the DNS responder", "error", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if server != nil {
|
||||||
|
d.serve(server, started)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// listen binds the responder and claims the server slot for serve. It returns a nil server, and no error, when DNS is
|
||||||
|
// disabled or a server is already running.
|
||||||
|
func (d *dnsServer) listen() (*dns.Server, chan struct{}, error) {
|
||||||
|
if !d.enabled.Load() {
|
||||||
|
return nil, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
started := make(chan struct{})
|
started := make(chan struct{})
|
||||||
d.serverMu.Lock()
|
d.serverMu.Lock()
|
||||||
if d.ctx.Err() != nil {
|
defer d.serverMu.Unlock()
|
||||||
d.serverMu.Unlock()
|
// Re-check enabled under the lock, a disable that raced our check above snapshots the slot under it too.
|
||||||
return
|
// A reload and Control.Start can both get here, the loser would orphan the live listener past Stop
|
||||||
|
if d.ctx.Err() != nil || d.server != nil || !d.enabled.Load() {
|
||||||
|
return nil, nil, nil
|
||||||
|
}
|
||||||
|
pc, err := net.ListenPacket("udp", d.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
addr := d.addr
|
|
||||||
server := &dns.Server{
|
server := &dns.Server{
|
||||||
Addr: addr,
|
Addr: d.addr,
|
||||||
Net: "udp",
|
PacketConn: pc,
|
||||||
Handler: d.mux,
|
Handler: d.mux,
|
||||||
NotifyStartedFunc: func() { close(started) },
|
NotifyStartedFunc: func() { close(started) },
|
||||||
}
|
}
|
||||||
d.server = server
|
d.server = server
|
||||||
d.started = started
|
d.started = started
|
||||||
d.serverMu.Unlock()
|
d.l.Info("Starting DNS responder", "dnsListener", pc.LocalAddr())
|
||||||
|
return server, started, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Per-invocation ctx watcher. Exits when Start does, so we don't leak a
|
// serve answers queries on a server from listen until Stop or the context ends it.
|
||||||
|
func (d *dnsServer) serve(server *dns.Server, started chan struct{}) {
|
||||||
|
// Per-invocation ctx watcher. Exits when serve does, so we don't leak a
|
||||||
// watcher per reload-driven restart.
|
// watcher per reload-driven restart.
|
||||||
done := make(chan struct{})
|
done := make(chan struct{})
|
||||||
go func() {
|
go func() {
|
||||||
@@ -188,18 +217,26 @@ func (d *dnsServer) Start() {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
d.l.Info("Starting DNS responder", "dnsListener", addr)
|
err := server.ActivateAndServe()
|
||||||
err := server.ListenAndServe()
|
|
||||||
close(done)
|
close(done)
|
||||||
|
|
||||||
// If the listener never bound (bind error) NotifyStartedFunc never fires,
|
// If serving failed before it started NotifyStartedFunc never fires, so close started here to release any Stop
|
||||||
// so close started here to release any Stop caller waiting on it.
|
// caller waiting on it. ActivateAndServe doesn't close the socket on that path either
|
||||||
select {
|
select {
|
||||||
case <-started:
|
case <-started:
|
||||||
default:
|
default:
|
||||||
close(started)
|
close(started)
|
||||||
|
_ = server.PacketConn.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Release our slot, unless a reload already replaced us, so a dead listener can't block a future Start
|
||||||
|
d.serverMu.Lock()
|
||||||
|
if d.server == server {
|
||||||
|
d.server = nil
|
||||||
|
d.started = nil
|
||||||
|
}
|
||||||
|
d.serverMu.Unlock()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
d.l.Warn("Failed to run the DNS responder", "error", err)
|
d.l.Warn("Failed to run the DNS responder", "error", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+225
-4
@@ -194,14 +194,51 @@ func TestDnsServer_reload_initial_serveDnsWithoutLighthouse(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestDnsServer_reload_sameAddr_noOp(t *testing.T) {
|
func TestDnsServer_reload_sameAddr_noOp(t *testing.T) {
|
||||||
|
port := freeUDPPort(t)
|
||||||
ds, c := newTestDnsServer(t)
|
ds, c := newTestDnsServer(t)
|
||||||
setDnsConfig(c, "127.0.0.1", "0", true, true)
|
setDnsConfig(c, "127.0.0.1", port, true, true)
|
||||||
|
|
||||||
require.NoError(t, ds.reload(c, true))
|
require.NoError(t, ds.reload(c, true))
|
||||||
// No server running yet, no addr change. Reload should not spawn anything.
|
|
||||||
|
go ds.Start()
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
before := ds.server
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
require.NotNil(t, before)
|
||||||
|
|
||||||
|
// Same address, so the running listener must be left alone rather than rebuilt under live queries
|
||||||
require.NoError(t, ds.reload(c, false))
|
require.NoError(t, ds.reload(c, false))
|
||||||
assert.True(t, ds.enabled.Load())
|
assert.True(t, ds.enabled.Load())
|
||||||
assert.Nil(t, ds.server)
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
after := ds.server
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
assert.Same(t, before, after, "a same-address reload must not restart the listener")
|
||||||
|
|
||||||
|
ds.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The branch the old sameAddr test was accidentally hitting: enabled with nothing running means reload starts it.
|
||||||
|
func TestDnsServer_reload_whenNotRunning_starts(t *testing.T) {
|
||||||
|
port := freeUDPPort(t)
|
||||||
|
ds, c := newTestDnsServer(t)
|
||||||
|
setDnsConfig(c, "127.0.0.1", port, true, true)
|
||||||
|
|
||||||
|
// initial only records config, it never starts anything
|
||||||
|
require.NoError(t, ds.reload(c, true))
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
assert.Nil(t, ds.server, "the initial reload must not start a listener")
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
|
||||||
|
require.NoError(t, ds.reload(c, false))
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
assert.NotNil(t, ds.server, "a reload with nothing running should bring DNS up")
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
|
||||||
|
ds.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDnsServer_StartStop_lifecycle(t *testing.T) {
|
func TestDnsServer_StartStop_lifecycle(t *testing.T) {
|
||||||
@@ -427,3 +464,187 @@ func waitFor(t *testing.T, cond func() bool) {
|
|||||||
}
|
}
|
||||||
t.Fatal("timed out waiting for condition")
|
t.Fatal("timed out waiting for condition")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Two reloads in quick succession, or a HUP before Control.Start, can race two Starts at the same listener.
|
||||||
|
func TestDnsServer_Start_isIdempotent(t *testing.T) {
|
||||||
|
port := freeUDPPort(t)
|
||||||
|
ds, c := newTestDnsServer(t)
|
||||||
|
setDnsConfig(c, "127.0.0.1", port, true, true)
|
||||||
|
require.NoError(t, ds.reload(c, true))
|
||||||
|
|
||||||
|
go ds.Start()
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
first := ds.server
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
require.NotNil(t, first)
|
||||||
|
|
||||||
|
// If the second Start replaces the tracked server, Stop kills the wrong one and the port leaks
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
ds.Start()
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(time.Second * 5):
|
||||||
|
t.Fatal("second Start never returned")
|
||||||
|
}
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
second := ds.server
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
assert.Same(t, first, second, "a second Start must not replace the running server")
|
||||||
|
|
||||||
|
// The real proof, after Stop the port must actually be free
|
||||||
|
ds.Stop()
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
pc, err := net.ListenPacket("udp", "127.0.0.1:"+port)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_ = pc.Close()
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// An address change must actually end up listening on the new port. Start's guard refuses when a server is already
|
||||||
|
// installed, so reload has to clear the slot before shutting the old one down.
|
||||||
|
func TestDnsServer_reload_addrChange_restarts(t *testing.T) {
|
||||||
|
first := freeUDPPort(t)
|
||||||
|
second := freeUDPPort(t)
|
||||||
|
|
||||||
|
ds, c := newTestDnsServer(t)
|
||||||
|
setDnsConfig(c, "127.0.0.1", first, true, true)
|
||||||
|
require.NoError(t, ds.reload(c, true))
|
||||||
|
|
||||||
|
go ds.Start()
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
// Cycle a few times, the failure this guards against depends on which goroutine wins serverMu
|
||||||
|
for i := range 8 {
|
||||||
|
want := second
|
||||||
|
if i%2 == 1 {
|
||||||
|
want = first
|
||||||
|
}
|
||||||
|
setDnsConfig(c, "127.0.0.1", want, true, true)
|
||||||
|
require.NoError(t, ds.reload(c, false))
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
srv := ds.server
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
require.NotNil(t, srv, "reload left DNS down instead of restarting it")
|
||||||
|
require.Equal(t, "127.0.0.1:"+want, srv.Addr, "reload should be serving the new address")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Land back on second so the port assertions below are meaningful
|
||||||
|
setDnsConfig(c, "127.0.0.1", second, true, true)
|
||||||
|
require.NoError(t, ds.reload(c, false))
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
// The old port must be released and the new one actually held
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
pc, err := net.ListenPacket("udp", "127.0.0.1:"+first)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_ = pc.Close()
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
_, err := net.ListenPacket("udp", "127.0.0.1:"+second)
|
||||||
|
require.Error(t, err, "the new address should be bound by the DNS responder")
|
||||||
|
|
||||||
|
ds.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// A listener that dies on its own must release the slot, or a later same-addr reload sees it as running and no-ops.
|
||||||
|
func TestDnsServer_Start_bindFailure_releasesSlot(t *testing.T) {
|
||||||
|
port := freeUDPPort(t)
|
||||||
|
blocker, err := net.ListenPacket("udp", "127.0.0.1:"+port)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
ds, c := newTestDnsServer(t)
|
||||||
|
setDnsConfig(c, "127.0.0.1", port, true, true)
|
||||||
|
require.NoError(t, ds.reload(c, true))
|
||||||
|
|
||||||
|
ds.Start() // returns once the bind fails
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
assert.Nil(t, ds.server, "a listener that failed to bind must not stay parked in the slot")
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
|
||||||
|
// With the slot released, a reload can retry once the port frees up
|
||||||
|
require.NoError(t, blocker.Close())
|
||||||
|
require.NoError(t, ds.reload(c, false))
|
||||||
|
waitForBind(t, ds)
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
assert.NotNil(t, ds.server, "a same-addr reload should retry after a failed bind")
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
|
||||||
|
ds.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// A disable that lands while Start is between its unlocked check and the guard must not leave a listener behind.
|
||||||
|
func TestDnsServer_Start_refusesWhenDisabledUnderLock(t *testing.T) {
|
||||||
|
port := freeUDPPort(t)
|
||||||
|
ds, c := newTestDnsServer(t)
|
||||||
|
setDnsConfig(c, "127.0.0.1", port, true, true)
|
||||||
|
require.NoError(t, ds.reload(c, true))
|
||||||
|
require.True(t, ds.enabled.Load())
|
||||||
|
|
||||||
|
// Holding serverMu parks Start on the lock, the only way to land the disable in that window on purpose
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
ds.Start()
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
t.Fatal("Start returned early, the test never exercised the window")
|
||||||
|
case <-time.After(time.Millisecond * 100):
|
||||||
|
}
|
||||||
|
|
||||||
|
// The disable reload's critical section. It sees nothing running, so it never calls Stop.
|
||||||
|
ds.enabled.Store(false)
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(time.Second * 5):
|
||||||
|
t.Fatal("Start never returned")
|
||||||
|
}
|
||||||
|
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
assert.Nil(t, ds.server, "Start must not install a listener a disable already cancelled")
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
|
||||||
|
pc, err := net.ListenPacket("udp", "127.0.0.1:"+port)
|
||||||
|
require.NoError(t, err, "an orphaned listener is still holding the port")
|
||||||
|
_ = pc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// A reload that can't bind says so, rather than finding out in the background
|
||||||
|
func TestDnsServer_reload_busyPortFails(t *testing.T) {
|
||||||
|
busy, err := net.ListenPacket("udp", "127.0.0.1:0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = busy.Close() })
|
||||||
|
_, port, err := net.SplitHostPort(busy.LocalAddr().String())
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
ds, c := newTestDnsServer(t)
|
||||||
|
setDnsConfig(c, "127.0.0.1", port, false, true)
|
||||||
|
require.NoError(t, ds.reload(c, true))
|
||||||
|
|
||||||
|
setDnsConfig(c, "127.0.0.1", port, true, true)
|
||||||
|
require.Error(t, ds.reload(c, false))
|
||||||
|
ds.serverMu.Lock()
|
||||||
|
assert.Nil(t, ds.server, "a failed bind kept the slot")
|
||||||
|
ds.serverMu.Unlock()
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
//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() {}))
|
||||||
|
|
||||||
|
// 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.NewStringWriter(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"}},
|
||||||
|
{"print-cert", []string{"10.222.0.250"}},
|
||||||
|
{"print-cert", []string{"not-an-address"}},
|
||||||
|
{"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,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
+65
-2
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
@@ -725,6 +724,70 @@ func TestReestablishRelays(t *testing.T) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRelayHandshakeOverDisestablishedEntry(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
// If them tears down the tunnel while me keeps Established relay state, me's next
|
||||||
|
// handshake flows through the relay with no fresh CreateRelayRequest and lands on
|
||||||
|
// them's Disestablished terminal relay entry. them must re-establish that entry, or
|
||||||
|
// its first transmit deletes its only relay and the tunnel is born transmit-dead:
|
||||||
|
// them can receive but every send is silently dropped.
|
||||||
|
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||||
|
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version1, ca, caKey, "me ", "10.128.0.1/24", m{"relay": m{"use_relays": true}})
|
||||||
|
relayControl, relayVpnIpNet, relayUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "relay ", "10.128.0.128/24", m{"relay": m{"am_relay": true}})
|
||||||
|
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "them ", "10.128.0.2/24", m{"relay": m{"use_relays": true}})
|
||||||
|
|
||||||
|
// Teach my how to get to the relay and that their can be reached via the relay
|
||||||
|
myControl.InjectLightHouseAddr(relayVpnIpNet[0].Addr(), relayUdpAddr)
|
||||||
|
myControl.InjectRelays(theirVpnIpNet[0].Addr(), []netip.Addr{relayVpnIpNet[0].Addr()})
|
||||||
|
relayControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||||
|
|
||||||
|
// Build a router so we don't have to reason who gets which packet
|
||||||
|
r := router.NewR(t, myControl, relayControl, theirControl)
|
||||||
|
defer r.RenderFlow()
|
||||||
|
|
||||||
|
// Start the servers
|
||||||
|
myControl.Start()
|
||||||
|
relayControl.Start()
|
||||||
|
theirControl.Start()
|
||||||
|
|
||||||
|
t.Log("Trigger a handshake from me to them via the relay")
|
||||||
|
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)
|
||||||
|
oldIdx := myControl.GetHostInfoByVpnAddr(theirVpnIpNet[0].Addr(), false).LocalIndex
|
||||||
|
|
||||||
|
t.Log("Close the tunnel on them only, marking their relay entry Disestablished")
|
||||||
|
theirControl.CloseTunnel(myVpnIpNet[0].Addr(), true)
|
||||||
|
|
||||||
|
t.Log("Re-handshake from me, riding the still-Established relay state")
|
||||||
|
myControl.ReHandshake(theirVpnIpNet[0].Addr())
|
||||||
|
for {
|
||||||
|
h := myControl.GetHostInfoByVpnAddr(theirVpnIpNet[0].Addr(), false)
|
||||||
|
if h != nil && h.LocalIndex != oldIdx && h.RemoteIndex != 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
r.RouteForAllExitFunc(func(*udp.Packet, *nebula.Control) router.ExitType {
|
||||||
|
return router.RouteAndExit
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
hAtThem := theirControl.GetHostInfoByVpnAddr(myVpnIpNet[0].Addr(), false)
|
||||||
|
require.NotNil(t, hAtThem, "them should have completed the relayed handshake")
|
||||||
|
require.Equal(t, []netip.Addr{relayVpnIpNet[0].Addr()}, hAtThem.CurrentRelaysToMe, "them should know a relay for the new tunnel")
|
||||||
|
|
||||||
|
t.Log("Send from them to me; their only relay entry must survive the transmit")
|
||||||
|
theirControl.InjectTunPacket(BuildTunUDPPacket(myVpnIpNet[0].Addr(), 80, theirVpnIpNet[0].Addr(), 80, []byte("Hi from them")))
|
||||||
|
require.Never(t, func() bool {
|
||||||
|
h := theirControl.GetHostInfoByVpnAddr(myVpnIpNet[0].Addr(), false)
|
||||||
|
return h == nil || len(h.CurrentRelaysToMe) == 0
|
||||||
|
}, time.Second, 10*time.Millisecond, "them deleted its only relay entry; the tunnel is permanently transmit-dead")
|
||||||
|
|
||||||
|
p = r.RouteForAllUntilTxTun(myControl)
|
||||||
|
assertUdpPacket(t, []byte("Hi from them"), p, theirVpnIpNet[0].Addr(), myVpnIpNet[0].Addr(), 80, 80)
|
||||||
|
r.RenderHostmaps("Final hostmaps", myControl, relayControl, theirControl)
|
||||||
|
}
|
||||||
|
|
||||||
func TestStage1RaceRelays(t *testing.T) {
|
func TestStage1RaceRelays(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
//NOTE: this is a race between me and relay resulting in a full tunnel from me to them via relay
|
//NOTE: this is a race between me and relay resulting in a full tunnel from me to them via relay
|
||||||
@@ -1450,7 +1513,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)))
|
require.NoError(t, myConfig.ReloadConfigString(string(newCfg)).Err)
|
||||||
|
|
||||||
// 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.
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,281 @@
|
|||||||
|
//go:build e2e_testing
|
||||||
|
|
||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula"
|
||||||
|
"github.com/slackhq/nebula/cert"
|
||||||
|
"github.com/slackhq/nebula/cert_test"
|
||||||
|
"github.com/slackhq/nebula/e2e/router"
|
||||||
|
"github.com/slackhq/nebula/header"
|
||||||
|
"github.com/slackhq/nebula/udp"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// reportedAddrs is what the lighthouse would hand a peer asking where vpnAddr is.
|
||||||
|
func reportedAddrs(t *testing.T, lh *nebula.Control, vpnAddr netip.Addr) []netip.AddrPort {
|
||||||
|
t.Helper()
|
||||||
|
cm := lh.QueryLighthouse(vpnAddr)
|
||||||
|
if cm == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var out []netip.AddrPort
|
||||||
|
for _, c := range *cm {
|
||||||
|
out = append(out, c.Reported...)
|
||||||
|
out = append(out, c.Learned...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitForLighthouseMsg routes until a lighthouse message lands on lh, or gives up. Reports whether one arrived.
|
||||||
|
func waitForLighthouseMsg(t *testing.T, r *router.R, lh *nebula.Control, wait time.Duration) bool {
|
||||||
|
t.Helper()
|
||||||
|
h := &header.H{}
|
||||||
|
return r.RouteForAllExitFuncOrTimeout(wait, func(p *udp.Packet, c *nebula.Control) router.ExitType {
|
||||||
|
if c != lh {
|
||||||
|
return router.KeepRouting
|
||||||
|
}
|
||||||
|
// Punches are a single byte and never parse, they are just not what we are after
|
||||||
|
if err := h.Parse(p.Data); err != nil {
|
||||||
|
return router.KeepRouting
|
||||||
|
}
|
||||||
|
if h.Type == header.LightHouse {
|
||||||
|
return router.RouteAndExit
|
||||||
|
}
|
||||||
|
return router.KeepRouting
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// A laptop that changes networks has to tell the lighthouse promptly, otherwise the lighthouse keeps handing peers
|
||||||
|
// the old address and their punches land nowhere. On a long lighthouse interval the only thing that closes that
|
||||||
|
// window is the rebind, which on darwin the network change monitor drives. The e2e build compiles the monitor out,
|
||||||
|
// so we call RebindUDPServer directly, which is the same thing the monitor does.
|
||||||
|
func TestRebindSendsLighthouseUpdate(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{})
|
||||||
|
|
||||||
|
lhControl, lhVpnIpNet, lhUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "lh", "10.128.0.1/24", m{
|
||||||
|
"lighthouse": m{"am_lighthouse": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 600s interval, so nothing scheduled can send an update during this test. A rebind is the only thing that can.
|
||||||
|
myControl, _, _, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.2/24", m{
|
||||||
|
"lighthouse": m{
|
||||||
|
"hosts": []any{lhVpnIpNet[0].Addr().String()},
|
||||||
|
"interval": 600,
|
||||||
|
},
|
||||||
|
"static_host_map": m{
|
||||||
|
lhVpnIpNet[0].Addr().String(): []any{lhUdpAddr.String()},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
r := router.NewR(t, lhControl, myControl)
|
||||||
|
defer r.RenderFlow()
|
||||||
|
|
||||||
|
lhControl.Start()
|
||||||
|
myControl.Start()
|
||||||
|
|
||||||
|
// Let the startup registration finish, then clear everything it left behind
|
||||||
|
require.True(t, waitForLighthouseMsg(t, r, lhControl, time.Second*5), "expected an initial registration")
|
||||||
|
r.RouteFor(time.Millisecond * 400)
|
||||||
|
|
||||||
|
// Nothing should be talking to the lighthouse on its own now
|
||||||
|
require.False(t, waitForLighthouseMsg(t, r, lhControl, time.Millisecond*200),
|
||||||
|
"nothing should reach the lighthouse before the rebind")
|
||||||
|
|
||||||
|
myControl.RebindUDPServer()
|
||||||
|
|
||||||
|
assert.True(t, waitForLighthouseMsg(t, r, lhControl, time.Second*5),
|
||||||
|
"a rebind should push an update to the lighthouse rather than waiting out the interval")
|
||||||
|
|
||||||
|
lhControl.Stop()
|
||||||
|
myControl.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The other half of a rebind: every live tunnel requeries the lighthouse on its next send. That query is what makes
|
||||||
|
// the lighthouse tell the peer to punch toward our new address, which is the part that actually revives a tunnel
|
||||||
|
// whose remote NAT state died while we were on a different network.
|
||||||
|
func TestRebindRequeriesPeersOnNextSend(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{})
|
||||||
|
|
||||||
|
lhControl, lhVpnIpNet, lhUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "lh", "10.128.0.1/24", m{
|
||||||
|
"lighthouse": m{"am_lighthouse": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
lhCfg := m{
|
||||||
|
"lighthouse": m{
|
||||||
|
"hosts": []any{lhVpnIpNet[0].Addr().String()},
|
||||||
|
"interval": 600,
|
||||||
|
// Without this the peers advertise this machine's real addresses and then try to punch at them,
|
||||||
|
// which the router has no route for.
|
||||||
|
"local_allow_list": m{
|
||||||
|
"10.0.0.0/24": true,
|
||||||
|
"::/0": false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"static_host_map": m{
|
||||||
|
lhVpnIpNet[0].Addr().String(): []any{lhUdpAddr.String()},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
myControl, myVpnIpNet, myUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.2/24", lhCfg)
|
||||||
|
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.3/24", lhCfg)
|
||||||
|
|
||||||
|
r := router.NewR(t, lhControl, myControl, theirControl)
|
||||||
|
defer r.RenderFlow()
|
||||||
|
|
||||||
|
lhControl.Start()
|
||||||
|
myControl.Start()
|
||||||
|
theirControl.Start()
|
||||||
|
r.RouteFor(time.Millisecond * 500)
|
||||||
|
|
||||||
|
// Point the peers at each other directly, this test is about the rebind and not about lighthouse discovery
|
||||||
|
myControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||||
|
theirControl.InjectLightHouseAddr(myVpnIpNet[0].Addr(), myUdpAddr)
|
||||||
|
|
||||||
|
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("initial")))
|
||||||
|
r.RouteFor(time.Second)
|
||||||
|
require.NotNil(t, myControl.GetHostInfoByVpnAddr(theirVpnIpNet[0].Addr(), false), "expected a tunnel to them")
|
||||||
|
r.RouteFor(time.Millisecond * 300)
|
||||||
|
|
||||||
|
// Assert on what the peer sees rather than on lighthouse traffic. A query for them makes the lighthouse send
|
||||||
|
// them a punch notification, which is the whole point. Our own update to the lighthouse sends them nothing,
|
||||||
|
// so this cannot be satisfied by the update the rebind itself pushes.
|
||||||
|
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("quiet")))
|
||||||
|
require.False(t, waitForLighthouseMsg(t, r, theirControl, time.Millisecond*300),
|
||||||
|
"an ordinary send should not requery the lighthouse")
|
||||||
|
|
||||||
|
myControl.RebindUDPServer()
|
||||||
|
r.RouteFor(time.Millisecond * 300) // let the update the rebind itself sends pass by
|
||||||
|
|
||||||
|
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("after rebind")))
|
||||||
|
assert.True(t, waitForLighthouseMsg(t, r, theirControl, time.Second*5),
|
||||||
|
"the first send after a rebind should requery the lighthouse, which then tells the peer to punch at us")
|
||||||
|
|
||||||
|
lhControl.Stop()
|
||||||
|
myControl.Stop()
|
||||||
|
theirControl.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The scenario this whole thing exists for: a laptop sleeps at the office and wakes up at home on a new address.
|
||||||
|
// Until it tells the lighthouse, the lighthouse keeps handing peers the office address, so their punches land
|
||||||
|
// nowhere and the tunnel stays dead. On a long interval the rebind is the only thing that closes that window.
|
||||||
|
func TestRebindAdvertisesNewAddressAfterMove(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{})
|
||||||
|
|
||||||
|
lhControl, lhVpnIpNet, lhUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "lh", "10.128.0.1/24", m{
|
||||||
|
"lighthouse": m{"am_lighthouse": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
myControl, myVpnIpNet, myUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.2/24", m{
|
||||||
|
"lighthouse": m{
|
||||||
|
"hosts": []any{lhVpnIpNet[0].Addr().String()},
|
||||||
|
"interval": 600,
|
||||||
|
},
|
||||||
|
"static_host_map": m{
|
||||||
|
lhVpnIpNet[0].Addr().String(): []any{lhUdpAddr.String()},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Advertise wherever we currently are rather than this machine's real NICs, read fresh each time so a move
|
||||||
|
// is picked up.
|
||||||
|
myControl.SetLocalAddrsFn(func(*nebula.LocalAllowList) []netip.Addr {
|
||||||
|
return []netip.Addr{myControl.GetUDPAddr().Addr()}
|
||||||
|
})
|
||||||
|
|
||||||
|
r := router.NewR(t, lhControl, myControl)
|
||||||
|
defer r.RenderFlow()
|
||||||
|
|
||||||
|
lhControl.Start()
|
||||||
|
myControl.Start()
|
||||||
|
|
||||||
|
require.True(t, waitForLighthouseMsg(t, r, lhControl, time.Second*5), "expected an initial registration")
|
||||||
|
r.RouteFor(time.Millisecond * 400)
|
||||||
|
|
||||||
|
require.Contains(t, reportedAddrs(t, lhControl, myVpnIpNet[0].Addr()), myUdpAddr,
|
||||||
|
"the lighthouse should know the address we started on")
|
||||||
|
|
||||||
|
// Wake up somewhere else
|
||||||
|
newAddr := netip.MustParseAddrPort("10.0.0.99:4242")
|
||||||
|
myControl.SetUDPAddr(newAddr)
|
||||||
|
r.AddRoute(newAddr.Addr(), newAddr.Port(), myControl)
|
||||||
|
|
||||||
|
// Nothing has told the lighthouse, and with interval 600 nothing scheduled will
|
||||||
|
r.RouteFor(time.Millisecond * 400)
|
||||||
|
require.NotContains(t, reportedAddrs(t, lhControl, myVpnIpNet[0].Addr()), newAddr,
|
||||||
|
"the lighthouse should still be handing out the old address before the rebind")
|
||||||
|
|
||||||
|
myControl.RebindUDPServer()
|
||||||
|
require.True(t, waitForLighthouseMsg(t, r, lhControl, time.Second*5), "expected an update after the rebind")
|
||||||
|
r.RouteFor(time.Millisecond * 400)
|
||||||
|
|
||||||
|
assert.Contains(t, reportedAddrs(t, lhControl, myVpnIpNet[0].Addr()), newAddr,
|
||||||
|
"after the rebind the lighthouse should hand peers our new address")
|
||||||
|
|
||||||
|
lhControl.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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
//go:build e2e_testing
|
||||||
|
|
||||||
|
package e2e
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula"
|
||||||
|
"github.com/slackhq/nebula/cert"
|
||||||
|
"github.com/slackhq/nebula/cert_test"
|
||||||
|
"github.com/slackhq/nebula/e2e/router"
|
||||||
|
"github.com/slackhq/nebula/udp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestRecoveryTiming measures how long a tunnel takes to come back after the peer stops accepting our traffic,
|
||||||
|
// which is what a laptop waking on a new network looks like from the peer's side: its NAT has no state for where
|
||||||
|
// we are now, so everything we send disappears.
|
||||||
|
//
|
||||||
|
// It is a measurement, not a pass/fail assertion. Recovery is timed to the moment the peer punches back at us,
|
||||||
|
// since that is when its NAT opens and the tunnel is usable again.
|
||||||
|
//
|
||||||
|
// go test -tags e2e_testing -v -run TestRecoveryTiming ./e2e/
|
||||||
|
func TestRecoveryTiming(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
rebind bool
|
||||||
|
}{
|
||||||
|
{"no trigger", false},
|
||||||
|
{"rebind counter", true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
d, lost := measureRecovery(t, tc.rebind)
|
||||||
|
t.Logf("RESULT %-16s recovered in %-9v (%d packets lost)", tc.name, d.Round(time.Millisecond), lost)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// measureRecovery returns how long until the peer punched back, and how many of our packets died meanwhile. When
|
||||||
|
// rebind is true we call RebindUDPServer once the tunnel goes dark, which is what the darwin network change
|
||||||
|
// monitor does and what iOS has always done. When false, nothing tells nebula anything is wrong.
|
||||||
|
func measureRecovery(t *testing.T, rebind bool) (time.Duration, int) {
|
||||||
|
t.Helper()
|
||||||
|
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||||
|
|
||||||
|
lhControl, lhVpnIpNet, lhUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "lh", "10.128.0.1/24", m{
|
||||||
|
"lighthouse": m{"am_lighthouse": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
peerCfg := m{
|
||||||
|
"lighthouse": m{
|
||||||
|
"hosts": []any{lhVpnIpNet[0].Addr().String()},
|
||||||
|
"interval": 600,
|
||||||
|
"local_allow_list": m{
|
||||||
|
"10.0.0.0/24": true,
|
||||||
|
"::/0": false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"static_host_map": m{
|
||||||
|
lhVpnIpNet[0].Addr().String(): []any{lhUdpAddr.String()},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
myControl, myVpnIpNet, myUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.2/24", peerCfg)
|
||||||
|
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.3/24", peerCfg)
|
||||||
|
|
||||||
|
r := router.NewR(t, lhControl, myControl, theirControl)
|
||||||
|
defer r.RenderFlow()
|
||||||
|
defer func() {
|
||||||
|
lhControl.Stop()
|
||||||
|
myControl.Stop()
|
||||||
|
theirControl.Stop()
|
||||||
|
}()
|
||||||
|
|
||||||
|
lhControl.Start()
|
||||||
|
myControl.Start()
|
||||||
|
theirControl.Start()
|
||||||
|
r.RouteFor(time.Millisecond * 500)
|
||||||
|
|
||||||
|
myControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||||
|
theirControl.InjectLightHouseAddr(myVpnIpNet[0].Addr(), myUdpAddr)
|
||||||
|
|
||||||
|
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("establish")))
|
||||||
|
r.RouteFor(time.Second)
|
||||||
|
if myControl.GetHostInfoByVpnAddr(theirVpnIpNet[0].Addr(), false) == nil {
|
||||||
|
t.Fatal("failed to establish the tunnel we are measuring")
|
||||||
|
}
|
||||||
|
r.RouteFor(time.Millisecond * 500)
|
||||||
|
|
||||||
|
// From here the peer's NAT has no state for us, everything we send it disappears
|
||||||
|
start := time.Now()
|
||||||
|
blackholed := 0
|
||||||
|
var recovered time.Duration
|
||||||
|
|
||||||
|
if rebind {
|
||||||
|
myControl.RebindUDPServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the tun busy the way someone retrying a stalled connection would
|
||||||
|
stop := make(chan struct{})
|
||||||
|
defer close(stop)
|
||||||
|
go func() {
|
||||||
|
tick := time.NewTicker(time.Millisecond * 200)
|
||||||
|
defer tick.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-stop:
|
||||||
|
return
|
||||||
|
case <-tick.C:
|
||||||
|
myControl.InjectTunPacket(BuildTunUDPPacket(
|
||||||
|
theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("retry")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
r.RouteForAllExitFuncOrTimeout(time.Second*30, func(p *udp.Packet, c *nebula.Control) router.ExitType {
|
||||||
|
if c == theirControl && p.From == myControl.GetUDPAddr() {
|
||||||
|
blackholed++
|
||||||
|
return router.Drop
|
||||||
|
}
|
||||||
|
|
||||||
|
// The peer reaching us directly is the moment its NAT opened, whether that is a punch or a handshake
|
||||||
|
if c == myControl && p.From == theirUdpAddr {
|
||||||
|
recovered = time.Since(start)
|
||||||
|
return router.RouteAndExit
|
||||||
|
}
|
||||||
|
|
||||||
|
return router.KeepRouting
|
||||||
|
})
|
||||||
|
|
||||||
|
if recovered == 0 {
|
||||||
|
t.Fatalf("no recovery within 30s (%d packets blackholed)", blackholed)
|
||||||
|
}
|
||||||
|
return recovered, blackholed
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package router
|
package router
|
||||||
|
|
||||||
|
|||||||
+143
-24
@@ -1,16 +1,17 @@
|
|||||||
//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"
|
||||||
@@ -22,7 +23,6 @@ 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
|
||||||
@@ -114,6 +114,28 @@ type packet struct {
|
|||||||
packet *udp.Packet
|
packet *udp.Packet
|
||||||
tun bool // a packet pulled off a tun device
|
tun bool // a packet pulled off a tun device
|
||||||
rx bool // the packet was received by a udp device
|
rx bool // the packet was received by a udp device
|
||||||
|
|
||||||
|
// h is the nebula header, parsed once when the packet is recorded. parseErr says why there isn't one, which
|
||||||
|
// the flow log reports rather than hiding. Punchy sends a single byte, so an unparseable packet is normal.
|
||||||
|
h header.H
|
||||||
|
parseErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
// fromAddr and toAddr are the addresses this packet actually travelled between. Reading them off the control
|
||||||
|
// instead would misreport the whole history once a test moves a node. Tun packets are synthesized without
|
||||||
|
// addresses, so they fall back to the control.
|
||||||
|
func (p *packet) fromAddr() netip.AddrPort {
|
||||||
|
if p.tun || !p.packet.From.IsValid() {
|
||||||
|
return p.from.GetUDPAddr()
|
||||||
|
}
|
||||||
|
return p.packet.From
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *packet) toAddr() netip.AddrPort {
|
||||||
|
if p.tun || !p.packet.To.IsValid() {
|
||||||
|
return p.to.GetUDPAddr()
|
||||||
|
}
|
||||||
|
return p.packet.To
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *packet) WasReceived() {
|
func (p *packet) WasReceived() {
|
||||||
@@ -131,6 +153,9 @@ const (
|
|||||||
ExitNow ExitType = 1
|
ExitNow ExitType = 1
|
||||||
// RouteAndExit routes this packet and exits immediately afterwards
|
// RouteAndExit routes this packet and exits immediately afterwards
|
||||||
RouteAndExit ExitType = 2
|
RouteAndExit ExitType = 2
|
||||||
|
// Drop discards this packet without delivering it and keeps routing. Use it to simulate a blackhole, such as
|
||||||
|
// a restrictive NAT refusing traffic from an address it has not seen.
|
||||||
|
Drop ExitType = 3
|
||||||
)
|
)
|
||||||
|
|
||||||
type ExitFunc func(packet *udp.Packet, receiver *nebula.Control) ExitType
|
type ExitFunc func(packet *udp.Packet, receiver *nebula.Control) ExitType
|
||||||
@@ -141,7 +166,9 @@ type ExitFunc func(packet *udp.Packet, receiver *nebula.Control) ExitType
|
|||||||
func NewR(t testing.TB, controls ...*nebula.Control) *R {
|
func NewR(t testing.TB, controls ...*nebula.Control) *R {
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
if err := os.MkdirAll("mermaid", 0755); err != nil {
|
// t.Name() contains a slash for subtests, so the flow log can land in a nested directory
|
||||||
|
fn := filepath.Join("mermaid", fmt.Sprintf("%s.md", t.Name()))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(fn), 0755); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,7 +179,7 @@ func NewR(t testing.TB, controls ...*nebula.Control) *R {
|
|||||||
outNat: make(map[outNatKey]netip.AddrPort),
|
outNat: make(map[outNatKey]netip.AddrPort),
|
||||||
flow: []flowEntry{},
|
flow: []flowEntry{},
|
||||||
ignoreFlows: []ignoreFlow{},
|
ignoreFlows: []ignoreFlow{},
|
||||||
fn: filepath.Join("mermaid", fmt.Sprintf("%s.md", t.Name())),
|
fn: fn,
|
||||||
t: t,
|
t: t,
|
||||||
cancelRender: cancel,
|
cancelRender: cancel,
|
||||||
}
|
}
|
||||||
@@ -249,7 +276,7 @@ func (r *R) renderFlow() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
addr := e.packet.from.GetUDPAddr()
|
addr := e.packet.fromAddr()
|
||||||
if _, ok := participants[addr]; ok {
|
if _, ok := participants[addr]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -268,7 +295,6 @@ func (r *R) renderFlow() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Print packets
|
// Print packets
|
||||||
h := &header.H{}
|
|
||||||
for _, e := range r.flow {
|
for _, e := range r.flow {
|
||||||
if e.packet == nil {
|
if e.packet == nil {
|
||||||
//fmt.Fprintf(f, " note over %s: %s\n", strings.Join(participantsVals, ", "), e.note)
|
//fmt.Fprintf(f, " note over %s: %s\n", strings.Join(participantsVals, ", "), e.note)
|
||||||
@@ -280,21 +306,22 @@ func (r *R) renderFlow() {
|
|||||||
fmt.Fprintln(f, r.formatUdpPacket(p))
|
fmt.Fprintln(f, r.formatUdpPacket(p))
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
if err := h.Parse(p.packet.Data); err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
line := "--x"
|
line := "--x"
|
||||||
if p.rx {
|
if p.rx {
|
||||||
line = "->>"
|
line = "->>"
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(f,
|
detail := fmt.Sprintf("%s(%s), index %v, counter: %v",
|
||||||
" %s%s%s: %s(%s), index %v, counter: %v\n",
|
p.h.TypeName(), p.h.SubTypeName(), p.h.RemoteIndex, p.h.MessageCounter)
|
||||||
normalizeName(p.from.GetUDPAddr().String()),
|
if p.parseErr != nil {
|
||||||
|
detail = fmt.Sprintf("unparsed, %v (%d bytes)", p.parseErr, len(p.packet.Data))
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(f, " %s%s%s: %s\n",
|
||||||
|
normalizeName(p.fromAddr().String()),
|
||||||
line,
|
line,
|
||||||
normalizeName(p.to.GetUDPAddr().String()),
|
normalizeName(p.toAddr().String()),
|
||||||
h.TypeName(), h.SubTypeName(), h.RemoteIndex, h.MessageCounter,
|
detail,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -347,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 := maps.Values(r.controls)
|
c := slices.AppendSeq(make([]*nebula.Control, 0, len(r.controls)), 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
|
||||||
})
|
})
|
||||||
@@ -408,21 +435,24 @@ func (r *R) unlockedInjectFlow(from, to *nebula.Control, p *udp.Packet, tun bool
|
|||||||
|
|
||||||
r.renderHostmaps(fmt.Sprintf("Packet %v", len(r.flow)))
|
r.renderHostmaps(fmt.Sprintf("Packet %v", len(r.flow)))
|
||||||
|
|
||||||
if len(r.ignoreFlows) > 0 {
|
|
||||||
var h header.H
|
var h header.H
|
||||||
err := h.Parse(p.Data)
|
var parseErr error
|
||||||
if err != nil {
|
if !tun {
|
||||||
panic(err)
|
parseErr = h.Parse(p.Data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Decide before copying, the copy comes from a freelist and an ignored packet would never be released
|
||||||
for _, i := range r.ignoreFlows {
|
for _, i := range r.ignoreFlows {
|
||||||
if !tun {
|
if tun {
|
||||||
if i.messageType == h.Type && i.subType == h.Subtype {
|
if i.tun.HasValue && i.tun.IsTrue {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
} else if i.tun.HasValue && i.tun.IsTrue {
|
continue
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A packet we could not parse has no type to match against, so no rule can ignore it
|
||||||
|
if parseErr == nil && i.messageType == h.Type && i.subType == h.Subtype {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,6 +461,8 @@ func (r *R) unlockedInjectFlow(from, to *nebula.Control, p *udp.Packet, tun bool
|
|||||||
to: to,
|
to: to,
|
||||||
packet: p.Copy(),
|
packet: p.Copy(),
|
||||||
tun: tun,
|
tun: tun,
|
||||||
|
h: h,
|
||||||
|
parseErr: parseErr,
|
||||||
}
|
}
|
||||||
|
|
||||||
r.flow = append(r.flow, flowEntry{packet: fp})
|
r.flow = append(r.flow, flowEntry{packet: fp})
|
||||||
@@ -660,6 +692,10 @@ func (r *R) RouteExitFunc(sender *nebula.Control, whatDo ExitFunc) {
|
|||||||
p.Release()
|
p.Release()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
case Drop:
|
||||||
|
// Record it so the flow log shows the attempt, but never hand it to the receiver
|
||||||
|
r.unlockedInjectFlow(sender, receiver, p, false)
|
||||||
|
|
||||||
case KeepRouting:
|
case KeepRouting:
|
||||||
fp := r.unlockedInjectFlow(sender, receiver, p, false)
|
fp := r.unlockedInjectFlow(sender, receiver, p, false)
|
||||||
receiver.InjectUDPPacket(p)
|
receiver.InjectUDPPacket(p)
|
||||||
@@ -690,6 +726,85 @@ func (r *R) RouteUntilAfterMsgType(sender *nebula.Control, msgType header.Messag
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RouteFor routes everything that shows up for the given duration and then returns. Use it to let a test settle
|
||||||
|
// deterministically rather than sleeping and hoping: a single FlushAll races a completing handshake, which queues
|
||||||
|
// more packets right behind it.
|
||||||
|
func (r *R) RouteFor(d time.Duration) {
|
||||||
|
r.RouteForAllExitFuncOrTimeout(d, func(*udp.Packet, *nebula.Control) ExitType {
|
||||||
|
return KeepRouting
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RouteForAllExitFuncOrTimeout is RouteForAllExitFunc with a deadline, reporting whether whatDo asked to exit
|
||||||
|
// before time ran out. The unbounded version blocks forever on a quiet network, so this is what a test needs to
|
||||||
|
// assert that something does NOT happen, or to route for a fixed settling period.
|
||||||
|
func (r *R) RouteForAllExitFuncOrTimeout(timeout time.Duration, whatDo ExitFunc) bool {
|
||||||
|
sc := make([]reflect.SelectCase, 0, len(r.controls)+1)
|
||||||
|
cm := make([]*nebula.Control, 0, len(r.controls))
|
||||||
|
|
||||||
|
for _, c := range r.controls {
|
||||||
|
sc = append(sc, reflect.SelectCase{
|
||||||
|
Dir: reflect.SelectRecv,
|
||||||
|
Chan: reflect.ValueOf(c.GetUDPTxChan()),
|
||||||
|
Send: reflect.Value{},
|
||||||
|
})
|
||||||
|
cm = append(cm, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
timer := time.NewTimer(timeout)
|
||||||
|
defer timer.Stop()
|
||||||
|
sc = append(sc, reflect.SelectCase{
|
||||||
|
Dir: reflect.SelectRecv,
|
||||||
|
Chan: reflect.ValueOf(timer.C),
|
||||||
|
Send: reflect.Value{},
|
||||||
|
})
|
||||||
|
|
||||||
|
for {
|
||||||
|
x, rx, _ := reflect.Select(sc)
|
||||||
|
if x == len(cm) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Lock()
|
||||||
|
p := rx.Interface().(*udp.Packet)
|
||||||
|
receiver := r.getControl(cm[x].GetUDPAddr(), p.To, p)
|
||||||
|
if receiver == nil {
|
||||||
|
r.Unlock()
|
||||||
|
panic("Can't RouteForAllExitFuncOrTimeout for host: " + p.To.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
e := whatDo(p, receiver)
|
||||||
|
switch e {
|
||||||
|
case ExitNow:
|
||||||
|
r.Unlock()
|
||||||
|
p.Release()
|
||||||
|
return true
|
||||||
|
|
||||||
|
case RouteAndExit:
|
||||||
|
fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
|
||||||
|
receiver.InjectUDPPacket(p)
|
||||||
|
fp.WasReceived()
|
||||||
|
r.Unlock()
|
||||||
|
p.Release()
|
||||||
|
return true
|
||||||
|
|
||||||
|
case Drop:
|
||||||
|
// Record it so the flow log shows the attempt, but never hand it to the receiver
|
||||||
|
r.unlockedInjectFlow(cm[x], receiver, p, false)
|
||||||
|
|
||||||
|
case KeepRouting:
|
||||||
|
fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
|
||||||
|
receiver.InjectUDPPacket(p)
|
||||||
|
fp.WasReceived()
|
||||||
|
|
||||||
|
default:
|
||||||
|
panic(fmt.Sprintf("Unknown exitFunc return: %v", e))
|
||||||
|
}
|
||||||
|
r.Unlock()
|
||||||
|
p.Release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (r *R) RouteForAllUntilAfterMsgTypeTo(receiver *nebula.Control, msgType header.MessageType, subType header.MessageSubType) {
|
func (r *R) RouteForAllUntilAfterMsgTypeTo(receiver *nebula.Control, msgType header.MessageType, subType header.MessageSubType) {
|
||||||
h := &header.H{}
|
h := &header.H{}
|
||||||
r.RouteForAllExitFunc(func(p *udp.Packet, r *nebula.Control) ExitType {
|
r.RouteForAllExitFunc(func(p *udp.Packet, r *nebula.Control) ExitType {
|
||||||
@@ -782,6 +897,10 @@ func (r *R) RouteForAllExitFunc(whatDo ExitFunc) {
|
|||||||
p.Release()
|
p.Release()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
case Drop:
|
||||||
|
// Record it so the flow log shows the attempt, but never hand it to the receiver
|
||||||
|
r.unlockedInjectFlow(cm[x], receiver, p, false)
|
||||||
|
|
||||||
case KeepRouting:
|
case KeepRouting:
|
||||||
fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
|
fp := r.unlockedInjectFlow(cm[x], receiver, p, false)
|
||||||
receiver.InjectUDPPacket(p)
|
receiver.InjectUDPPacket(p)
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
|
|||||||
Vendored
+720
@@ -0,0 +1,720 @@
|
|||||||
|
$ version
|
||||||
|
e2e-test
|
||||||
|
|
||||||
|
$ version -json
|
||||||
|
e2e-test
|
||||||
|
|
||||||
|
$ version -pretty
|
||||||
|
e2e-test
|
||||||
|
|
||||||
|
$ device-info
|
||||||
|
name= cidr=[10.222.0.1/24]
|
||||||
|
|
||||||
|
$ device-info -json
|
||||||
|
{"name":"","cidr":["10.222.0.1/24"]}
|
||||||
|
|
||||||
|
$ device-info -pretty
|
||||||
|
{
|
||||||
|
"name": "",
|
||||||
|
"cidr": [
|
||||||
|
"10.222.0.1/24"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
$ list-hostmap
|
||||||
|
|
||||||
|
$ list-hostmap -json
|
||||||
|
[]
|
||||||
|
|
||||||
|
$ list-hostmap -pretty
|
||||||
|
[]
|
||||||
|
|
||||||
|
$ list-hostmap -by-index
|
||||||
|
|
||||||
|
$ list-hostmap -json -by-index
|
||||||
|
[]
|
||||||
|
|
||||||
|
$ list-hostmap -pretty -by-index
|
||||||
|
[]
|
||||||
|
|
||||||
|
$ list-pending-hostmap
|
||||||
|
[10.222.0.9]: []
|
||||||
|
|
||||||
|
$ list-pending-hostmap -json
|
||||||
|
[{"vpnAddrs":["10.222.0.9"],"localIndex":<n>,"remoteIndex":<n>,"remoteAddrs":[],"cert":null,"messageCounter":<n>,"currentRemote":"","currentRelaysToMe":[],"currentRelaysThroughMe":[]}]
|
||||||
|
|
||||||
|
$ list-pending-hostmap -pretty
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"vpnAddrs": [
|
||||||
|
"10.222.0.9"
|
||||||
|
],
|
||||||
|
"localIndex": <n>,
|
||||||
|
"remoteIndex": <n>,
|
||||||
|
"remoteAddrs": [],
|
||||||
|
"cert": null,
|
||||||
|
"messageCounter": <n>,
|
||||||
|
"currentRemote": "",
|
||||||
|
"currentRelaysToMe": [],
|
||||||
|
"currentRelaysThroughMe": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
$ list-pending-hostmap -by-index
|
||||||
|
|
||||||
|
$ list-pending-hostmap -json -by-index
|
||||||
|
[]
|
||||||
|
|
||||||
|
$ list-pending-hostmap -pretty -by-index
|
||||||
|
[]
|
||||||
|
|
||||||
|
$ list-lighthouse-addrmap
|
||||||
|
10.222.0.9: {}
|
||||||
|
|
||||||
|
$ list-lighthouse-addrmap -json
|
||||||
|
[{"vpnAddr":"10.222.0.9","addrs":{}}]
|
||||||
|
|
||||||
|
$ list-lighthouse-addrmap -pretty
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"vpnAddr": "10.222.0.9",
|
||||||
|
"addrs": {}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
$ print-cert
|
||||||
|
{
|
||||||
|
"details": {
|
||||||
|
"curve": "CURVE25519",
|
||||||
|
"groups": [],
|
||||||
|
"isCa": false,
|
||||||
|
"issuer": "<hex>",
|
||||||
|
"name": "output-golden",
|
||||||
|
"networks": [
|
||||||
|
"10.222.0.1/24"
|
||||||
|
],
|
||||||
|
"notAfter": "<time>",
|
||||||
|
"notBefore": "<time>",
|
||||||
|
"publicKey": "<hex>",
|
||||||
|
"unsafeNetworks": []
|
||||||
|
},
|
||||||
|
"fingerprint": "<hex>",
|
||||||
|
"signature": "<hex>",
|
||||||
|
"version": 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$ print-cert -json
|
||||||
|
{"details":{"curve":"CURVE25519","groups":[],"isCa":false,"issuer":"<hex>","name":"output-golden","networks":["10.222.0.1/24"],"notAfter":"<time>","notBefore":"<time>","publicKey":"<hex>","unsafeNetworks":[]},"fingerprint":"<hex>","signature":"<hex>","version":1}\ No newline at end of output
|
||||||
|
|
||||||
|
$ print-cert -pretty
|
||||||
|
{
|
||||||
|
"details": {
|
||||||
|
"curve": "CURVE25519",
|
||||||
|
"groups": [],
|
||||||
|
"isCa": false,
|
||||||
|
"issuer": "<hex>",
|
||||||
|
"name": "output-golden",
|
||||||
|
"networks": [
|
||||||
|
"10.222.0.1/24"
|
||||||
|
],
|
||||||
|
"notAfter": "<time>",
|
||||||
|
"notBefore": "<time>",
|
||||||
|
"publicKey": "<hex>",
|
||||||
|
"unsafeNetworks": []
|
||||||
|
},
|
||||||
|
"fingerprint": "<hex>",
|
||||||
|
"signature": "<hex>",
|
||||||
|
"version": 1
|
||||||
|
}\ No newline at end of output
|
||||||
|
|
||||||
|
$ print-cert -raw
|
||||||
|
-----BEGIN NEBULA CERTIFICATE-----
|
||||||
|
<pem>
|
||||||
|
-----END NEBULA CERTIFICATE-----
|
||||||
|
|
||||||
|
$ print-cert -json -raw
|
||||||
|
{"details":{"curve":"CURVE25519","groups":[],"isCa":false,"issuer":"<hex>","name":"output-golden","networks":["10.222.0.1/24"],"notAfter":"<time>","notBefore":"<time>","publicKey":"<hex>","unsafeNetworks":[]},"fingerprint":"<hex>","signature":"<hex>","version":1}\ No newline at end of output
|
||||||
|
|
||||||
|
$ print-cert -pretty -raw
|
||||||
|
{
|
||||||
|
"details": {
|
||||||
|
"curve": "CURVE25519",
|
||||||
|
"groups": [],
|
||||||
|
"isCa": false,
|
||||||
|
"issuer": "<hex>",
|
||||||
|
"name": "output-golden",
|
||||||
|
"networks": [
|
||||||
|
"10.222.0.1/24"
|
||||||
|
],
|
||||||
|
"notAfter": "<time>",
|
||||||
|
"notBefore": "<time>",
|
||||||
|
"publicKey": "<hex>",
|
||||||
|
"unsafeNetworks": []
|
||||||
|
},
|
||||||
|
"fingerprint": "<hex>",
|
||||||
|
"signature": "<hex>",
|
||||||
|
"version": 1
|
||||||
|
}\ No newline at end of output
|
||||||
|
|
||||||
|
$ print-cert 10.222.0.9
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.9
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert -json 10.222.0.9
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.9
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert -pretty 10.222.0.9
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.9
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert 10.222.0.250
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert -json 10.222.0.250
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert -pretty 10.222.0.250
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert not-an-address
|
||||||
|
The provided vpn addr could not be parsed: not-an-address
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert -json not-an-address
|
||||||
|
The provided vpn addr could not be parsed: not-an-address
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-cert -pretty not-an-address
|
||||||
|
The provided vpn addr could not be parsed: not-an-address
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel
|
||||||
|
No vpn address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel -json
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-pretty
|
||||||
|
pretty prints json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel -pretty
|
||||||
|
No vpn address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel 10.222.0.9
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.9
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel -json 10.222.0.9
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-pretty
|
||||||
|
pretty prints json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel -pretty 10.222.0.9
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.9
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel 10.222.0.250
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel -json 10.222.0.250
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-pretty
|
||||||
|
pretty prints json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-tunnel -pretty 10.222.0.250
|
||||||
|
Could not find tunnel for vpn addr: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-relays
|
||||||
|
{"Relays":null}
|
||||||
|
|
||||||
|
$ print-relays -json
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-pretty
|
||||||
|
pretty prints json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ print-relays -pretty
|
||||||
|
{
|
||||||
|
"Relays": null
|
||||||
|
}
|
||||||
|
|
||||||
|
$ query-lighthouse
|
||||||
|
No vpn address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse -json
|
||||||
|
The provided vpn address could not be parsed: -json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse -pretty
|
||||||
|
The provided vpn address could not be parsed: -pretty
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse 10.222.0.9
|
||||||
|
{}
|
||||||
|
|
||||||
|
$ query-lighthouse -json 10.222.0.9
|
||||||
|
The provided vpn address could not be parsed: -json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse -pretty 10.222.0.9
|
||||||
|
The provided vpn address could not be parsed: -pretty
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse not-an-address
|
||||||
|
The provided vpn address could not be parsed: not-an-address
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse -json not-an-address
|
||||||
|
The provided vpn address could not be parsed: -json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ query-lighthouse -pretty not-an-address
|
||||||
|
The provided vpn address could not be parsed: -pretty
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -json
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -pretty
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level debug
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -json debug
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -pretty debug
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level bogus
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -json bogus
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -pretty bogus
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level info
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -json info
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-level -pretty info
|
||||||
|
Log level is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format -json
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format -pretty
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format json
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format -json json
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format -pretty json
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format text
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format -json text
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ log-format -pretty text
|
||||||
|
Log format is not reconfigurable on this logger
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote
|
||||||
|
No vpn address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -json
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -pretty
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote 10.222.0.9
|
||||||
|
No address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -json 10.222.0.9
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -pretty 10.222.0.9
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -address 10.94.0.10:4242 10.222.0.9
|
||||||
|
Could not find tunnel for vpn address: 10.222.0.9
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -json -address 10.94.0.10:4242 10.222.0.9
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -pretty -address 10.94.0.10:4242 10.222.0.9
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -address 10.94.0.10:4242 10.222.0.250
|
||||||
|
Could not find tunnel for vpn address: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -json -address 10.94.0.10:4242 10.222.0.250
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ change-remote -pretty -address 10.94.0.10:4242 10.222.0.250
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
The new remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel
|
||||||
|
No vpn address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -json
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -pretty
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel 10.222.0.9
|
||||||
|
Tunnel already handshaking
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -json 10.222.0.9
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -pretty 10.222.0.9
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -address 10.94.0.10:4242 10.222.0.10
|
||||||
|
Created
|
||||||
|
|
||||||
|
$ create-tunnel -json -address 10.94.0.10:4242 10.222.0.10
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -pretty -address 10.94.0.10:4242 10.222.0.10
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel not-an-address
|
||||||
|
The provided vpn address could not be parsed: not-an-address
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -json not-an-address
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ create-tunnel -pretty not-an-address
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-address string
|
||||||
|
Optionally provide a real remote address, ip:port
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel
|
||||||
|
No vpn address was provided
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel -json
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-local-only
|
||||||
|
Disables notifying the remote that the tunnel is shutting down
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel -pretty
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-local-only
|
||||||
|
Disables notifying the remote that the tunnel is shutting down
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel 10.222.0.250
|
||||||
|
Could not find tunnel for vpn address: 10.222.0.250
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel -json 10.222.0.250
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-local-only
|
||||||
|
Disables notifying the remote that the tunnel is shutting down
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel -pretty 10.222.0.250
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-local-only
|
||||||
|
Disables notifying the remote that the tunnel is shutting down
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel not-an-address
|
||||||
|
The provided vpn address could not be parsed: not-an-address
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel -json not-an-address
|
||||||
|
flag provided but not defined: -json
|
||||||
|
Usage:
|
||||||
|
-local-only
|
||||||
|
Disables notifying the remote that the tunnel is shutting down
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ close-tunnel -pretty not-an-address
|
||||||
|
flag provided but not defined: -pretty
|
||||||
|
Usage:
|
||||||
|
-local-only
|
||||||
|
Disables notifying the remote that the tunnel is shutting down
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ help
|
||||||
|
Available commands:
|
||||||
|
change-remote - Changes the remote address used in the tunnel for the provided vpn addr
|
||||||
|
close-tunnel - Closes a tunnel for the provided vpn addr
|
||||||
|
create-tunnel - Creates a tunnel for the provided vpn address
|
||||||
|
device-info - Prints information about the network device.
|
||||||
|
help - prints available commands or help <command> for specific usage info
|
||||||
|
list-hostmap - List all known previously connected hosts
|
||||||
|
list-lighthouse-addrmap - List all lighthouse map entries
|
||||||
|
list-pending-hostmap - List all handshaking hosts
|
||||||
|
log-format - Gets or sets the current log format
|
||||||
|
log-level - Gets or sets the current log level
|
||||||
|
logout - Ends the current session
|
||||||
|
print-cert - Prints the current certificate being used or the certificate for the provided vpn addr
|
||||||
|
print-relays - Prints json details about all relay info
|
||||||
|
print-tunnel - Prints json details about a tunnel for the provided vpn addr
|
||||||
|
query-lighthouse - Query the lighthouses for the provided vpn address
|
||||||
|
reload - Reloads configuration from disk, same as sending HUP to the process
|
||||||
|
version - Prints the currently running version of nebula
|
||||||
|
|
||||||
|
|
||||||
|
$ help -json
|
||||||
|
Command not available -json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ help -pretty
|
||||||
|
Command not available -pretty
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ help print-cert
|
||||||
|
print-cert - Prints the current certificate being used or the certificate for the provided vpn addr
|
||||||
|
-json
|
||||||
|
outputs as json
|
||||||
|
-pretty
|
||||||
|
pretty prints json, assumes -json
|
||||||
|
-raw
|
||||||
|
raw prints the PEM encoded certificate, not compatible with -json or -pretty
|
||||||
|
|
||||||
|
$ help -json print-cert
|
||||||
|
Command not available -json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ help -pretty print-cert
|
||||||
|
Command not available -pretty
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ help logout
|
||||||
|
logout - Ends the current session
|
||||||
|
|
||||||
|
$ help -json logout
|
||||||
|
Command not available -json
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ help -pretty logout
|
||||||
|
Command not available -pretty
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ logout -h
|
||||||
|
logout - Ends the current session
|
||||||
|
|
||||||
|
$ logout -json -h
|
||||||
|
logout - Ends the current session
|
||||||
|
|
||||||
|
$ logout -pretty -h
|
||||||
|
logout - Ends the current session
|
||||||
|
|
||||||
|
$ not-a-command 10.222.0.9
|
||||||
|
did not understand: not-a-command
|
||||||
|
Available commands:
|
||||||
|
change-remote - Changes the remote address used in the tunnel for the provided vpn addr
|
||||||
|
close-tunnel - Closes a tunnel for the provided vpn addr
|
||||||
|
create-tunnel - Creates a tunnel for the provided vpn address
|
||||||
|
device-info - Prints information about the network device.
|
||||||
|
help - prints available commands or help <command> for specific usage info
|
||||||
|
list-hostmap - List all known previously connected hosts
|
||||||
|
list-lighthouse-addrmap - List all lighthouse map entries
|
||||||
|
list-pending-hostmap - List all handshaking hosts
|
||||||
|
log-format - Gets or sets the current log format
|
||||||
|
log-level - Gets or sets the current log level
|
||||||
|
logout - Ends the current session
|
||||||
|
print-cert - Prints the current certificate being used or the certificate for the provided vpn addr
|
||||||
|
print-relays - Prints json details about all relay info
|
||||||
|
print-tunnel - Prints json details about a tunnel for the provided vpn addr
|
||||||
|
query-lighthouse - Query the lighthouses for the provided vpn address
|
||||||
|
reload - Reloads configuration from disk, same as sending HUP to the process
|
||||||
|
version - Prints the currently running version of nebula
|
||||||
|
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ not-a-command -json 10.222.0.9
|
||||||
|
did not understand: not-a-command
|
||||||
|
Available commands:
|
||||||
|
change-remote - Changes the remote address used in the tunnel for the provided vpn addr
|
||||||
|
close-tunnel - Closes a tunnel for the provided vpn addr
|
||||||
|
create-tunnel - Creates a tunnel for the provided vpn address
|
||||||
|
device-info - Prints information about the network device.
|
||||||
|
help - prints available commands or help <command> for specific usage info
|
||||||
|
list-hostmap - List all known previously connected hosts
|
||||||
|
list-lighthouse-addrmap - List all lighthouse map entries
|
||||||
|
list-pending-hostmap - List all handshaking hosts
|
||||||
|
log-format - Gets or sets the current log format
|
||||||
|
log-level - Gets or sets the current log level
|
||||||
|
logout - Ends the current session
|
||||||
|
print-cert - Prints the current certificate being used or the certificate for the provided vpn addr
|
||||||
|
print-relays - Prints json details about all relay info
|
||||||
|
print-tunnel - Prints json details about a tunnel for the provided vpn addr
|
||||||
|
query-lighthouse - Query the lighthouses for the provided vpn address
|
||||||
|
reload - Reloads configuration from disk, same as sending HUP to the process
|
||||||
|
version - Prints the currently running version of nebula
|
||||||
|
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ not-a-command -pretty 10.222.0.9
|
||||||
|
did not understand: not-a-command
|
||||||
|
Available commands:
|
||||||
|
change-remote - Changes the remote address used in the tunnel for the provided vpn addr
|
||||||
|
close-tunnel - Closes a tunnel for the provided vpn addr
|
||||||
|
create-tunnel - Creates a tunnel for the provided vpn address
|
||||||
|
device-info - Prints information about the network device.
|
||||||
|
help - prints available commands or help <command> for specific usage info
|
||||||
|
list-hostmap - List all known previously connected hosts
|
||||||
|
list-lighthouse-addrmap - List all lighthouse map entries
|
||||||
|
list-pending-hostmap - List all handshaking hosts
|
||||||
|
log-format - Gets or sets the current log format
|
||||||
|
log-level - Gets or sets the current log level
|
||||||
|
logout - Ends the current session
|
||||||
|
print-cert - Prints the current certificate being used or the certificate for the provided vpn addr
|
||||||
|
print-relays - Prints json details about all relay info
|
||||||
|
print-tunnel - Prints json details about a tunnel for the provided vpn addr
|
||||||
|
query-lighthouse - Query the lighthouses for the provided vpn address
|
||||||
|
reload - Reloads configuration from disk, same as sending HUP to the process
|
||||||
|
version - Prints the currently running version of nebula
|
||||||
|
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ reload
|
||||||
|
Reloading config
|
||||||
|
Config reload failed, the new config did not load: no config files found at
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ reload -json
|
||||||
|
Reloading config
|
||||||
|
Config reload failed, the new config did not load: no config files found at
|
||||||
|
exit status 1
|
||||||
|
|
||||||
|
$ reload -pretty
|
||||||
|
Reloading config
|
||||||
|
Config reload failed, the new config did not load: no config files found at
|
||||||
|
exit status 1
|
||||||
|
|
||||||
+2
-3
@@ -1,5 +1,4 @@
|
|||||||
//go:build e2e_testing
|
//go:build e2e_testing
|
||||||
// +build e2e_testing
|
|
||||||
|
|
||||||
package e2e
|
package e2e
|
||||||
|
|
||||||
@@ -130,7 +129,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 = myC.ReloadConfigString(string(cb)).Err
|
||||||
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()
|
||||||
@@ -223,7 +222,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 = myC.ReloadConfigString(string(cb)).Err
|
||||||
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()
|
||||||
|
|||||||
@@ -1,188 +0,0 @@
|
|||||||
package nebula
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"log/slog"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"golang.org/x/net/ipv4"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestInnerECN(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
pkt []byte
|
|
||||||
want byte
|
|
||||||
}{
|
|
||||||
{"empty", nil, 0},
|
|
||||||
{"v4_NotECT", v4WithToS(0x00), 0x00},
|
|
||||||
{"v4_ECT0", v4WithToS(0x02), 0x02},
|
|
||||||
{"v4_ECT1", v4WithToS(0x01), 0x01},
|
|
||||||
{"v4_CE", v4WithToS(0x03), 0x03},
|
|
||||||
{"v4_DSCP_then_NotECT", v4WithToS(0x88 | 0x00), 0x00},
|
|
||||||
{"v4_DSCP_then_CE", v4WithToS(0x88 | 0x03), 0x03},
|
|
||||||
{"v6_NotECT", v6WithTC(0x00), 0x00},
|
|
||||||
{"v6_ECT0", v6WithTC(0x02), 0x02},
|
|
||||||
{"v6_CE", v6WithTC(0x03), 0x03},
|
|
||||||
{"v6_DSCP_then_CE", v6WithTC(0x88 | 0x03), 0x03},
|
|
||||||
{"unknown_version", []byte{0xa5, 0xff}, 0},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
t.Run(c.name, func(t *testing.T) {
|
|
||||||
got := innerECN(c.pkt)
|
|
||||||
if got != c.want {
|
|
||||||
t.Errorf("innerECN=0x%02x want 0x%02x", got, c.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// v4WithToS returns a 2-byte slice tall enough for innerECN: byte 0 carries
|
|
||||||
// version=4 in the high nibble, byte 1 is the full ToS so we exercise both
|
|
||||||
// the DSCP and ECN portions through the byte 1 mask.
|
|
||||||
func v4WithToS(tos byte) []byte {
|
|
||||||
return []byte{0x45, tos}
|
|
||||||
}
|
|
||||||
|
|
||||||
// v6WithTC builds a 2-byte slice that places a known traffic class value
|
|
||||||
// across bytes 0 (high nibble of TC) and 1 (low nibble of TC). innerECN
|
|
||||||
// extracts ECN as (b[1]>>4)&0x03, which corresponds to TC[1:0].
|
|
||||||
func v6WithTC(tc byte) []byte {
|
|
||||||
return []byte{0x60 | (tc>>4)&0x0f, (tc & 0x0f) << 4}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestApplyOuterECN(t *testing.T) {
|
|
||||||
silent := slog.New(slog.DiscardHandler)
|
|
||||||
hi := &HostInfo{}
|
|
||||||
|
|
||||||
// Build a v4 packet helper with a given inner ECN field.
|
|
||||||
v4 := func(innerECN byte) []byte {
|
|
||||||
// 20-byte minimal IPv4 header with ToS = innerECN (DSCP zeroed).
|
|
||||||
return []byte{
|
|
||||||
0x45, innerECN, 0, 28,
|
|
||||||
0, 0, 0x40, 0,
|
|
||||||
64, 6, 0, 0,
|
|
||||||
10, 0, 0, 1,
|
|
||||||
10, 0, 0, 2,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Build a v6 packet helper with a given inner ECN field. ECN occupies
|
|
||||||
// TC[1:0] which sit at byte 1 mask 0x30.
|
|
||||||
v6 := func(innerECN byte) []byte {
|
|
||||||
// 40-byte minimal IPv6 header with TC[1:0] = innerECN.
|
|
||||||
pkt := make([]byte, 40)
|
|
||||||
pkt[0] = 0x60 // version=6, TC[7:4]=0
|
|
||||||
pkt[1] = (innerECN & 0x03) << 4 // TC[3:0]: low 2 bits = ECN, top 2 = DSCP-low (0)
|
|
||||||
return pkt
|
|
||||||
}
|
|
||||||
|
|
||||||
type cell struct {
|
|
||||||
outer byte
|
|
||||||
inner byte
|
|
||||||
wantECN byte
|
|
||||||
wantSame bool // expect inner unchanged (true => verify the byte didn't move)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RFC 6040 normal-mode combine table. Only outer==CE causes mutation.
|
|
||||||
table := []cell{
|
|
||||||
{ecnNotECT, ecnNotECT, ecnNotECT, true},
|
|
||||||
{ecnNotECT, ecnECT0, ecnECT0, true},
|
|
||||||
{ecnNotECT, ecnECT1, ecnECT1, true},
|
|
||||||
{ecnNotECT, ecnCE, ecnCE, true},
|
|
||||||
|
|
||||||
{ecnECT0, ecnNotECT, ecnNotECT, true},
|
|
||||||
{ecnECT0, ecnECT0, ecnECT0, true},
|
|
||||||
{ecnECT0, ecnECT1, ecnECT1, true},
|
|
||||||
{ecnECT0, ecnCE, ecnCE, true},
|
|
||||||
|
|
||||||
{ecnECT1, ecnNotECT, ecnNotECT, true},
|
|
||||||
{ecnECT1, ecnECT0, ecnECT0, true},
|
|
||||||
{ecnECT1, ecnECT1, ecnECT1, true},
|
|
||||||
{ecnECT1, ecnCE, ecnCE, true},
|
|
||||||
|
|
||||||
{ecnCE, ecnNotECT, ecnNotECT, true}, // legacy: log, leave alone
|
|
||||||
{ecnCE, ecnECT0, ecnCE, false}, // CE folded in
|
|
||||||
{ecnCE, ecnECT1, ecnCE, false},
|
|
||||||
{ecnCE, ecnCE, ecnCE, true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range table {
|
|
||||||
t.Run("v4", func(t *testing.T) {
|
|
||||||
pkt := v4(c.inner)
|
|
||||||
applyOuterECN(pkt, c.outer, hi, silent)
|
|
||||||
got := pkt[1] & 0x03
|
|
||||||
if got != c.wantECN {
|
|
||||||
t.Errorf("v4 outer=0x%02x inner=0x%02x: got 0x%02x want 0x%02x", c.outer, c.inner, got, c.wantECN)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.Run("v6", func(t *testing.T) {
|
|
||||||
pkt := v6(c.inner)
|
|
||||||
applyOuterECN(pkt, c.outer, hi, silent)
|
|
||||||
got := (pkt[1] >> 4) & 0x03
|
|
||||||
if got != c.wantECN {
|
|
||||||
t.Errorf("v6 outer=0x%02x inner=0x%02x: got 0x%02x want 0x%02x", c.outer, c.inner, got, c.wantECN)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestApplyOuterECN_IPv4ChecksumStaysValid guards against H1: folding an outer
|
|
||||||
// CE mark into the inner IPv4 ToS byte must keep the IPv4 header checksum valid.
|
|
||||||
// The passthrough emit paths write the packet verbatim, so a stale checksum
|
|
||||||
// turns an underlay congestion mark into packet loss at the receiver.
|
|
||||||
func TestApplyOuterECN_IPv4ChecksumStaysValid(t *testing.T) {
|
|
||||||
silent := slog.New(slog.DiscardHandler)
|
|
||||||
hi := &HostInfo{}
|
|
||||||
|
|
||||||
// 20-byte IPv4 header with DSCP=0x88 and inner ECN = ECT(0). Folding CE
|
|
||||||
// flips only the low two bits of the ToS byte while leaving DSCP intact.
|
|
||||||
pkt := []byte{
|
|
||||||
0x45, 0x88 | ecnECT0, 0, 40,
|
|
||||||
0x1c, 0x46, 0x40, 0x00,
|
|
||||||
64, 6, 0, 0,
|
|
||||||
10, 0, 0, 1,
|
|
||||||
10, 0, 0, 2,
|
|
||||||
}
|
|
||||||
// Stamp a correct header checksum before the fold.
|
|
||||||
binary.BigEndian.PutUint16(pkt[10:12], ipv4HeaderChecksum(pkt[:ipv4.HeaderLen]))
|
|
||||||
if !ipv4HeaderChecksumValid(pkt[:ipv4.HeaderLen]) {
|
|
||||||
t.Fatal("test setup: initial header checksum invalid")
|
|
||||||
}
|
|
||||||
|
|
||||||
applyOuterECN(pkt, ecnCE, hi, silent)
|
|
||||||
|
|
||||||
// CE folded in, DSCP preserved.
|
|
||||||
if got, want := pkt[1], byte(0x88|ecnCE); got != want {
|
|
||||||
t.Fatalf("ToS after fold = 0x%02x, want 0x%02x", got, want)
|
|
||||||
}
|
|
||||||
// The incremental RFC 1624 update must leave the checksum valid and equal
|
|
||||||
// to a full recompute over the mutated header.
|
|
||||||
if !ipv4HeaderChecksumValid(pkt[:ipv4.HeaderLen]) {
|
|
||||||
t.Fatalf("IPv4 header checksum invalid after CE fold: 0x%04x", binary.BigEndian.Uint16(pkt[10:12]))
|
|
||||||
}
|
|
||||||
if got, want := binary.BigEndian.Uint16(pkt[10:12]), ipv4HeaderChecksum(pkt[:ipv4.HeaderLen]); got != want {
|
|
||||||
t.Fatalf("checksum = 0x%04x, full recompute = 0x%04x", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ipv4HeaderChecksum computes the RFC 1071 IPv4 header checksum over hdr,
|
|
||||||
// treating the checksum field (bytes 10:12) as zero.
|
|
||||||
func ipv4HeaderChecksum(hdr []byte) uint16 {
|
|
||||||
var sum uint32
|
|
||||||
for i := 0; i+1 < len(hdr); i += 2 {
|
|
||||||
if i == 10 {
|
|
||||||
continue // checksum field
|
|
||||||
}
|
|
||||||
sum += uint32(hdr[i])<<8 | uint32(hdr[i+1])
|
|
||||||
}
|
|
||||||
for sum > 0xffff {
|
|
||||||
sum = (sum >> 16) + (sum & 0xffff)
|
|
||||||
}
|
|
||||||
return ^uint16(sum)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ipv4HeaderChecksumValid reports whether the stored checksum matches a fresh
|
|
||||||
// computation over the header.
|
|
||||||
func ipv4HeaderChecksumValid(hdr []byte) bool {
|
|
||||||
return binary.BigEndian.Uint16(hdr[10:12]) == ipv4HeaderChecksum(hdr)
|
|
||||||
}
|
|
||||||
+55
-40
@@ -8,6 +8,7 @@ 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.
|
||||||
@@ -43,7 +44,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
|
# you have configured to be lighthouses in your network. Not reloadable.
|
||||||
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
|
||||||
@@ -126,18 +127,23 @@ 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"
|
# To listen on only ipv4, use "0.0.0.0". Not reloadable.
|
||||||
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: 10485760
|
read_buffer: 3412512
|
||||||
#write_buffer: 10485760
|
write_buffer: 3412512
|
||||||
|
|
||||||
# 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.
|
||||||
@@ -146,6 +152,14 @@ listen:
|
|||||||
# Default true; set to false to leave WDF in charge of inbound decisions on the listener port. Not reloadable.
|
# Default true; set to false to leave WDF in charge of inbound decisions on the listener port. Not reloadable.
|
||||||
#windows_bypass_wdf: true
|
#windows_bypass_wdf: true
|
||||||
|
|
||||||
|
# On macOS only
|
||||||
|
# macOS scopes the udp socket to the interface it was created on, so moving between networks (wifi to wired,
|
||||||
|
# office to home) leaves Nebula sending out an interface that no longer has a route. When true, Nebula watches
|
||||||
|
# the routing socket and rebinds the listener once the change settles.
|
||||||
|
# iOS does not use this, the host app drives the same rebind itself.
|
||||||
|
# Default true. Not reloadable.
|
||||||
|
#rebind_on_network_change: true
|
||||||
|
|
||||||
# By default, Nebula replies to packets it has no tunnel for with a "recv_error" packet. This packet helps speed up reconnection
|
# By default, Nebula replies to packets it has no tunnel for with a "recv_error" packet. This packet helps speed up reconnection
|
||||||
# in the case that Nebula on either side did not shut down cleanly. This response can be abused as a way to discover if Nebula is running
|
# in the case that Nebula on either side did not shut down cleanly. This response can be abused as a way to discover if Nebula is running
|
||||||
# on a host though. This option lets you configure if you want to send "recv_error" packets always, never, or only to private network remotes.
|
# on a host though. This option lets you configure if you want to send "recv_error" packets always, never, or only to private network remotes.
|
||||||
@@ -161,12 +175,14 @@ 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.
|
# This option is only supported on Linux. Not reloadable.
|
||||||
#routines: 1
|
#routines: 1
|
||||||
|
|
||||||
punchy:
|
punchy:
|
||||||
@@ -190,6 +206,7 @@ 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
|
||||||
@@ -216,12 +233,6 @@ 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,
|
|
||||||
# save-mutex-profile) to the specified directory. Relative paths will be resolved within this directory,
|
|
||||||
# and absolute paths outside of it will be rejected. Default is $TMP/nebula-debug.
|
|
||||||
# The directory is NOT automatically created.
|
|
||||||
# Overriding this to "" is the same as "/" and will allow overwriting any path on the host.
|
|
||||||
#sandbox_dir: /var/tmp/nebula-debug
|
|
||||||
|
|
||||||
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
||||||
relay:
|
relay:
|
||||||
@@ -240,38 +251,50 @@ 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 NetBSD: Required to be set, must be in the form `tun[0-9]+`
|
# For OpenBSD and NetBSD: if set, must be in the form `tun[0-9]+`, otherwise the first free one is used.
|
||||||
|
# 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
|
# Toggles forwarding of multicast packets. Not reloadable.
|
||||||
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 500
|
# 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
|
||||||
tx_queue: 500
|
# Not reloadable.
|
||||||
|
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
|
# 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
|
# 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.
|
# instead of being sprayed across multiple TX rings and reordered. Not reloadable. Coerced to false if routines <= 1.
|
||||||
#
|
|
||||||
# When cpu_affinity is unset, nebula picks CPUs that do NOT service any physical NIC's interrupts (read from
|
|
||||||
# /sys/class/net/*/device/msi_irqs and /proc/irq/*/effective_affinity_list): an encrypt thread pinned onto a core
|
|
||||||
# that also runs NAPI for a NIC RX queue fights the softirq for the core and collapses throughput for flows hashed
|
|
||||||
# to that queue. If the NIC's vectors blanket every allowed CPU (many drivers default to one queue per core) the
|
|
||||||
# avoidance logs and falls back to the old spread; narrow the NIC's queue/IRQ spread (e.g. `ethtool -X <dev>
|
|
||||||
# equal N`) or set cpu_affinity explicitly to benefit.
|
|
||||||
#pin_threads: true
|
#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
|
# 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
|
# (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;
|
# 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 and falls back to spreading queues across the allowed
|
# a non-integer or not-allowed entry disables the override, leaving the default pin selection described below.
|
||||||
# CPUs. Setting this disables the automatic NIC-IRQ avoidance described under pin_threads — prefer CPUs that don't
|
# Only meaningful while pin_threads is true. Not reloadable.
|
||||||
# service your underlay NIC's RX queue IRQs. 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:
|
#cpu_affinity:
|
||||||
# - 2
|
# - 2
|
||||||
# - 4
|
# - 4
|
||||||
@@ -339,7 +362,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
|
# SO_RCVBUFFORCE is used to avoid having to raise the system wide max. Not reloadable.
|
||||||
#use_system_route_table_buffer_size: 0
|
#use_system_route_table_buffer_size: 0
|
||||||
|
|
||||||
# Configure logging level
|
# Configure logging level
|
||||||
@@ -389,14 +412,16 @@ 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
|
# query_buffer is the size of the buffer channel for querying lighthouses, drops are recorded in the lighthouse.query.dropped metric.
|
||||||
#query_buffer: 64
|
# Not reloadable.
|
||||||
|
#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
|
# after receiving the response for lighthouse queries. Not reloadable.
|
||||||
#trigger_buffer: 64
|
#trigger_buffer: 64
|
||||||
|
|
||||||
# Tunnel manager settings
|
# Tunnel manager settings
|
||||||
@@ -412,16 +437,6 @@ logging:
|
|||||||
# This setting is reloadable
|
# This setting is reloadable
|
||||||
#inactivity_timeout: 10m
|
#inactivity_timeout: 10m
|
||||||
|
|
||||||
# ecn (default true) propagates ECN (Explicit Congestion Notification) across the tunnel per RFC 6040: the inner
|
|
||||||
# packet's ECN codepoint is copied onto the outer carrier header on encapsulation, and an outer CE ("congestion
|
|
||||||
# experienced") mark is folded back into the inner header on decapsulation. On linux it additionally stamps
|
|
||||||
# RTAX_FEATURE_ECN on the routes nebula installs, so the kernel actively negotiates ECN for connections to mesh
|
|
||||||
# prefixes. Disable this only when an underlay middlebox mangles or clears ECN bits unpredictably.
|
|
||||||
# This setting is reloadable, BUT flipping it at runtime only updates the datapath (the inner<->outer copy/combine).
|
|
||||||
# The RTAX_FEATURE_ECN flag on already-installed routes is NOT revisited on reload, so nebula must be restarted for
|
|
||||||
# the route half of this setting to take effect.
|
|
||||||
#ecn: true
|
|
||||||
|
|
||||||
# Nebula security group configuration
|
# Nebula security group configuration
|
||||||
firewall:
|
firewall:
|
||||||
# Action to take when a packet is not allowed by the firewall rules.
|
# Action to take when a packet is not allowed by the firewall rules.
|
||||||
|
|||||||
@@ -8,6 +8,15 @@ Before=sshd.service
|
|||||||
Type=notify
|
Type=notify
|
||||||
NotifyAccess=main
|
NotifyAccess=main
|
||||||
SyslogIdentifier=nebula
|
SyslogIdentifier=nebula
|
||||||
|
|
||||||
|
# Uncomment to run as an unprivileged user with only CAP_NET_ADMIN. Requires a
|
||||||
|
# nebula user that owns the config directory. Add CAP_NET_BIND_SERVICE to both
|
||||||
|
# lines if any listener (lighthouse DNS, listen.port, stats, sshd) binds <1024.
|
||||||
|
#User=nebula
|
||||||
|
#Group=nebula
|
||||||
|
#CapabilityBoundingSet=CAP_NET_ADMIN
|
||||||
|
#AmbientCapabilities=CAP_NET_ADMIN
|
||||||
|
|
||||||
ExecReload=/bin/kill -HUP $MAINPID
|
ExecReload=/bin/kill -HUP $MAINPID
|
||||||
ExecStart=/usr/local/bin/nebula -config /etc/nebula/config.yml
|
ExecStart=/usr/local/bin/nebula -config /etc/nebula/config.yml
|
||||||
Restart=always
|
Restart=always
|
||||||
|
|||||||
+15
-14
@@ -21,6 +21,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/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
|
"github.com/slackhq/nebula/iputil"
|
||||||
)
|
)
|
||||||
|
|
||||||
type FirewallInterface interface {
|
type FirewallInterface interface {
|
||||||
@@ -262,11 +263,11 @@ func (f *Firewall) AddRule(incoming bool, proto uint8, startPort int32, endPort
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch proto {
|
switch proto {
|
||||||
case firewall.ProtoTCP:
|
case iputil.IPProtocolTCP:
|
||||||
fp = ft.TCP
|
fp = ft.TCP
|
||||||
case firewall.ProtoUDP:
|
case iputil.IPProtocolUDP:
|
||||||
fp = ft.UDP
|
fp = ft.UDP
|
||||||
case firewall.ProtoICMP, firewall.ProtoICMPv6:
|
case iputil.IPProtocolICMP, iputil.IPProtocolICMPv6:
|
||||||
//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)
|
||||||
@@ -364,13 +365,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 = firewall.ProtoTCP
|
proto = iputil.IPProtocolTCP
|
||||||
startPort, endPort, err = parsePort(sPort)
|
startPort, endPort, err = parsePort(sPort)
|
||||||
case "udp":
|
case "udp":
|
||||||
proto = firewall.ProtoUDP
|
proto = iputil.IPProtocolUDP
|
||||||
startPort, endPort, err = parsePort(sPort)
|
startPort, endPort, err = parsePort(sPort)
|
||||||
case "icmp":
|
case "icmp":
|
||||||
proto = firewall.ProtoICMP
|
proto = iputil.IPProtocolICMP
|
||||||
startPort = firewall.PortAny
|
startPort = firewall.PortAny
|
||||||
endPort = firewall.PortAny
|
endPort = firewall.PortAny
|
||||||
if sPort != "" {
|
if sPort != "" {
|
||||||
@@ -560,9 +561,9 @@ func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool,
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch fp.Protocol {
|
switch fp.Protocol {
|
||||||
case firewall.ProtoTCP:
|
case iputil.IPProtocolTCP:
|
||||||
c.Expires = time.Now().Add(f.TCPTimeout)
|
c.Expires = time.Now().Add(f.TCPTimeout)
|
||||||
case firewall.ProtoUDP:
|
case iputil.IPProtocolUDP:
|
||||||
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)
|
||||||
@@ -582,9 +583,9 @@ func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
|
|||||||
c := &conn{}
|
c := &conn{}
|
||||||
|
|
||||||
switch fp.Protocol {
|
switch fp.Protocol {
|
||||||
case firewall.ProtoTCP:
|
case iputil.IPProtocolTCP:
|
||||||
timeout = f.TCPTimeout
|
timeout = f.TCPTimeout
|
||||||
case firewall.ProtoUDP:
|
case iputil.IPProtocolUDP:
|
||||||
timeout = f.UDPTimeout
|
timeout = f.UDPTimeout
|
||||||
default:
|
default:
|
||||||
timeout = f.DefaultTimeout
|
timeout = f.DefaultTimeout
|
||||||
@@ -635,15 +636,15 @@ func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedC
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch p.Protocol {
|
switch p.Protocol {
|
||||||
case firewall.ProtoTCP:
|
case iputil.IPProtocolTCP:
|
||||||
if ft.TCP.match(p, incoming, c, caPool) {
|
if ft.TCP.match(p, incoming, c, caPool) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
case firewall.ProtoUDP:
|
case iputil.IPProtocolUDP:
|
||||||
if ft.UDP.match(p, incoming, c, caPool) {
|
if ft.UDP.match(p, incoming, c, caPool) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
case firewall.ProtoICMP, firewall.ProtoICMPv6:
|
case iputil.IPProtocolICMP, iputil.IPProtocolICMPv6:
|
||||||
if ft.ICMP.match(p, incoming, c, caPool) {
|
if ft.ICMP.match(p, incoming, c, caPool) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -680,7 +681,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 == firewall.ProtoICMP || p.Protocol == firewall.ProtoICMPv6 {
|
if p.Protocol == iputil.IPProtocolICMP || p.Protocol == iputil.IPProtocolICMPv6 {
|
||||||
// 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)
|
||||||
|
|||||||
@@ -22,7 +22,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 := 0; i < cacheLen; i++ {
|
for i := range cacheLen {
|
||||||
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
|
||||||
|
|||||||
+15
-9
@@ -4,17 +4,14 @@ 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`
|
||||||
)
|
)
|
||||||
@@ -45,13 +42,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 ProtoTCP:
|
case iputil.IPProtocolTCP:
|
||||||
proto = "tcp"
|
proto = "tcp"
|
||||||
case ProtoICMP:
|
case iputil.IPProtocolICMP:
|
||||||
proto = "icmp"
|
proto = "icmp"
|
||||||
case ProtoICMPv6:
|
case iputil.IPProtocolICMPv6:
|
||||||
proto = "icmpv6"
|
proto = "icmpv6"
|
||||||
case ProtoUDP:
|
case iputil.IPProtocolUDP:
|
||||||
proto = "udp"
|
proto = "udp"
|
||||||
default:
|
default:
|
||||||
proto = fmt.Sprintf("unknown %v", fp.Protocol)
|
proto = fmt.Sprintf("unknown %v", fp.Protocol)
|
||||||
@@ -65,3 +62,12 @@ 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
|
||||||
|
}
|
||||||
+34
-33
@@ -13,6 +13,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/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"
|
||||||
@@ -72,20 +73,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, firewall.ProtoTCP, 1, 1, []string{}, "", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, iputil.IPProtocolTCP, 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, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 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, firewall.ProtoICMP, 1, 1, []string{}, "h1", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, iputil.IPProtocolICMP, 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)
|
||||||
@@ -116,11 +117,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, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", "", "", "ca-name", ""))
|
require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 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, firewall.ProtoUDP, 1, 1, []string{"g1"}, "", "", "", "", "ca-sha"))
|
require.NoError(t, fw.AddRule(true, iputil.IPProtocolUDP, 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)
|
||||||
@@ -185,7 +186,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +264,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,7 +351,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: firewall.ProtoUDP}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolUDP}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -360,7 +361,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: firewall.ProtoTCP, LocalPort: 1}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 1}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -370,7 +371,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: firewall.ProtoTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, 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) {
|
||||||
@@ -379,7 +380,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: firewall.ProtoTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: ip.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -392,7 +393,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: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, 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) {
|
||||||
@@ -404,7 +405,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: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -417,7 +418,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: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, 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) {
|
||||||
@@ -429,7 +430,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: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
assert.False(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -441,7 +442,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: firewall.ProtoTCP, LocalPort: 10}, true, c, cp))
|
assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -453,7 +454,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: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix.Addr()}, true, c, cp))
|
assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, 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) {
|
||||||
@@ -464,7 +465,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: firewall.ProtoTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
assert.True(b, ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 100, LocalAddr: pfix6.Addr()}, true, c, cp))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -476,7 +477,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: firewall.ProtoTCP, LocalPort: 10}, true, c, cp)
|
ft.match(firewall.Packet{Protocol: iputil.IPProtocolTCP, LocalPort: 10}, true, c, cp)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -492,7 +493,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -550,7 +551,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,7 +639,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -675,7 +676,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
network := netip.MustParsePrefix("1.2.3.4/24")
|
network := netip.MustParsePrefix("1.2.3.4/24")
|
||||||
@@ -758,13 +759,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: firewall.ProtoICMP,
|
Protocol: iputil.IPProtocolICMP,
|
||||||
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, firewall.ProtoICMP, 0, 0, []string{"any"}, "", "", "", "", ""))
|
require.NoError(t, fw.AddRule(true, iputil.IPProtocolICMP, 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
|
||||||
@@ -910,7 +911,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
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)
|
||||||
@@ -961,7 +962,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
|
require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
|
||||||
@@ -1031,7 +1032,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
@@ -1317,28 +1318,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: firewall.ProtoTCP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolTCP, 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: firewall.ProtoUDP, startPort: 1, endPort: 1, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolUDP, 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: firewall.ProtoICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolICMP, 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: firewall.ProtoICMP, startPort: firewall.PortAny, endPort: firewall.PortAny, groups: nil, host: "a", ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: false, proto: iputil.IPProtocolICMP, 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())
|
||||||
@@ -1582,7 +1583,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: firewall.ProtoUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
return testcase{
|
return testcase{
|
||||||
|
|||||||
@@ -1,56 +1,49 @@
|
|||||||
module github.com/slackhq/nebula
|
module github.com/slackhq/nebula
|
||||||
|
|
||||||
go 1.25.0
|
go 1.27.2
|
||||||
|
|
||||||
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/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.28.0
|
github.com/gaissmai/bart v0.29.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.72
|
github.com/miekg/dns v1.1.73
|
||||||
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.23.2
|
github.com/prometheus/client_golang v1.24.1
|
||||||
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.11.1
|
github.com/stretchr/testify v1.12.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.4
|
go.yaml.in/yaml/v3 v3.0.5
|
||||||
golang.org/x/crypto v0.53.0
|
golang.org/x/crypto v0.57.0
|
||||||
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090
|
golang.org/x/net v0.59.0
|
||||||
golang.org/x/net v0.56.0
|
golang.org/x/sync v0.23.0
|
||||||
golang.org/x/sync v0.21.0
|
golang.org/x/sys v0.48.0
|
||||||
golang.org/x/sys v0.46.0
|
golang.org/x/term v0.46.0
|
||||||
golang.org/x/term v0.44.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.11
|
google.golang.org/protobuf v1.36.12
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe
|
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980
|
||||||
)
|
)
|
||||||
|
|
||||||
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.66.1 // indirect
|
github.com/prometheus/common v0.70.1 // indirect
|
||||||
github.com/prometheus/procfs v0.16.1 // indirect
|
github.com/prometheus/procfs v0.21.1 // indirect
|
||||||
github.com/vishvananda/netns v0.0.5 // indirect
|
github.com/vishvananda/netns v0.0.5 // indirect
|
||||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc // indirect
|
||||||
golang.org/x/mod v0.36.0 // indirect
|
golang.org/x/time v0.15.0 // indirect
|
||||||
golang.org/x/time v0.5.0 // indirect
|
|
||||||
golang.org/x/tools v0.45.0 // indirect
|
|
||||||
)
|
)
|
||||||
@@ -3,6 +3,8 @@ 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/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=
|
||||||
@@ -10,8 +12,6 @@ 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=
|
||||||
@@ -19,15 +19,12 @@ 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.28.0 h1:89yZLo8NmyqD0RYgJ3QO9HhqqGGw+oWhf90cZm69Lko=
|
github.com/gaissmai/bart v0.29.0 h1:wO6HGE8g9YE0Wm0bCpYxwRzfQ4+fbJKOhL64e5ACGCI=
|
||||||
github.com/gaissmai/bart v0.28.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
|
github.com/gaissmai/bart v0.29.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=
|
||||||
@@ -70,23 +67,22 @@ 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.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||||
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.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
||||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||||
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=
|
||||||
@@ -102,14 +98,13 @@ 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.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||||
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=
|
||||||
@@ -118,18 +113,16 @@ 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.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||||
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.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||||
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=
|
||||||
@@ -143,35 +136,31 @@ 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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||||
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.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
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.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||||
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 h1:Di6/M8l0O2lCLc6VVRWhgCiApHV8MnQurBnFSHsQtNY=
|
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc h1:TS73t7x3KarrNd5qAipmspBDS1rkMcgVG/fS1aRb4Rc=
|
||||||
golang.org/x/exp v0.0.0-20230725093048-515e97ebf090/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
|
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
|
||||||
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=
|
||||||
@@ -182,8 +171,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.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||||
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=
|
||||||
@@ -191,8 +180,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.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
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=
|
||||||
@@ -206,25 +195,21 @@ 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.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
|
||||||
golang.org/x/sys v0.46.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.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||||
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.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||||
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||||
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=
|
||||||
@@ -243,8 +228,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.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
google.golang.org/protobuf v1.36.12/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=
|
||||||
@@ -258,5 +243,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-20240423190808-9d7a357edefe h1:fre4i6mv4iBuz5lCMOzHD1rH1ljqHWSICFmZRbbgp3g=
|
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980 h1:ribyrTYQ/QYeUIs8x8bVLYwGyepa7RnHLqJzegT5YYk=
|
||||||
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe/go.mod h1:sxc3Uvk/vHcd3tj7/DHVBoR5wvWT/MmRq2pj7HRJnwU=
|
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980/go.mod h1:pK/dapF5Bf3KGW7/kd5CI5IC4lYh9FMFY1qETAIGLXk=
|
||||||
+130
@@ -0,0 +1,130 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
+36
-17
@@ -54,7 +54,8 @@ 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
|
||||||
@@ -259,14 +260,6 @@ 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)
|
||||||
|
|
||||||
@@ -295,7 +288,13 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
|||||||
hm.messageMetrics.Tx(header.Handshake, hh.machine.Subtype(), 1)
|
hm.messageMetrics.Tx(header.Handshake, hh.machine.Subtype(), 1)
|
||||||
err := hm.outside.WriteTo(stage0, addr)
|
err := hm.outside.WriteTo(stage0, addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
hostinfo.logger(hm.l).Error("Failed to send handshake message",
|
// These repeat every attempt, so match the success log below and only shout when the remotes changed
|
||||||
|
level := slog.LevelDebug
|
||||||
|
if remotesHaveChanged {
|
||||||
|
level = slog.LevelError
|
||||||
|
}
|
||||||
|
|
||||||
|
hostinfo.logger(hm.l).Log(context.Background(), level, "Failed to send handshake message",
|
||||||
"udpAddr", addr,
|
"udpAddr", addr,
|
||||||
"initiatorIndex", hostinfo.localIndexId,
|
"initiatorIndex", hostinfo.localIndexId,
|
||||||
"handshake", hsFields,
|
"handshake", hsFields,
|
||||||
@@ -365,6 +364,9 @@ 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{},
|
||||||
@@ -529,8 +531,10 @@ func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
|
|||||||
|
|
||||||
func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
|
func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
|
||||||
for _, addr := range hostinfo.vpnAddrs {
|
for _, addr := range hostinfo.vpnAddrs {
|
||||||
|
if cur, ok := hm.vpnIps[addr]; ok && cur.hostinfo == hostinfo {
|
||||||
delete(hm.vpnIps, addr)
|
delete(hm.vpnIps, addr)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(hm.vpnIps) == 0 {
|
if len(hm.vpnIps) == 0 {
|
||||||
hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
|
hm.vpnIps = map[netip.Addr]*HandshakeHostInfo{}
|
||||||
@@ -741,8 +745,14 @@ 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: newConnectionStateFromResult(result),
|
ConnectionState: connState,
|
||||||
localIndexId: result.LocalIndex,
|
localIndexId: result.LocalIndex,
|
||||||
remoteIndexId: result.RemoteIndex,
|
remoteIndexId: result.RemoteIndex,
|
||||||
vpnAddrs: vpnAddrs,
|
vpnAddrs: vpnAddrs,
|
||||||
@@ -860,7 +870,13 @@ 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.
|
||||||
hostinfo.ConnectionState = newConnectionStateFromResult(result)
|
cs, err := 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 {
|
||||||
@@ -926,13 +942,14 @@ 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{}
|
||||||
|
})
|
||||||
|
// 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
|
hostinfo.vpnAddrs = vpnAddrs
|
||||||
f.sendCloseTunnel(hostinfo)
|
f.sendCloseTunnel(hostinfo)
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -967,7 +984,9 @@ 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 sendbatcher
|
// 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)))
|
||||||
@@ -1078,8 +1097,8 @@ func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hos
|
|||||||
hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
|
hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
|
||||||
// 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.remoteIdx, Established)
|
via.relayHI.relayState.UpdateRelayForByIdxState(via.relay.LocalIndex, Established)
|
||||||
f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false)
|
f.SendVia(via.relayHI, via.relay, msg, make([]byte, 12), make([]byte, mtu), false, 0)
|
||||||
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])...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"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) {
|
||||||
@@ -42,8 +43,6 @@ 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)
|
||||||
|
|
||||||
@@ -84,7 +83,7 @@ func (mw *mockEncWriter) SendMessageToVpnAddr(_ header.MessageType, _ header.Mes
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mw *mockEncWriter) SendVia(_ *HostInfo, _ *Relay, _, _, _ []byte, _ bool) {
|
func (mw *mockEncWriter) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,3 +234,70 @@ 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")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
+16
-6
@@ -24,6 +24,11 @@ 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
|
||||||
@@ -190,13 +195,18 @@ func SubTypeName(t MessageType, s MessageSubType) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func IsValidSubType(t MessageType, s MessageSubType) bool {
|
func IsValidSubType(t MessageType, s MessageSubType) bool {
|
||||||
if n, ok := subTypeMap[t]; ok {
|
switch t {
|
||||||
if _, ok := (*n)[s]; ok {
|
case Message:
|
||||||
return true
|
return s == MessageNone || s == MessageRelay
|
||||||
}
|
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,6 +102,57 @@ 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
-75
@@ -6,7 +6,6 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"slices"
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -18,7 +17,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/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
|
||||||
@@ -239,11 +237,15 @@ const (
|
|||||||
|
|
||||||
type HostInfo struct {
|
type HostInfo struct {
|
||||||
remote atomic.Pointer[netip.AddrPort]
|
remote atomic.Pointer[netip.AddrPort]
|
||||||
remotes *RemoteList
|
|
||||||
promoteCounter atomic.Uint32
|
|
||||||
ConnectionState *ConnectionState
|
ConnectionState *ConnectionState
|
||||||
|
|
||||||
|
// Traffic bits, pendingDeletion, and the rebind epoch we last sent under
|
||||||
|
state atomic.Uint32
|
||||||
|
|
||||||
|
promoteCounter atomic.Uint32
|
||||||
remoteIndexId uint32
|
remoteIndexId uint32
|
||||||
localIndexId uint32
|
localIndexId uint32
|
||||||
|
remotes *RemoteList
|
||||||
|
|
||||||
// vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
|
// vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
|
||||||
// The host may have other vpn addresses that are outside our
|
// The host may have other vpn addresses that are outside our
|
||||||
@@ -262,11 +264,6 @@ type HostInfo struct {
|
|||||||
// This is used to limit lighthouse re-queries in chatty clients
|
// This is used to limit lighthouse re-queries in chatty clients
|
||||||
nextLHQuery atomic.Int64
|
nextLHQuery atomic.Int64
|
||||||
|
|
||||||
// lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
|
|
||||||
// for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
|
|
||||||
// with a handshake
|
|
||||||
lastRebindCount int8
|
|
||||||
|
|
||||||
// lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
|
// lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
|
||||||
// Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
|
// Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
|
||||||
// This is used to avoid an attack where a handshake packet is replayed after some time
|
// This is used to avoid an attack where a handshake packet is replayed after some time
|
||||||
@@ -275,9 +272,6 @@ type HostInfo struct {
|
|||||||
lastRoam time.Time
|
lastRoam time.Time
|
||||||
lastRoamRemote netip.AddrPort
|
lastRoamRemote netip.AddrPort
|
||||||
|
|
||||||
//TODO: in, out, and others might benefit from being an atomic.Int32. We could collapse connectionManager pendingDeletion, relayUsed, and in/out into this 1 thing
|
|
||||||
in, out, pendingDeletion atomic.Bool
|
|
||||||
|
|
||||||
// lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
|
// lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
|
||||||
// This value will be behind against actual tunnel utilization in the hot path.
|
// This value will be behind against actual tunnel utilization in the hot path.
|
||||||
// This should only be used by the ConnectionManagers ticker routine.
|
// This should only be used by the ConnectionManagers ticker routine.
|
||||||
@@ -287,7 +281,6 @@ type HostInfo struct {
|
|||||||
type ViaSender struct {
|
type ViaSender struct {
|
||||||
UdpAddr netip.AddrPort
|
UdpAddr netip.AddrPort
|
||||||
relayHI *HostInfo // relayHI is the host info object of the relay
|
relayHI *HostInfo // relayHI is the host info object of the relay
|
||||||
remoteIdx uint32 // remoteIdx is the index included in the header of the received packet
|
|
||||||
relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
|
relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
|
||||||
IsRelayed bool // IsRelayed is true if the packet was sent through a relay
|
IsRelayed bool // IsRelayed is true if the packet was sent through a relay
|
||||||
}
|
}
|
||||||
@@ -323,9 +316,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)
|
hm.reload(c, true, nil)
|
||||||
c.RegisterReloadCallback(func(c *config.C) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
hm.reload(c, false)
|
hm.reload(c, false, r)
|
||||||
})
|
})
|
||||||
|
|
||||||
l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
|
l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
|
||||||
@@ -344,7 +337,8 @@ func newHostMap(l *slog.Logger) *HostMap {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hm *HostMap) reload(c *config.C, initial bool) {
|
// r is nil on the initial load
|
||||||
|
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{})
|
||||||
@@ -355,8 +349,9 @@ func (hm *HostMap) reload(c *config.C, initial bool) {
|
|||||||
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", rawPreferredRanges,
|
"range", rawPreferredRange,
|
||||||
)
|
)
|
||||||
|
r.Failed()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -544,6 +539,17 @@ 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 {
|
||||||
@@ -659,7 +665,7 @@ func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
|
|||||||
hm.Indexes[hostinfo.localIndexId] = hostinfo
|
hm.Indexes[hostinfo.localIndexId] = hostinfo
|
||||||
hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
|
hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
|
||||||
|
|
||||||
hostinfo.out.Store(true)
|
hostinfo.markOut(f.rebindEpoch.Load())
|
||||||
if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
|
if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
|
||||||
f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
|
f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
|
||||||
}
|
}
|
||||||
@@ -760,6 +766,64 @@ func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interfac
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bits within HostInfo.state, everything above stateEpochShift is the epoch
|
||||||
|
const (
|
||||||
|
stateIn uint32 = 1 << iota
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
// markIn records inbound traffic
|
||||||
|
func (i *HostInfo) markIn() {
|
||||||
|
if i.state.Load()&stateIn == 0 {
|
||||||
|
i.state.Or(stateIn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// markOut records a send and reports whether the epoch moved, meaning we want a punch from the far side
|
||||||
|
func (i *HostInfo) markOut(epoch uint32) bool {
|
||||||
|
e := epoch << stateEpochShift
|
||||||
|
for {
|
||||||
|
old := i.state.Load()
|
||||||
|
if old&stateOut != 0 && old&^stateFlags == e {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if i.state.CompareAndSwap(old, old&stateFlags|stateOut|e) {
|
||||||
|
return old&^stateFlags != e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// markOutOnly records a send without consuming the rebind epoch, for paths that cannot act on a requery
|
||||||
|
func (i *HostInfo) markOutOnly() {
|
||||||
|
if i.state.Load()&stateOut == 0 {
|
||||||
|
i.state.Or(stateOut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// takeTraffic clears both traffic bits, leaving the epoch alone, and reports what they were
|
||||||
|
func (i *HostInfo) takeTraffic() (in bool, out bool) {
|
||||||
|
old := i.state.And(^(stateIn | stateOut))
|
||||||
|
return old&stateIn != 0, old&stateOut != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *HostInfo) setPendingDeletion(v bool) {
|
||||||
|
if v {
|
||||||
|
i.state.Or(statePendingDeletion)
|
||||||
|
} else {
|
||||||
|
i.state.And(^statePendingDeletion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *HostInfo) isPendingDeletion() bool {
|
||||||
|
return i.state.Load()&statePendingDeletion != 0
|
||||||
|
}
|
||||||
|
|
||||||
func (i *HostInfo) GetCert() *cert.CachedCertificate {
|
func (i *HostInfo) GetCert() *cert.CachedCertificate {
|
||||||
if i.ConnectionState != nil {
|
if i.ConnectionState != nil {
|
||||||
return i.ConnectionState.peerCert
|
return i.ConnectionState.peerCert
|
||||||
@@ -866,59 +930,3 @@ 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,3 +401,62 @@ 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())
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@@ -9,13 +10,14 @@ import (
|
|||||||
"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/batch"
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
"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.Packet, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
||||||
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
||||||
// only valid until the next Read on that queue. Every consumer below
|
// only valid until the next Read on that queue. Every consumer below
|
||||||
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
||||||
@@ -57,6 +59,9 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Packe
|
|||||||
// kernel as one giant blob; segment first so the loopback
|
// kernel as one giant blob; segment first so the loopback
|
||||||
// path sees one IP datagram per Write.
|
// path sees one IP datagram per Write.
|
||||||
err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
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)
|
_, werr := f.queues[q].Write(seg)
|
||||||
return werr
|
return werr
|
||||||
})
|
})
|
||||||
@@ -74,7 +79,7 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Packe
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
|
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
|
||||||
// borrowed: SegmentSuperpacket builds each segment in the kernel-supplied pkt
|
// borrowed: SegmentSuperpacket builds each segment in the kernel-supplied pkt
|
||||||
// bytes underneath. cachePacket explicitly copies its argument (handshake_manager.go cachePacket),
|
// bytes underneath. cachePacket explicitly copies its argument (handshake_manager.go cachePacket),
|
||||||
// so retaining segments past the loop is safe.
|
// so retaining segments past the loop is safe.
|
||||||
@@ -105,9 +110,9 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Packe
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
|
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||||
if dropReason == nil {
|
if dropReason == nil {
|
||||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch, rejectBuf, q)
|
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
||||||
} else {
|
} else {
|
||||||
f.rejectInside(packet, rejectBuf, q)
|
f.rejectInside(packet, rejectBuf, q)
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
@@ -126,7 +131,6 @@ func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, s
|
|||||||
c := ci.messageCounter.Add(1)
|
c := ci.messageCounter.Add(1)
|
||||||
|
|
||||||
out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
|
out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
|
||||||
f.connectionManager.Out(hostinfo)
|
|
||||||
|
|
||||||
out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
|
out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
|
||||||
if noiseutil.EncryptLockNeeded {
|
if noiseutil.EncryptLockNeeded {
|
||||||
@@ -138,8 +142,7 @@ func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, s
|
|||||||
"udpAddr", hostinfo.GetRemote(),
|
"udpAddr", hostinfo.GetRemote(),
|
||||||
"counter", c,
|
"counter", c,
|
||||||
)
|
)
|
||||||
// Skip this segment; the rest of the superpacket can still
|
// Skip this segment; the rest of the superpacket can still go out. TCP will retransmit anything we drop here.
|
||||||
// go out — TCP will retransmit anything we drop here.
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,28 +154,28 @@ func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, s
|
|||||||
// later sendmmsg flush. Segmentation is fused with encryption here so the
|
// later sendmmsg flush. Segmentation is fused with encryption here so the
|
||||||
// kernel-supplied superpacket bytes never get written into a separate
|
// kernel-supplied superpacket bytes never get written into a separate
|
||||||
// scratch arena: SegmentSuperpacket builds each segment's plaintext in
|
// scratch arena: SegmentSuperpacket builds each segment's plaintext in
|
||||||
// segScratch[:segLen] in turn, and we encrypt directly into a fresh
|
// segScratch[:segLen] in turn, and we encrypt directly into a fresh SendBatch slot.
|
||||||
// SendBatch slot.
|
func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch *batch.SendBatch) {
|
||||||
func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int) {
|
|
||||||
ci := hostinfo.ConnectionState
|
ci := hostinfo.ConnectionState
|
||||||
if ci.eKey == nil {
|
if ci.eKey == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
remote := hostinfo.GetRemote()
|
// One traffic-out mark covers every segment of the superpacket; doing it
|
||||||
ecnEnabled := f.ecnEnabled.Load()
|
// per segment in sendInsideEncrypt paid an atomic store up to ~45 extra
|
||||||
if hostinfo.lastRebindCount != f.rebindCount {
|
// times per TSO packet, inside writeLock under boring crypto.
|
||||||
//NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
|
//
|
||||||
// finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
|
// 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])
|
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
||||||
hostinfo.lastRebindCount = f.rebindCount
|
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind counter",
|
hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind epoch",
|
||||||
"vpnAddrs", hostinfo.vpnAddrs,
|
"vpnAddrs", hostinfo.vpnAddrs,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
remote := hostinfo.GetRemote()
|
||||||
if !remote.IsValid() { //the relay path
|
if !remote.IsValid() { //the relay path
|
||||||
//first, find our relay hostinfo:
|
//first, find our relay hostinfo:
|
||||||
var relayHostInfo *HostInfo
|
var relayHostInfo *HostInfo
|
||||||
@@ -196,8 +199,8 @@ func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []b
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
||||||
//relay header + header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305) + relay tag
|
//relay header + header + plaintext + AEAD tag + relay tag
|
||||||
scratch := sendBatch.Reserve(header.Len + header.Len + len(seg) + 16 + 16)
|
scratch := sendBatch.Reserve(len(seg) + header.MaxOverhead)
|
||||||
|
|
||||||
innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
|
innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
|
||||||
if innerPacket == nil {
|
if innerPacket == nil {
|
||||||
@@ -211,11 +214,7 @@ func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []b
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var ecn byte
|
sendBatch.Commit(toSend, relayHostInfo.GetRemote())
|
||||||
if ecnEnabled {
|
|
||||||
ecn = innerECN(seg)
|
|
||||||
}
|
|
||||||
sendBatch.Commit(toSend, relayHostInfo.GetRemote(), ecn)
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -233,36 +232,14 @@ func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []b
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var ecn byte
|
sendBatch.Commit(out, remote)
|
||||||
if ecnEnabled {
|
|
||||||
ecn = innerECN(seg)
|
|
||||||
}
|
|
||||||
sendBatch.Commit(out, remote, ecn)
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
hostinfo.logger(f.l).Error("Failed to segment superpacket for send",
|
hostinfo.logger(f.l).Error("Failed to segment superpacket for send", "error", err)
|
||||||
"error", err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// innerECN returns the 2-bit IP-level ECN codepoint of an inner IPv4 or IPv6
|
|
||||||
// packet, or 0 if pkt is too short or its IP version is unrecognized. Used at
|
|
||||||
// encap to copy the inner codepoint onto the outer carrier per RFC 6040.
|
|
||||||
func innerECN(pkt []byte) byte {
|
|
||||||
if len(pkt) < 2 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
switch pkt[0] >> 4 {
|
|
||||||
case 4:
|
|
||||||
return pkt[1] & 0x03
|
|
||||||
case 6:
|
|
||||||
return (pkt[1] >> 4) & 0x03
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
||||||
@@ -279,27 +256,30 @@ func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
|
func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, rejectBuf []byte, q int) {
|
||||||
if !f.firewall.InboundSendReject {
|
if !f.firewall.InboundSendReject {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
out = iputil.CreateRejectPacket(packet, out)
|
// split rejectBuf to make sure we have room to write the plaintext rejection, then encrypt it, without trampling anything
|
||||||
|
// 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",
|
f.l.Info("rejectOutside: packet too big, not sending", "packet", packet, "outPacket", out)
|
||||||
"packet", packet,
|
|
||||||
"outPacket", out,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
|
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, encryptBuf, 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
|
||||||
@@ -393,7 +373,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.Packet{}
|
fp := &firewall.ParsedPacket{}
|
||||||
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)
|
||||||
@@ -401,7 +381,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, false, hostinfo, f.pki.GetCAPool(), nil)
|
dropReason := f.firewall.Drop(fp.Packet, 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",
|
||||||
@@ -452,6 +432,14 @@ 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.
|
||||||
|
func (f *Interface) dropExhausted(hostinfo *HostInfo, c uint64, msg string) {
|
||||||
|
f.messageMetrics.TxExhausted(1)
|
||||||
|
if c == RejectAfterMessages {
|
||||||
|
hostinfo.logger(f.l).Error(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (f *Interface) prepareSendVia(via *HostInfo,
|
func (f *Interface) prepareSendVia(via *HostInfo,
|
||||||
relay *Relay,
|
relay *Relay,
|
||||||
ad,
|
ad,
|
||||||
@@ -463,10 +451,17 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
|||||||
// 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 := via.ConnectionState.messageCounter.Add(1)
|
c, ok := via.ConnectionState.NextMessageCounter()
|
||||||
|
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.Out(via)
|
f.connectionManager.OutNoRebind(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.
|
||||||
@@ -514,22 +509,18 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
|||||||
// nb is a buffer used to store the nonce value, re-used for performance reasons.
|
// 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
|
// out is a buffer used to store the result of the Encrypt operation
|
||||||
// q indicates which writer to use to send the packet.
|
// q indicates which writer to use to send the packet.
|
||||||
func (f *Interface) SendVia(via *HostInfo,
|
func (f *Interface) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
|
||||||
relay *Relay,
|
|
||||||
ad,
|
|
||||||
nb,
|
|
||||||
out []byte,
|
|
||||||
nocopy bool,
|
|
||||||
) {
|
|
||||||
toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
|
toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// already logged by prepareSendVia
|
// already logged by prepareSendVia
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = f.writers[0].WriteTo(toSend, via.GetRemote())
|
err = f.writers[q].WriteTo(toSend, via.GetRemote())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
|
if l, ok := logging.RateLimited(f.l, f.udpRelayTxErrLimiter); ok {
|
||||||
|
via.logger(l).Info("Failed to WriteTo in sendVia", "error", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,37 +529,50 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
||||||
fullOut := out
|
|
||||||
|
|
||||||
|
// 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 {
|
if useRelay {
|
||||||
if len(out) < header.Len {
|
// The relay tunnel runs the same cipher, and adds its own header and tag
|
||||||
// out always has a capacity of mtu, but not always a length greater than the header.Len.
|
need += header.Len + ci.eKey.Overhead()
|
||||||
// Grow it to make sure the next operation works.
|
|
||||||
out = out[:header.Len]
|
|
||||||
}
|
}
|
||||||
|
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
|
||||||
|
if useRelay {
|
||||||
// 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:]
|
out = out[header.Len: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 := ci.messageCounter.Add(1)
|
c, ok := ci.NextMessageCounter()
|
||||||
|
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)
|
||||||
f.connectionManager.Out(hostinfo)
|
// A closing tunnel is torn down right after this, so skip the connection manager entirely: no point recording
|
||||||
|
// traffic or asking the lighthouse for a punch. Otherwise, if we rebound since this tunnel last sent, ask the
|
||||||
// Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
|
// lighthouse to get the far side punching at us again.
|
||||||
// all our addrs and enable a faster roaming.
|
if t != header.CloseTunnel && f.connectionManager.Out(hostinfo) {
|
||||||
if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
|
|
||||||
//NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
|
|
||||||
// finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
|
|
||||||
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
||||||
hostinfo.lastRebindCount = f.rebindCount
|
|
||||||
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 counter",
|
f.l.Debug("Lighthouse update triggered for punch due to rebind epoch",
|
||||||
"vpnAddrs", hostinfo.vpnAddrs,
|
"vpnAddrs", hostinfo.vpnAddrs,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -591,19 +595,23 @@ 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 {
|
||||||
hostinfo.logger(f.l).Error("Failed to write outgoing packet",
|
if l, ok := logging.RateLimited(f.l, f.udpTxErrLimiter); ok {
|
||||||
|
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 {
|
||||||
hostinfo.logger(f.l).Error("Failed to write outgoing packet",
|
if l, ok := logging.RateLimited(f.l, f.udpTxErrLimiter); ok {
|
||||||
|
hostinfo.logger(l).Error("Failed to write outgoing packet",
|
||||||
"error", err,
|
"error", err,
|
||||||
"udpAddr", remote,
|
"udpAddr", hr,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Try to send via a relay
|
// Try to send via a relay
|
||||||
for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
|
for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
|
||||||
@@ -616,7 +624,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)
|
f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true, q)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+265
@@ -0,0 +1,265 @@
|
|||||||
|
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:]))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
-91
@@ -2,6 +2,7 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/fips140"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
@@ -23,6 +24,7 @@ import (
|
|||||||
"github.com/slackhq/nebula/overlay"
|
"github.com/slackhq/nebula/overlay"
|
||||||
"github.com/slackhq/nebula/overlay/batch"
|
"github.com/slackhq/nebula/overlay/batch"
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
"github.com/slackhq/nebula/overlay/tio"
|
||||||
|
"github.com/slackhq/nebula/ratelimit"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -97,11 +99,6 @@ type Interface struct {
|
|||||||
// a CPU at all (tun.pin_threads, default true). When false, threads are
|
// a CPU at all (tun.pin_threads, default true). When false, threads are
|
||||||
// left free to migrate as on stock nebula.
|
// left free to migrate as on stock nebula.
|
||||||
pinThreads bool
|
pinThreads bool
|
||||||
// ecnEnabled gates RFC 6040 underlay ECN propagation. When true,
|
|
||||||
// inside.go copies the inner ECN onto the outer carrier on encap and
|
|
||||||
// decryptToTun folds outer CE into the inner header on decap. Toggle
|
|
||||||
// via tunnels.ecn (default true).
|
|
||||||
ecnEnabled atomic.Bool
|
|
||||||
relayManager *relayManager
|
relayManager *relayManager
|
||||||
|
|
||||||
tryPromoteEvery atomic.Uint32
|
tryPromoteEvery atomic.Uint32
|
||||||
@@ -111,8 +108,8 @@ type Interface struct {
|
|||||||
sendRecvErrorConfig recvErrorConfig
|
sendRecvErrorConfig recvErrorConfig
|
||||||
acceptRecvErrorConfig recvErrorConfig
|
acceptRecvErrorConfig recvErrorConfig
|
||||||
|
|
||||||
// rebindCount is used to decide if an active tunnel should trigger a punch notification through a lighthouse
|
// Bumped on every udp rebind, tunnels compare it to decide they need a punch from the far side
|
||||||
rebindCount int8
|
rebindEpoch atomic.Uint32
|
||||||
version string
|
version string
|
||||||
|
|
||||||
conntrackCacheTimeout time.Duration
|
conntrackCacheTimeout time.Duration
|
||||||
@@ -120,12 +117,18 @@ type Interface struct {
|
|||||||
ctx context.Context
|
ctx context.Context
|
||||||
writers []udp.Conn
|
writers []udp.Conn
|
||||||
queues []tio.Queue
|
queues []tio.Queue
|
||||||
// batchers is one per tun queue, wrapping queues[i].
|
// batchers is one per tun queue, wrapping queues[i]. readOutsidePackets
|
||||||
// decryptToTun sends plaintext into the batch.RxBatcher;
|
// commits plaintext into the batcher; the plaintext is decrypted
|
||||||
// listenOut calls its Flush at the end of each UDP recvmmsg batch.
|
// in place inside the UDP receive buffers, so listenOut must call Flush
|
||||||
batchers []batch.RxBatcher
|
// 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
|
wg 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)
|
||||||
fatalErr atomic.Pointer[error]
|
fatalErr atomic.Pointer[error]
|
||||||
@@ -135,18 +138,13 @@ 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,
|
SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int)
|
||||||
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,6 +203,23 @@ 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,
|
||||||
@@ -222,7 +237,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.RxBatcher, c.routines),
|
batchers: make([]*batch.MultiCoalescer, c.routines),
|
||||||
myVpnNetworks: cs.myVpnNetworks,
|
myVpnNetworks: cs.myVpnNetworks,
|
||||||
myVpnNetworksTable: cs.myVpnNetworksTable,
|
myVpnNetworksTable: cs.myVpnNetworksTable,
|
||||||
myVpnAddrs: cs.myVpnAddrs,
|
myVpnAddrs: cs.myVpnAddrs,
|
||||||
@@ -233,8 +248,12 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
conntrackCacheTimeout: c.ConntrackCacheTimeout,
|
conntrackCacheTimeout: c.ConntrackCacheTimeout,
|
||||||
cpuAffinity: c.CpuAffinity,
|
cpuAffinity: c.CpuAffinity,
|
||||||
pinThreads: c.PinThreads,
|
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),
|
||||||
@@ -273,6 +292,9 @@ 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.outside.SupportsMultipleReaders() {
|
||||||
@@ -288,6 +310,13 @@ func (f *Interface) activate() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if len(queues) < f.routines {
|
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",
|
f.l.Warn("tun multiqueue is not supported on this platform, falling back to fewer routines",
|
||||||
"requested", f.routines, "opened", len(queues))
|
"requested", f.routines, "opened", len(queues))
|
||||||
f.routines = len(queues)
|
f.routines = len(queues)
|
||||||
@@ -297,18 +326,7 @@ func (f *Interface) activate() error {
|
|||||||
metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
|
metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
|
||||||
|
|
||||||
for i := range f.queues {
|
for i := range f.queues {
|
||||||
caps := tio.QueueCapabilities(f.queues[i])
|
f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l)
|
||||||
if caps.TSO || caps.USO {
|
|
||||||
// Multi-lane: TCP gets coalesced when TSO is on, UDP when USO
|
|
||||||
// is on, everything else (and either lane disabled) falls
|
|
||||||
// through to passthrough so non-IP / non-TCP-UDP traffic still
|
|
||||||
// reaches the TUN.
|
|
||||||
arena := batch.NewArena(batch.DefaultMultiArenaCap)
|
|
||||||
f.batchers[i] = batch.NewMultiCoalescer(f.queues[i], f.l, arena, caps.TSO, caps.USO)
|
|
||||||
} else {
|
|
||||||
arena := batch.NewArena(batch.DefaultPassthroughArenaCap)
|
|
||||||
f.batchers[i] = batch.NewPassthrough(f.queues[i], arena.Reserve, arena.Reset)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -356,6 +374,31 @@ 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 {
|
||||||
@@ -364,21 +407,17 @@ func (f *Interface) listenOut(i int) {
|
|||||||
li = f.outside
|
li = f.outside
|
||||||
}
|
}
|
||||||
|
|
||||||
ctCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
|
rxc := newRxContext(f, i)
|
||||||
lhh := f.lightHouse.NewRequestHandler()
|
|
||||||
h := &header.H{}
|
|
||||||
fwPacket := &firewall.Packet{}
|
|
||||||
nb := make([]byte, 12, 12)
|
|
||||||
|
|
||||||
listener := func(fromUdpAddr netip.AddrPort, payload []byte, meta udp.RxMeta) {
|
listener := func(fromUdpAddr netip.AddrPort, payload []byte) {
|
||||||
plaintext := f.batchers[i].Reserve(len(payload))
|
f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, payload, rxc)
|
||||||
f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, plaintext[:0], payload, h, fwPacket, lhh, nb, i, ctCache.Get(), meta)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
flusher := func() {
|
flusher := func() {
|
||||||
if err := f.batchers[i].Flush(); err != nil {
|
if err := f.batchers[i].Flush(); err != nil {
|
||||||
f.l.Error("Failed to flush tun coalescer", "error", err)
|
f.l.Error("Failed to flush tun coalescer", "error", err)
|
||||||
}
|
}
|
||||||
|
clear(rxc.hostmapCache)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := li.ListenOut(listener, flusher)
|
err := li.ListenOut(listener, flusher)
|
||||||
@@ -394,10 +433,7 @@ 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) listenIn(queue tio.Queue, i int) {
|
func (f *Interface) pinThisThread(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 {
|
|
||||||
var cpu int
|
var cpu int
|
||||||
if n := len(f.cpuAffinity); n > 0 {
|
if n := len(f.cpuAffinity); n > 0 {
|
||||||
// Explicit tun.cpu_affinity list wins; parseCpuAffinity already
|
// Explicit tun.cpu_affinity list wins; parseCpuAffinity already
|
||||||
@@ -414,12 +450,19 @@ func (f *Interface) listenIn(queue tio.Queue, i int) {
|
|||||||
if err := util.PinThreadToCPU(cpu); err != nil {
|
if err := util.PinThreadToCPU(cpu); err != nil {
|
||||||
f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
|
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)
|
rejectBuf := make([]byte, mtu)
|
||||||
arenaSize := batch.SendBatchCap * (udp.MTU + 32)
|
arenaSize := batch.SendBatchCap * (udp.MTU + 32)
|
||||||
sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
|
sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
|
||||||
fwPacket := &firewall.Packet{}
|
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)
|
||||||
@@ -441,26 +484,36 @@ func (f *Interface) listenIn(queue tio.Queue, i int) {
|
|||||||
// accumulated so the first packets of a deep read drain
|
// accumulated so the first packets of a deep read drain
|
||||||
// hit the wire while the rest are still being encrypted.
|
// hit the wire while the rest are still being encrypted.
|
||||||
if sb.Len() >= batch.SendBatchCap {
|
if sb.Len() >= batch.SendBatchCap {
|
||||||
if err := sb.Flush(); err != nil {
|
f.flushSendBatch(sb, i)
|
||||||
f.l.Error("Failed to write outgoing batch", "error", err, "writer", i)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
f.flushSendBatch(sb, i)
|
||||||
if err := sb.Flush(); err != nil {
|
|
||||||
f.l.Error("Failed to write outgoing batch", "error", err, "writer", 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)
|
||||||
c.RegisterReloadCallback(f.reloadSendRecvError)
|
for _, reload := range []func(*config.C){
|
||||||
c.RegisterReloadCallback(f.reloadAcceptRecvError)
|
f.reloadSendRecvError, f.reloadAcceptRecvError, f.reloadDisconnectInvalid, f.reloadMisc,
|
||||||
c.RegisterReloadCallback(f.reloadDisconnectInvalid)
|
} {
|
||||||
c.RegisterReloadCallback(f.reloadMisc)
|
c.RegisterReloadCallback(func(c *config.C, _ *config.Reload) { reload(c) })
|
||||||
c.RegisterReloadCallback(f.reloadEcn)
|
}
|
||||||
|
|
||||||
for _, udpConn := range f.writers {
|
for _, udpConn := range f.writers {
|
||||||
c.RegisterReloadCallback(udpConn.ReloadConfig)
|
c.RegisterReloadCallback(udpConn.ReloadConfig)
|
||||||
@@ -477,7 +530,7 @@ func (f *Interface) reloadDisconnectInvalid(c *config.C) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) reloadFirewall(c *config.C) {
|
func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
||||||
cs := f.pki.getCertState()
|
cs := f.pki.getCertState()
|
||||||
curCert := cs.getCertificate(cert.Version2)
|
curCert := cs.getCertificate(cert.Version2)
|
||||||
if curCert == nil {
|
if curCert == nil {
|
||||||
@@ -496,6 +549,7 @@ func (f *Interface) reloadFirewall(c *config.C) {
|
|||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -593,34 +647,15 @@ func (f *Interface) reloadMisc(c *config.C) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// reloadEcn syncs Interface.ecnEnabled with the tunnels.ecn config knob.
|
// statsEmitter updates the interface's gauges, the stats server runs it on its capture loop.
|
||||||
// Default is enabled (RFC 6040 normal mode); set false on the rare path
|
func (f *Interface) statsEmitter() func() {
|
||||||
// where an underlay middlebox rewrites or drops ECN bits unpredictably.
|
|
||||||
func (f *Interface) reloadEcn(c *config.C) {
|
|
||||||
initial := c.InitialLoad()
|
|
||||||
if initial || c.HasChanged("tunnels.ecn") {
|
|
||||||
v := c.GetBool("tunnels.ecn", true)
|
|
||||||
changed := f.ecnEnabled.Swap(v) != v
|
|
||||||
if !initial {
|
|
||||||
f.l.Info("tunnels.ecn changed", "enabled", v)
|
|
||||||
if changed {
|
|
||||||
f.l.Warn("tunnels.ecn datapath toggled, but route-level ECN negotiation (RTAX_FEATURE_ECN) retains its previous state until nebula is restarted", "enabled", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
|
|
||||||
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)
|
||||||
|
|
||||||
emit := func() {
|
return func() {
|
||||||
f.firewall.EmitStats()
|
f.firewall.EmitStats()
|
||||||
f.handshakeManager.EmitStats()
|
f.handshakeManager.EmitStats()
|
||||||
udpStats()
|
udpStats()
|
||||||
@@ -637,19 +672,6 @@ func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
|
|||||||
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 {
|
||||||
|
|||||||
+5
-14
@@ -3,7 +3,6 @@
|
|||||||
package nebula
|
package nebula
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -18,11 +17,8 @@ import (
|
|||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Test_emitStats_primesGauges covers issue #907: a Prometheus scrape that
|
// Priming before the first tick (issue #907) is Start's job, see TestStatsServer_Start_primes.
|
||||||
// landed before the first ticker fire used to read 0 for the cert gauges.
|
func Test_statsEmitter_setsGauges(t *testing.T) {
|
||||||
// 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()
|
||||||
@@ -56,17 +52,12 @@ func Test_emitStats_primesGauges(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 emitStats runs")
|
require.Zero(t, ttlGauge.Value(), "gauge should be zero before the emitter runs")
|
||||||
|
|
||||||
// Pre-cancel the context so emitStats returns after priming the gauges
|
ifce.statsEmitter()()
|
||||||
// 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 primed by emitStats before its first tick")
|
assert.Positive(t, ttl, "ttl gauge should be set by one run of the emitter")
|
||||||
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())
|
||||||
|
|||||||
+26
-4
@@ -65,10 +65,10 @@ func TestReloadFirewall_CertUnsafeNetworksChanged(t *testing.T) {
|
|||||||
pki.cs.Store(&CertState{v2Cert: c2, initiatingVersion: cert.Version2})
|
pki.cs.Store(&CertState{v2Cert: c2, initiatingVersion: cert.Version2})
|
||||||
|
|
||||||
// Reload with the same YAML so HasChanged("firewall") reports false.
|
// Reload with the same YAML so HasChanged("firewall") reports false.
|
||||||
require.NoError(t, cfg.ReloadConfigString(rawYAML))
|
require.NoError(t, cfg.ReloadConfigString(rawYAML).Err)
|
||||||
require.False(t, cfg.HasChanged("firewall"))
|
require.False(t, cfg.HasChanged("firewall"))
|
||||||
|
|
||||||
f.reloadFirewall(cfg)
|
f.reloadFirewall(cfg, nil)
|
||||||
|
|
||||||
assert.NotSame(t, fw, f.firewall, "firewall pointer should have been replaced")
|
assert.NotSame(t, fw, f.firewall, "firewall pointer should have been replaced")
|
||||||
assert.Equal(t, newUnsafe, f.firewall.unsafeNetworks)
|
assert.Equal(t, newUnsafe, f.firewall.unsafeNetworks)
|
||||||
@@ -113,8 +113,30 @@ func TestReloadFirewall_NoChange(t *testing.T) {
|
|||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
|
|
||||||
require.NoError(t, cfg.ReloadConfigString(rawYAML))
|
require.NoError(t, cfg.ReloadConfigString(rawYAML).Err)
|
||||||
f.reloadFirewall(cfg)
|
f.reloadFirewall(cfg, nil)
|
||||||
|
|
||||||
assert.Same(t, fw, f.firewall, "firewall should not have been replaced")
|
assert.Same(t, fw, f.firewall, "firewall should not have been replaced")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rules that don't parse keep the old firewall, and the reload says it could not apply them
|
||||||
|
func TestReloadFirewall_BadRulesFailTheReload(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
pki := &PKI{}
|
||||||
|
pki.cs.Store(&CertState{v2Cert: &dummyCert{version: cert.Version2, networks: []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}}, initiatingVersion: cert.Version2})
|
||||||
|
|
||||||
|
rules := func(proto string) string {
|
||||||
|
return "firewall:\n outbound:\n - port: any\n proto: any\n host: any\n inbound:\n - port: any\n proto: " + proto + "\n host: any\n"
|
||||||
|
}
|
||||||
|
cfg := config.NewC(l)
|
||||||
|
require.NoError(t, cfg.LoadString(rules("any")))
|
||||||
|
fw, err := NewFirewallFromConfig(l, pki.getCertState(), cfg)
|
||||||
|
require.NoError(t, err)
|
||||||
|
f := &Interface{pki: pki, firewall: fw, l: l}
|
||||||
|
cfg.RegisterReloadCallback(f.reloadFirewall)
|
||||||
|
|
||||||
|
res := cfg.ReloadConfigString(rules("nope"))
|
||||||
|
require.NoError(t, res.Err)
|
||||||
|
assert.True(t, res.Failed)
|
||||||
|
assert.Same(t, fw, f.firewall)
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package iputil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/overlay/checksum"
|
||||||
|
"golang.org/x/net/ipv4"
|
||||||
|
"golang.org/x/net/ipv6"
|
||||||
|
)
|
||||||
|
|
||||||
|
const udpHeaderLen = 8
|
||||||
|
|
||||||
|
// SetTransportChecksum recomputes the TCP or UDP checksum of an IPv4 or IPv6
|
||||||
|
// packet in place.
|
||||||
|
//
|
||||||
|
// A kernel that offloads checksums to the NIC hands a packet to a tun with the
|
||||||
|
// transport checksum unfinished: only the pseudo-header sum is in the field and
|
||||||
|
// the rest is left for hardware that a tun does not have. A packet written
|
||||||
|
// straight back to that tun is dropped on re-entry unless the checksum is
|
||||||
|
// completed first. ICMP is left alone; it arrived complete on the kernels this
|
||||||
|
// was measured against.
|
||||||
|
//
|
||||||
|
// So is any packet whose transport header cannot be located: fragments, unknown
|
||||||
|
// extension headers and truncated packets. An IPv6 fragment header is declined
|
||||||
|
// even when it carries the whole datagram (RFC 6946 atomic fragment), because
|
||||||
|
// the walk reports only that a fragment header was present.
|
||||||
|
func SetTransportChecksum(packet []byte) {
|
||||||
|
if len(packet) < 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch int(packet[0] >> 4) {
|
||||||
|
case ipv4.Version:
|
||||||
|
setTransportChecksum4(packet)
|
||||||
|
case ipv6.Version:
|
||||||
|
setTransportChecksum6(packet)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setTransportChecksum4(packet []byte) {
|
||||||
|
if len(packet) < ipv4.HeaderLen {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ihl := int(packet[0]&0x0f) << 2
|
||||||
|
end := int(binary.BigEndian.Uint16(packet[2:4]))
|
||||||
|
if ihl < ipv4.HeaderLen || end < ihl || end > len(packet) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// do not attempt to set checksums for fragments
|
||||||
|
if binary.BigEndian.Uint16(packet[6:8])&0x3fff != 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
transport, ok := transportExtent(packet[ihl:end], packet[9])
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
csum := ipv4PseudoheaderChecksum(packet[12:16], packet[16:20], uint32(packet[9]), uint32(len(transport)))
|
||||||
|
writeTransportChecksum(transport, packet[9], csum)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setTransportChecksum6(packet []byte) {
|
||||||
|
if len(packet) < ipv6.HeaderLen {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
end := ipv6.HeaderLen + int(binary.BigEndian.Uint16(packet[4:6]))
|
||||||
|
if end > len(packet) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// we must find the transport header in order to write a checksum
|
||||||
|
proto, offset, _, anyFragment, err := IPv6FindUpperProtocol(packet[:end])
|
||||||
|
if err != nil || anyFragment || offset >= end {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
transport, ok := transportExtent(packet[offset:end], proto)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
csum := ipv6PseudoheaderChecksum(packet[8:24], packet[24:40], uint32(proto), uint32(len(transport)))
|
||||||
|
writeTransportChecksum(transport, proto, csum)
|
||||||
|
}
|
||||||
|
|
||||||
|
// transportExtent narrows a segment to the length its own header declares. UDP
|
||||||
|
// carries a Length field, and RFC 768 and RFC 8200 section 8.1 both make that
|
||||||
|
// field, not the IP payload extent, the length the pseudo-header counts and the
|
||||||
|
// checksum covers; a datagram padded out to a link's minimum frame is the usual
|
||||||
|
// way the two differ. TCP has no such field, so its segment runs to the end of
|
||||||
|
// the IP payload. A Length that overruns the bytes IP delivered describes a
|
||||||
|
// datagram that is not there.
|
||||||
|
func transportExtent(transport []byte, proto uint8) ([]byte, bool) {
|
||||||
|
if proto != IPProtocolUDP {
|
||||||
|
return transport, true
|
||||||
|
}
|
||||||
|
if len(transport) < udpHeaderLen {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
ulen := int(binary.BigEndian.Uint16(transport[4:6]))
|
||||||
|
if ulen < udpHeaderLen || ulen > len(transport) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return transport[:ulen], true
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeTransportChecksum stores the checksum of transport, taken over the
|
||||||
|
// pseudo-header sum csum, in the header's checksum field. A UDP checksum that
|
||||||
|
// computes to zero goes on the wire as 0xffff: zero means no checksum was
|
||||||
|
// computed (RFC 768), and over IPv6 the checksum is mandatory (RFC 8200 section 8.1).
|
||||||
|
func writeTransportChecksum(transport []byte, proto uint8, csum uint32) {
|
||||||
|
var at, minLen int
|
||||||
|
switch proto {
|
||||||
|
case IPProtocolTCP:
|
||||||
|
at, minLen = 16, 20
|
||||||
|
case IPProtocolUDP:
|
||||||
|
at, minLen = 6, udpHeaderLen
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(transport) < minLen {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
transport[at], transport[at+1] = 0, 0
|
||||||
|
sum := ^checksum.Checksum(transport, fold(csum))
|
||||||
|
if sum == 0 && proto == IPProtocolUDP {
|
||||||
|
sum = 0xffff
|
||||||
|
}
|
||||||
|
binary.BigEndian.PutUint16(transport[at:], sum)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fold(csum uint32) uint16 {
|
||||||
|
for csum > 0xffff {
|
||||||
|
csum = (csum >> 16) + (csum & 0xffff)
|
||||||
|
}
|
||||||
|
return uint16(csum)
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package iputil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/gopacket"
|
||||||
|
"github.com/google/gopacket/layers"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"golang.org/x/net/ipv6"
|
||||||
|
)
|
||||||
|
|
||||||
|
// serialize builds a packet with gopacket, whose checksums are computed
|
||||||
|
// independently of this package.
|
||||||
|
func serialize(t *testing.T, ls ...gopacket.SerializableLayer) []byte {
|
||||||
|
buf := gopacket.NewSerializeBuffer()
|
||||||
|
require.NoError(t, gopacket.SerializeLayers(buf, gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}, ls...))
|
||||||
|
return append([]byte(nil), buf.Bytes()...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// withExtensionHeader inserts an 8 byte IPv6 extension header of the given
|
||||||
|
// type between the IPv6 header and its payload. The transport checksum does not
|
||||||
|
// change: the pseudo-header counts only upper-layer bytes.
|
||||||
|
func withExtensionHeader(pkt []byte, typ layers.IPProtocol, hdr [8]byte) []byte {
|
||||||
|
hdr[0] = pkt[6]
|
||||||
|
out := make([]byte, 0, len(pkt)+8)
|
||||||
|
out = append(out, pkt[:40]...)
|
||||||
|
out = append(out, hdr[:]...)
|
||||||
|
out = append(out, pkt[40:]...)
|
||||||
|
out[6] = byte(typ)
|
||||||
|
binary.BigEndian.PutUint16(out[4:6], binary.BigEndian.Uint16(pkt[4:6])+8)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncate copies the first n bytes into a buffer of exactly that capacity, so
|
||||||
|
// a read past the length panics instead of quietly succeeding.
|
||||||
|
func truncate(pkt []byte, n int) []byte {
|
||||||
|
out := make([]byte, n)
|
||||||
|
copy(out, pkt)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// extChain builds an IPv6 packet fronted by n Destination Options headers. Each
|
||||||
|
// points at another one, so the walk spends its whole budget without reaching a
|
||||||
|
// transport header. lastExtLen inflates the final header's declared length,
|
||||||
|
// which is how the walk ends up past the end of the packet.
|
||||||
|
func extChain(n int, lastExtLen byte) []byte {
|
||||||
|
pkt := make([]byte, ipv6.HeaderLen)
|
||||||
|
pkt[0], pkt[6], pkt[7] = 0x60, 60, 64
|
||||||
|
for i := range n {
|
||||||
|
h := make([]byte, 8)
|
||||||
|
h[0] = 60
|
||||||
|
if i == n-1 {
|
||||||
|
h[1] = lastExtLen
|
||||||
|
}
|
||||||
|
pkt = append(pkt, h...)
|
||||||
|
}
|
||||||
|
pkt = append(pkt, make([]byte, 20)...)
|
||||||
|
binary.BigEndian.PutUint16(pkt[4:6], uint16(len(pkt)-ipv6.HeaderLen))
|
||||||
|
return pkt
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetTransportChecksum(t *testing.T) {
|
||||||
|
// Source and destination differ so that a pseudo-header built from the wrong
|
||||||
|
// one, or from the two swapped, does not land on the same checksum anyway.
|
||||||
|
v4 := func(proto layers.IPProtocol) *layers.IPv4 {
|
||||||
|
return &layers.IPv4{Version: 4, TTL: 64, Id: 0x1234, Protocol: proto, SrcIP: net.IPv4(192, 0, 2, 1).To4(), DstIP: net.IPv4(198, 51, 100, 2).To4()}
|
||||||
|
}
|
||||||
|
v6 := func(proto layers.IPProtocol) *layers.IPv6 {
|
||||||
|
return &layers.IPv6{Version: 6, HopLimit: 64, NextHeader: proto, SrcIP: net.ParseIP("2001:db8::1"), DstIP: net.ParseIP("2001:db8:1::2")}
|
||||||
|
}
|
||||||
|
tcp := func(ip gopacket.NetworkLayer) *layers.TCP {
|
||||||
|
l := &layers.TCP{SrcPort: 49152, DstPort: 443, SYN: true, Window: 65535}
|
||||||
|
require.NoError(t, l.SetNetworkLayerForChecksum(ip))
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
udp := func(ip gopacket.NetworkLayer) *layers.UDP {
|
||||||
|
l := &layers.UDP{SrcPort: 49152, DstPort: 53}
|
||||||
|
require.NoError(t, l.SetNetworkLayerForChecksum(ip))
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
payload := gopacket.Payload("self")
|
||||||
|
nop := layers.IPv4Option{OptionType: 1, OptionLength: 1}
|
||||||
|
|
||||||
|
ip4tcp := v4(layers.IPProtocolTCP)
|
||||||
|
ip4opts := v4(layers.IPProtocolTCP)
|
||||||
|
ip4opts.Options = []layers.IPv4Option{nop, nop, nop, nop}
|
||||||
|
ip4udp := v4(layers.IPProtocolUDP)
|
||||||
|
ip6tcp := v6(layers.IPProtocolTCP)
|
||||||
|
ip6udp := v6(layers.IPProtocolUDP)
|
||||||
|
hopByHop := [8]byte{0, 0, 1, 4} // next header, length 0, PadN of 4
|
||||||
|
|
||||||
|
// Bytes past the length the IP header declares are not part of the
|
||||||
|
// datagram and must not be summed.
|
||||||
|
trailing4 := append(serialize(t, ip4tcp, tcp(ip4tcp), payload), []byte("trailing")...)
|
||||||
|
trailing6 := append(serialize(t, ip6tcp, tcp(ip6tcp), payload), []byte("trailing")...)
|
||||||
|
|
||||||
|
// A datagram padded out past the length UDP declares: the pseudo-header
|
||||||
|
// counts the UDP Length field, so the checksum is the unpadded one.
|
||||||
|
padded4 := append(serialize(t, ip4udp, udp(ip4udp), payload), []byte("pad!")...)
|
||||||
|
binary.BigEndian.PutUint16(padded4[2:4], uint16(len(padded4)))
|
||||||
|
padded6 := append(serialize(t, ip6udp, udp(ip6udp), payload), []byte("pad!")...)
|
||||||
|
binary.BigEndian.PutUint16(padded6[4:6], uint16(len(padded6)-ipv6.HeaderLen))
|
||||||
|
|
||||||
|
// Corrupting the checksum and asking for it back must yield gopacket's
|
||||||
|
// packet, byte for byte.
|
||||||
|
recomputed := []struct {
|
||||||
|
name string
|
||||||
|
pkt []byte
|
||||||
|
cksum int
|
||||||
|
}{
|
||||||
|
{"v4 tcp", serialize(t, ip4tcp, tcp(ip4tcp), payload), 20 + 16},
|
||||||
|
{"v4 tcp with ip options", serialize(t, ip4opts, tcp(ip4opts), payload), 24 + 16},
|
||||||
|
{"v4 udp", serialize(t, ip4udp, udp(ip4udp), payload), 20 + 6},
|
||||||
|
{"v4 tcp header only", serialize(t, ip4tcp, tcp(ip4tcp)), 20 + 16},
|
||||||
|
{"v4 udp header only", serialize(t, ip4udp, udp(ip4udp)), 20 + 6},
|
||||||
|
{"v6 tcp", serialize(t, ip6tcp, tcp(ip6tcp), payload), 40 + 16},
|
||||||
|
{"v6 udp", serialize(t, ip6udp, udp(ip6udp), payload), 40 + 6},
|
||||||
|
{"v6 udp header only", serialize(t, ip6udp, udp(ip6udp)), 40 + 6},
|
||||||
|
{"v6 tcp behind hop-by-hop", withExtensionHeader(serialize(t, ip6tcp, tcp(ip6tcp), payload), layers.IPProtocolIPv6HopByHop, hopByHop), 48 + 16},
|
||||||
|
{"v4 tcp with bytes past the total length", trailing4, 20 + 16},
|
||||||
|
{"v6 tcp with bytes past the payload length", trailing6, 40 + 16},
|
||||||
|
{"v4 udp padded past its declared length", padded4, 20 + 6},
|
||||||
|
{"v6 udp padded past its declared length", padded6, 40 + 6},
|
||||||
|
}
|
||||||
|
for _, tt := range recomputed {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := append([]byte(nil), tt.pkt...)
|
||||||
|
binary.BigEndian.PutUint16(got[tt.cksum:], 0x1234)
|
||||||
|
require.NotEqual(t, tt.pkt, got)
|
||||||
|
SetTransportChecksum(got)
|
||||||
|
assert.Equal(t, tt.pkt, got)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
ip4frag := v4(layers.IPProtocolTCP)
|
||||||
|
ip4frag.Flags = layers.IPv4MoreFragments
|
||||||
|
ip4later := v4(layers.IPProtocolTCP)
|
||||||
|
ip4later.FragOffset = 1
|
||||||
|
ip4icmp := v4(layers.IPProtocolICMPv4)
|
||||||
|
|
||||||
|
badIHL := serialize(t, ip4tcp, tcp(ip4tcp), payload)
|
||||||
|
badIHL[0] = 0x44 // header length 16, shorter than an ipv4 header
|
||||||
|
shortTotalLen := serialize(t, ip4tcp, tcp(ip4tcp), payload)
|
||||||
|
binary.BigEndian.PutUint16(shortTotalLen[2:4], 10) // shorter than the header it introduces
|
||||||
|
cutTCP := serialize(t, ip4tcp, tcp(ip4tcp), payload)
|
||||||
|
binary.BigEndian.PutUint16(cutTCP[2:4], 20+19) // one byte short of a tcp header
|
||||||
|
cutTCP = truncate(cutTCP, 20+19)
|
||||||
|
cutUDP := serialize(t, ip4udp, udp(ip4udp), payload)
|
||||||
|
binary.BigEndian.PutUint16(cutUDP[2:4], 20+7) // one byte short of a udp header
|
||||||
|
cutUDP = truncate(cutUDP, 20+7)
|
||||||
|
// Two bytes short, so a transport header survives whole and the minimum
|
||||||
|
// length check cannot stand in for the bounds check.
|
||||||
|
cutV6 := truncate(serialize(t, ip6tcp, tcp(ip6tcp), payload), 62)
|
||||||
|
fragment := [8]byte{0, 0, 0, 1, 0, 0, 0, 1} // next header, reserved, offset 0 with M set, id
|
||||||
|
overrun4 := serialize(t, ip4udp, udp(ip4udp), payload)
|
||||||
|
binary.BigEndian.PutUint16(overrun4[24:26], uint16(len(overrun4)-20+1)) // one byte past what ip delivered
|
||||||
|
overrun6 := serialize(t, ip6udp, udp(ip6udp), payload)
|
||||||
|
binary.BigEndian.PutUint16(overrun6[44:46], uint16(len(overrun6)-ipv6.HeaderLen+1))
|
||||||
|
shortUDPLen := serialize(t, ip4udp, udp(ip4udp), payload)
|
||||||
|
binary.BigEndian.PutUint16(shortUDPLen[24:26], 7) // shorter than the header it counts
|
||||||
|
|
||||||
|
// Where the checksum cannot be completed the packet is left as it came.
|
||||||
|
untouched := []struct {
|
||||||
|
name string
|
||||||
|
pkt []byte
|
||||||
|
cksum int
|
||||||
|
}{
|
||||||
|
{"v4 first fragment", serialize(t, ip4frag, tcp(ip4frag), payload), 20 + 16},
|
||||||
|
{"v4 later fragment", serialize(t, ip4later, tcp(ip4later), payload), 20 + 16},
|
||||||
|
{"v4 icmp", serialize(t, ip4icmp, &layers.ICMPv4{TypeCode: layers.CreateICMPv4TypeCode(8, 0), Id: 1, Seq: 1}, payload), 20 + 2},
|
||||||
|
{"v4 header length below the minimum", badIHL, 20 + 16},
|
||||||
|
{"v4 total length below the header length", shortTotalLen, 20 + 16},
|
||||||
|
{"v4 truncated below its total length", truncate(serialize(t, ip4tcp, tcp(ip4tcp), payload), 30), -1},
|
||||||
|
{"v4 tcp header cut short", cutTCP, 20 + 16},
|
||||||
|
{"v4 udp header cut short", cutUDP, -1},
|
||||||
|
{"v6 fragment", withExtensionHeader(serialize(t, ip6tcp, tcp(ip6tcp), payload), layers.IPProtocolIPv6Fragment, fragment), 48 + 16},
|
||||||
|
{"v6 truncated below its payload length", truncate(serialize(t, ip6tcp, tcp(ip6tcp), payload), 50), -1},
|
||||||
|
{"v6 truncated with a whole transport header still present", cutV6, 40 + 16},
|
||||||
|
{"v6 extension header chain longer than the walk", extChain(9, 0), 112 + 16},
|
||||||
|
{"v6 extension header chain running past the packet", extChain(8, 255), 104 + 16},
|
||||||
|
{"v4 udp length past the end of the datagram", overrun4, 20 + 6},
|
||||||
|
{"v6 udp length past the end of the datagram", overrun6, 40 + 6},
|
||||||
|
{"v4 udp length below a udp header", shortUDPLen, 20 + 6},
|
||||||
|
}
|
||||||
|
for _, tt := range untouched {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if tt.cksum >= 0 {
|
||||||
|
binary.BigEndian.PutUint16(tt.pkt[tt.cksum:], 0x1234)
|
||||||
|
}
|
||||||
|
want := append([]byte(nil), tt.pkt...)
|
||||||
|
SetTransportChecksum(tt.pkt)
|
||||||
|
assert.Equal(t, want, tt.pkt)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("too short to carry a header", func(t *testing.T) {
|
||||||
|
for _, pkt := range [][]byte{nil, {}, {0x45}, {0x60}} {
|
||||||
|
assert.NotPanics(t, func() { SetTransportChecksum(pkt) })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("tcp checksum of zero goes out as zero", func(t *testing.T) {
|
||||||
|
pkt := serialize(t, ip4tcp, tcp(ip4tcp), gopacket.Payload{0, 0})
|
||||||
|
c := binary.BigEndian.Uint16(pkt[36:38])
|
||||||
|
require.NotZero(t, c)
|
||||||
|
// Only udp reserves zero to mean "not computed", so tcp keeps it.
|
||||||
|
binary.BigEndian.PutUint16(pkt[40:42], c)
|
||||||
|
SetTransportChecksum(pkt)
|
||||||
|
assert.Zero(t, binary.BigEndian.Uint16(pkt[36:38]))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("udp checksum of zero goes out as 0xffff", func(t *testing.T) {
|
||||||
|
pkt := serialize(t, ip4udp, udp(ip4udp), gopacket.Payload{0, 0})
|
||||||
|
c := binary.BigEndian.Uint16(pkt[26:28])
|
||||||
|
require.NotZero(t, c)
|
||||||
|
// The one's complement sum is now 0xffff - c; adding c to the payload
|
||||||
|
// makes it 0xffff, whose complement is zero.
|
||||||
|
binary.BigEndian.PutUint16(pkt[28:30], c)
|
||||||
|
SetTransportChecksum(pkt)
|
||||||
|
assert.Equal(t, uint16(0xffff), binary.BigEndian.Uint16(pkt[26:28]))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFold(t *testing.T) {
|
||||||
|
// 0xffff is the fold's fixed point, so a loop bound one notch tight never
|
||||||
|
// terminates on it.
|
||||||
|
for _, tt := range []struct {
|
||||||
|
in uint32
|
||||||
|
want uint16
|
||||||
|
}{
|
||||||
|
{0, 0},
|
||||||
|
{0xffff, 0xffff},
|
||||||
|
{0x10000, 1},
|
||||||
|
{0x1fffe, 0xffff},
|
||||||
|
{0xffffffff, 0xffff},
|
||||||
|
} {
|
||||||
|
assert.Equal(t, tt.want, fold(tt.in))
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
-9
@@ -2,11 +2,16 @@ package iputil
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
|
||||||
"golang.org/x/net/ipv4"
|
"golang.org/x/net/ipv4"
|
||||||
"golang.org/x/net/ipv6"
|
"golang.org/x/net/ipv6"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrIPv6CouldNotFindPayload is returned when the ipv6 extension header chain is truncated before a terminal
|
||||||
|
// upper layer protocol is reached.
|
||||||
|
var ErrIPv6CouldNotFindPayload = errors.New("could not find payload in ipv6 packet")
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// MaxIPv4RejectPacketSize is the largest IPv4 reject packet:
|
// MaxIPv4RejectPacketSize is the largest IPv4 reject packet:
|
||||||
// - 20 byte ipv4 header
|
// - 20 byte ipv4 header
|
||||||
@@ -22,6 +27,13 @@ const (
|
|||||||
maxIPv6RejectPacketSize = ipv6.HeaderLen + 8 + 1000
|
maxIPv6RejectPacketSize = ipv6.HeaderLen + 8 + 1000
|
||||||
|
|
||||||
MaxRejectPacketSize = maxIPv6RejectPacketSize
|
MaxRejectPacketSize = maxIPv6RejectPacketSize
|
||||||
|
|
||||||
|
IPProtocolICMP = 1
|
||||||
|
IPProtocolICMPv6 = 58
|
||||||
|
IPProtocolTCP = 6
|
||||||
|
IPProtocolUDP = 17
|
||||||
|
ICMPv6TypeEchoRequest = 128
|
||||||
|
ICMPv6TypeEchoReply = 129
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateRejectPacket(packet []byte, out []byte) []byte {
|
func CreateRejectPacket(packet []byte, out []byte) []byte {
|
||||||
@@ -199,8 +211,8 @@ func ipv4CreateRejectTCPPacket(packet []byte, out []byte) []byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ipv6CreateRejectPacket(packet []byte, out []byte) []byte {
|
func ipv6CreateRejectPacket(packet []byte, out []byte) []byte {
|
||||||
proto, offset, isFragment := ipv6FindUpperProtocol(packet)
|
proto, offset, isFragment, _, err := IPv6FindUpperProtocol(packet)
|
||||||
if isFragment {
|
if err != nil || isFragment {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
switch proto {
|
switch proto {
|
||||||
@@ -333,40 +345,57 @@ func ipv6CreateRejectTCPPacket(packet []byte, out []byte, offset int) []byte {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func ipv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragment bool) {
|
// IPv6FindUpperProtocol walks the ipv6 extension header chain and returns the upper layer protocol, the offset it begins at, and whether the packet is a non-first fragment.
|
||||||
|
// Only the RFC 8200 and IANA extension headers below are walked.
|
||||||
|
// Everything else, including Mobility (135), HIP (139), Shim6 (140), experimental 253/254, and real upper layer protocols like SCTP or GRE, is terminal.
|
||||||
|
// For a non-first fragment the returned protocol is the fragmented protocol and offset points at the fragment header, there is no transport header to locate.
|
||||||
|
// Returns ErrIPv6CouldNotFindPayload if packet is smaller than an ipv6 header, or the chain is truncated, or if more than 8 extension headers are present.
|
||||||
|
func IPv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragment bool, anyFragment bool, err error) {
|
||||||
|
const maxIPv6ExtHeaders = 8
|
||||||
|
if len(packet) < ipv6.HeaderLen {
|
||||||
|
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
||||||
|
}
|
||||||
nextHeader = packet[6]
|
nextHeader = packet[6]
|
||||||
offset = ipv6.HeaderLen
|
offset = ipv6.HeaderLen
|
||||||
|
|
||||||
for {
|
for range maxIPv6ExtHeaders {
|
||||||
switch nextHeader {
|
switch nextHeader {
|
||||||
case 0, 43, 60: // Hop-by-Hop, Routing, Destination
|
case 0, 43, 60: // Hop-by-Hop, Routing, Destination
|
||||||
if len(packet) < offset+2 {
|
if len(packet) < offset+2 {
|
||||||
return nextHeader, offset, isFragment
|
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
nextHeader = packet[offset]
|
nextHeader = packet[offset]
|
||||||
offset += (int(packet[offset+1]) + 1) << 3
|
offset += (int(packet[offset+1]) + 1) << 3
|
||||||
|
|
||||||
case 44: // Fragment
|
case 44: // Fragment
|
||||||
if len(packet) < offset+8 {
|
if len(packet) < offset+8 {
|
||||||
return nextHeader, offset, isFragment
|
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
|
anyFragment = true
|
||||||
|
// Non-first fragments carry no transport header, report the fragmented protocol and stop
|
||||||
if packet[offset+2] != 0 || packet[offset+3]&0xf8 != 0 {
|
if packet[offset+2] != 0 || packet[offset+3]&0xf8 != 0 {
|
||||||
isFragment = true
|
return packet[offset], offset, true, anyFragment, nil
|
||||||
}
|
}
|
||||||
nextHeader = packet[offset]
|
nextHeader = packet[offset]
|
||||||
offset += 8
|
offset += 8
|
||||||
|
|
||||||
case 51: // AH
|
case 51: // AH
|
||||||
if len(packet) < offset+2 {
|
if len(packet) < offset+2 {
|
||||||
return nextHeader, offset, isFragment
|
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
nextHeader = packet[offset]
|
nextHeader = packet[offset]
|
||||||
offset += (int(packet[offset+1]) + 2) << 2
|
offset += (int(packet[offset+1]) + 2) << 2
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nextHeader, offset, isFragment
|
if offset > len(packet) {
|
||||||
|
// A prior extension header can declare a length that advances offset past the packet, reject this.
|
||||||
|
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
||||||
|
}
|
||||||
|
return nextHeader, offset, isFragment, anyFragment, nil //success!
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Fail closed
|
||||||
|
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateICMPEchoResponse(packet, out []byte) []byte {
|
func CreateICMPEchoResponse(packet, out []byte) []byte {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
"golang.org/x/net/ipv4"
|
"golang.org/x/net/ipv4"
|
||||||
"golang.org/x/net/ipv6"
|
"golang.org/x/net/ipv6"
|
||||||
)
|
)
|
||||||
@@ -515,3 +516,75 @@ func TestCreateICMPEchoResponse_IPv6_NotICMPv6(t *testing.T) {
|
|||||||
result := CreateICMPEchoResponse(packet, out)
|
result := CreateICMPEchoResponse(packet, out)
|
||||||
assert.Nil(t, result)
|
assert.Nil(t, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_IPv6FindUpperProtocol(t *testing.T) {
|
||||||
|
src := net.ParseIP("fd00::1")
|
||||||
|
dst := net.ParseIP("fd00::2")
|
||||||
|
|
||||||
|
// 8 byte extension/transport stand-ins, first byte is the next header, second is the length field
|
||||||
|
extToTCP := []byte{6, 0, 0, 0, 0, 0, 0, 0} // len 0 -> 8 bytes, next = TCP
|
||||||
|
extToUDP := []byte{17, 0, 0, 0, 0, 0, 0, 0} // len 0 -> 8 bytes, next = UDP
|
||||||
|
extToRouting := []byte{43, 0, 0, 0, 0, 0, 0, 0} // len 0 -> 8 bytes, next = Routing
|
||||||
|
ahToUDP := []byte{17, 0, 0, 0, 0, 0, 0, 0} // AH len 0 -> (0+2)<<2 = 8 bytes, next = UDP
|
||||||
|
firstFragToUDP := []byte{17, 0, 0, 1, 0, 0, 0, 1} // frag offset 0, M=1, next = UDP
|
||||||
|
nonFirstFrag := []byte{17, 0, 0, 9, 0, 0, 0, 1} // frag offset non-zero, next = UDP
|
||||||
|
transport := []byte{0, 80, 1, 187, 0, 0, 0, 0} // stand-in bytes, IPv6FindUpperProtocol never reads ports
|
||||||
|
extToHbH := []byte{0, 0, 0, 0, 0, 0, 0, 0} // len 0 -> 8 bytes, next = Hop-by-Hop
|
||||||
|
|
||||||
|
// 8 walked headers spend the budget before the 9th slot's terminal is ever classified. This is the
|
||||||
|
// report 4040546 shape: without failing closed the walk hands back offset 104, and a caller reads ports
|
||||||
|
// from the attacker's bytes there.
|
||||||
|
var budgetChain []byte
|
||||||
|
for range 7 {
|
||||||
|
budgetChain = append(budgetChain, extToHbH...)
|
||||||
|
}
|
||||||
|
budgetChain = append(budgetChain, extToTCP...)
|
||||||
|
budgetChain = append(budgetChain, transport...)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
nextHeader uint8
|
||||||
|
payload []byte
|
||||||
|
wantProto uint8
|
||||||
|
wantOffset int
|
||||||
|
wantFragment bool
|
||||||
|
wantAnyFrag bool
|
||||||
|
wantErr error
|
||||||
|
}{
|
||||||
|
{"plain udp", 17, transport, 17, ipv6.HeaderLen, false, false, nil},
|
||||||
|
{"hop-by-hop then tcp", 0, append(extToTCP, transport...), 6, ipv6.HeaderLen + 8, false, false, nil},
|
||||||
|
{"routing then tcp", 43, append(extToTCP, transport...), 6, ipv6.HeaderLen + 8, false, false, nil},
|
||||||
|
{"destination then udp", 60, append(extToUDP, transport...), 17, ipv6.HeaderLen + 8, false, false, nil},
|
||||||
|
{"hop-by-hop, routing, then tcp", 0, append(append(extToRouting, extToTCP...), transport...), 6, ipv6.HeaderLen + 16, false, false, nil},
|
||||||
|
{"ah then udp", 51, append(ahToUDP, transport...), 17, ipv6.HeaderLen + 8, false, false, nil},
|
||||||
|
{"first fragment walks to transport", 44, append(firstFragToUDP, transport...), 17, ipv6.HeaderLen + 8, false, true, nil},
|
||||||
|
{"non-first fragment stops", 44, append(nonFirstFrag, transport...), 17, ipv6.HeaderLen, true, true, nil},
|
||||||
|
{"unknown protocol is terminal", 132, transport, 132, ipv6.HeaderLen, false, false, nil}, // SCTP
|
||||||
|
{"truncated extension header", 0, nil, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
|
||||||
|
// Destination Options with a declared length (255+1)*8 = 2048 that runs past the 48 byte buffer, next = SCTP
|
||||||
|
{"extension length past buffer", 0, []byte{132, 255, 0, 0, 0, 0, 0, 0}, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
|
||||||
|
{"budget exhausted fails closed", 0, budgetChain, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
packet := makeIPv6Packet(src, dst, tt.nextHeader, tt.payload)
|
||||||
|
proto, offset, isFragment, anyFragment, err := IPv6FindUpperProtocol(packet)
|
||||||
|
if tt.wantErr != nil {
|
||||||
|
require.ErrorIs(t, err, tt.wantErr)
|
||||||
|
} else {
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
assert.Equal(t, tt.wantProto, proto)
|
||||||
|
assert.Equal(t, tt.wantOffset, offset)
|
||||||
|
assert.Equal(t, tt.wantFragment, isFragment)
|
||||||
|
assert.Equal(t, tt.wantAnyFrag, anyFragment)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// A packet smaller than an ipv6 header must error rather than panic reading byte 6
|
||||||
|
t.Run("shorter than ipv6 header", func(t *testing.T) {
|
||||||
|
_, _, _, _, err := IPv6FindUpperProtocol(make([]byte, 6))
|
||||||
|
assert.ErrorIs(t, err, ErrIPv6CouldNotFindPayload)
|
||||||
|
})
|
||||||
|
}
|
||||||
+88
-10
@@ -15,10 +15,12 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
|
"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/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/logging"
|
"github.com/slackhq/nebula/logging"
|
||||||
|
"github.com/slackhq/nebula/nicfinder"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
"github.com/slackhq/nebula/util"
|
"github.com/slackhq/nebula/util"
|
||||||
)
|
)
|
||||||
@@ -34,8 +36,18 @@ type LightHouse struct {
|
|||||||
|
|
||||||
myVpnNetworks []netip.Prefix
|
myVpnNetworks []netip.Prefix
|
||||||
myVpnNetworksTable *bart.Lite
|
myVpnNetworksTable *bart.Lite
|
||||||
|
// myVpnAddrsTable contains our overlay host addrs, as opposed to the overlay networks
|
||||||
|
myVpnAddrsTable *bart.Lite
|
||||||
punchy *Punchy
|
punchy *Punchy
|
||||||
|
|
||||||
|
// localAddrsFn enumerates the underlay addresses we advertise. It is a field so tests can supply simulated
|
||||||
|
// addresses rather than whatever this machine's NICs happen to be. Set it before Start.
|
||||||
|
localAddrsFn func(*LocalAllowList) []netip.Addr
|
||||||
|
|
||||||
|
// lastLocalAddrsErr is the previous localAddrsFn failure. Enumeration runs on every update, so an
|
||||||
|
// unchanged failure is demoted to Debug rather than warning every lighthouse.interval forever.
|
||||||
|
lastLocalAddrsErr atomic.Pointer[string]
|
||||||
|
|
||||||
// Local cache of answers from light houses
|
// Local cache of answers from light houses
|
||||||
// map of vpn addr to answers
|
// map of vpn addr to answers
|
||||||
addrMap map[netip.Addr]*RemoteList
|
addrMap map[netip.Addr]*RemoteList
|
||||||
@@ -70,6 +82,8 @@ type LightHouse struct {
|
|||||||
|
|
||||||
updateTrigger chan struct{}
|
updateTrigger chan struct{}
|
||||||
queryChan chan netip.Addr
|
queryChan chan netip.Addr
|
||||||
|
// queryDropped counts queries QueryServer dropped because queryChan was full.
|
||||||
|
queryDropped metrics.Counter
|
||||||
|
|
||||||
calculatedRemotes atomic.Pointer[bart.Table[[]*calculatedRemote]] // Maps VpnAddr to []*calculatedRemote
|
calculatedRemotes atomic.Pointer[bart.Table[[]*calculatedRemote]] // Maps VpnAddr to []*calculatedRemote
|
||||||
|
|
||||||
@@ -100,13 +114,21 @@ func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, c
|
|||||||
amLighthouse: amLighthouse,
|
amLighthouse: amLighthouse,
|
||||||
myVpnNetworks: cs.myVpnNetworks,
|
myVpnNetworks: cs.myVpnNetworks,
|
||||||
myVpnNetworksTable: cs.myVpnNetworksTable,
|
myVpnNetworksTable: cs.myVpnNetworksTable,
|
||||||
|
myVpnAddrsTable: cs.myVpnAddrsTable,
|
||||||
addrMap: make(map[netip.Addr]*RemoteList),
|
addrMap: make(map[netip.Addr]*RemoteList),
|
||||||
nebulaPort: nebulaPort,
|
nebulaPort: nebulaPort,
|
||||||
punchy: p,
|
punchy: p,
|
||||||
updateTrigger: make(chan struct{}, 1),
|
updateTrigger: make(chan struct{}, 1),
|
||||||
queryChan: make(chan netip.Addr, c.GetUint32("handshakes.query_buffer", 64)),
|
queryChan: make(chan netip.Addr, c.GetUint32("handshakes.query_buffer", 1024)),
|
||||||
|
queryDropped: metrics.GetOrRegisterCounter("lighthouse.query.dropped", nil),
|
||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
|
h.localAddrsFn = func(al *LocalAllowList) []netip.Addr {
|
||||||
|
addrs, err := nicfinder.Find(ctx, h.l, al)
|
||||||
|
h.logLocalAddrsErr(err)
|
||||||
|
return addrs
|
||||||
|
}
|
||||||
|
|
||||||
lighthouses := make([]netip.Addr, 0)
|
lighthouses := make([]netip.Addr, 0)
|
||||||
h.lighthouses.Store(&lighthouses)
|
h.lighthouses.Store(&lighthouses)
|
||||||
staticList := make(map[netip.Addr]struct{})
|
staticList := make(map[netip.Addr]struct{})
|
||||||
@@ -116,18 +138,21 @@ func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, c
|
|||||||
h.metrics = newLighthouseMetrics()
|
h.metrics = newLighthouseMetrics()
|
||||||
}
|
}
|
||||||
|
|
||||||
err := h.reload(c, true)
|
err := h.reload(c, true, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c.RegisterReloadCallback(func(c *config.C) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
err := h.reload(c, false)
|
r.RestartRequiredIfChanged("lighthouse.am_lighthouse", "listen.port", "handshakes.query_buffer", "stats.lighthouse_metrics")
|
||||||
|
err := h.reload(c, false, r)
|
||||||
switch v := err.(type) {
|
switch v := err.(type) {
|
||||||
case *util.ContextualError:
|
case *util.ContextualError:
|
||||||
v.Log(l)
|
v.Log(l)
|
||||||
|
r.Failed()
|
||||||
case error:
|
case error:
|
||||||
l.Error("failed to reload lighthouse", "error", err)
|
l.Error("failed to reload lighthouse", "error", err)
|
||||||
|
r.Failed()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -168,7 +193,8 @@ func (lh *LightHouse) GetUpdateInterval() int64 {
|
|||||||
return lh.interval.Load()
|
return lh.interval.Load()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lh *LightHouse) reload(c *config.C, initial bool) error {
|
// r is nil on the initial load
|
||||||
|
func (lh *LightHouse) reload(c *config.C, initial bool, r *config.Reload) error {
|
||||||
if initial || c.HasChanged("lighthouse.advertise_addrs") {
|
if initial || c.HasChanged("lighthouse.advertise_addrs") {
|
||||||
rawAdvAddrs := c.GetStringSlice("lighthouse.advertise_addrs", []string{})
|
rawAdvAddrs := c.GetStringSlice("lighthouse.advertise_addrs", []string{})
|
||||||
advAddrs := make([]netip.AddrPort, 0)
|
advAddrs := make([]netip.AddrPort, 0)
|
||||||
@@ -203,6 +229,7 @@ func (lh *LightHouse) reload(c *config.C, initial bool) error {
|
|||||||
"addr", rawAddr,
|
"addr", rawAddr,
|
||||||
"entry", i+1,
|
"entry", i+1,
|
||||||
)
|
)
|
||||||
|
r.Failed()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,7 +364,13 @@ func (lh *LightHouse) reload(c *config.C, initial bool) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if initial || c.HasChanged("relay.relays") {
|
// am_relay decides whether relay.relays applies to us at all
|
||||||
|
if initial || c.HasChanged("relay.relays") || c.HasChanged("relay.am_relay") {
|
||||||
|
var before []netip.Addr
|
||||||
|
if !initial {
|
||||||
|
before = lh.GetRelaysForMe()
|
||||||
|
}
|
||||||
|
|
||||||
switch c.GetBool("relay.am_relay", false) {
|
switch c.GetBool("relay.am_relay", false) {
|
||||||
case true:
|
case true:
|
||||||
// Relays aren't allowed to specify other relays
|
// Relays aren't allowed to specify other relays
|
||||||
@@ -355,6 +388,7 @@ func (lh *LightHouse) reload(c *config.C, initial bool) error {
|
|||||||
"relay", v,
|
"relay", v,
|
||||||
"error", err,
|
"error", err,
|
||||||
)
|
)
|
||||||
|
r.Failed()
|
||||||
} else {
|
} else {
|
||||||
lh.l.Info("Read relay from config", "relay", v)
|
lh.l.Info("Read relay from config", "relay", v)
|
||||||
relaysForMe = append(relaysForMe, configRIP)
|
relaysForMe = append(relaysForMe, configRIP)
|
||||||
@@ -362,6 +396,11 @@ func (lh *LightHouse) reload(c *config.C, initial bool) error {
|
|||||||
}
|
}
|
||||||
lh.relaysForMe.Store(&relaysForMe)
|
lh.relaysForMe.Store(&relaysForMe)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tell the lighthouses now rather than at the next interval, but only when what we advertise changed
|
||||||
|
if !initial && !slices.Equal(before, lh.GetRelaysForMe()) {
|
||||||
|
lh.TriggerUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -494,14 +533,19 @@ func (lh *LightHouse) Query(vpnAddr netip.Addr) *RemoteList {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// QueryServer is asynchronous so no reply should be expected
|
// QueryServer is asynchronous and non-blocking, no reply should be expected.
|
||||||
|
// If the query channel is full, the query is dropped.
|
||||||
func (lh *LightHouse) QueryServer(vpnAddr netip.Addr) {
|
func (lh *LightHouse) QueryServer(vpnAddr netip.Addr) {
|
||||||
// Don't put lighthouse addrs in the query channel because we can't query lighthouses about lighthouses
|
// Don't put lighthouse addrs in the query channel because we can't query lighthouses about lighthouses
|
||||||
if lh.amLighthouse || lh.IsLighthouseAddr(vpnAddr) {
|
if lh.amLighthouse || lh.IsLighthouseAddr(vpnAddr) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
lh.queryChan <- vpnAddr
|
select {
|
||||||
|
case lh.queryChan <- vpnAddr:
|
||||||
|
default:
|
||||||
|
lh.queryDropped.Inc(1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lh *LightHouse) QueryCache(vpnAddrs []netip.Addr) *RemoteList {
|
func (lh *LightHouse) QueryCache(vpnAddrs []netip.Addr) *RemoteList {
|
||||||
@@ -905,6 +949,26 @@ func (lh *LightHouse) TriggerUpdate() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// logLocalAddrsErr reports a localAddrs failure at Warn the first time it is seen and at Debug while
|
||||||
|
// it persists unchanged, so a permanent failure does not warn on every update forever.
|
||||||
|
func (lh *LightHouse) logLocalAddrsErr(err error) {
|
||||||
|
if err == nil {
|
||||||
|
lh.lastLocalAddrsErr.Store(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := err.Error()
|
||||||
|
prev := lh.lastLocalAddrsErr.Swap(&msg)
|
||||||
|
if prev != nil && *prev == msg {
|
||||||
|
if lh.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
|
lh.l.Debug("Failed to collect local addresses to advertise", "error", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
lh.l.Warn("Failed to collect local addresses to advertise", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
func (lh *LightHouse) SendUpdate() {
|
func (lh *LightHouse) SendUpdate() {
|
||||||
var v4 []*V4AddrPort
|
var v4 []*V4AddrPort
|
||||||
var v6 []*V6AddrPort
|
var v6 []*V6AddrPort
|
||||||
@@ -918,7 +982,7 @@ func (lh *LightHouse) SendUpdate() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lal := lh.GetLocalAllowList()
|
lal := lh.GetLocalAllowList()
|
||||||
for _, e := range localAddrs(lh.l, lal) {
|
for _, e := range lh.localAddrsFn(lal) {
|
||||||
if lh.myVpnNetworksTable.Contains(e) {
|
if lh.myVpnNetworksTable.Contains(e) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -1150,6 +1214,17 @@ func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, fromVpnAddrs []neti
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Don't respond to requests for us.
|
||||||
|
if lhh.lh.myVpnAddrsTable.Contains(queryVpnAddr) {
|
||||||
|
if lhh.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
|
lhh.l.Debug("Ignoring HostQuery for one of my own addresses",
|
||||||
|
"fromVpnAddrs", fromVpnAddrs,
|
||||||
|
"queryVpnAddr", queryVpnAddr,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
found, ln, err := lhh.lh.queryAndPrepMessage(queryVpnAddr, func(c *cache) (int, error) {
|
found, ln, err := lhh.lh.queryAndPrepMessage(queryVpnAddr, func(c *cache) (int, error) {
|
||||||
n = lhh.resetMeta()
|
n = lhh.resetMeta()
|
||||||
n.Type = NebulaMeta_HostQueryReply
|
n.Type = NebulaMeta_HostQueryReply
|
||||||
@@ -1186,10 +1261,13 @@ func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, fromVpnAddrs []neti
|
|||||||
// sendHostPunchNotification signals the other side to punch some zero byte udp packets
|
// sendHostPunchNotification signals the other side to punch some zero byte udp packets
|
||||||
func (lhh *LightHouseHandler) sendHostPunchNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, punchNotifDest netip.Addr, w EncWriter) {
|
func (lhh *LightHouseHandler) sendHostPunchNotification(n *NebulaMeta, fromVpnAddrs []netip.Addr, punchNotifDest netip.Addr, w EncWriter) {
|
||||||
whereToPunch := fromVpnAddrs[0]
|
whereToPunch := fromVpnAddrs[0]
|
||||||
|
// Resolve the target before taking the querier's RemoteList lock below. GetHostInfo takes the
|
||||||
|
// hostmap lock, and the hostmap is taken before the lighthouse, which is taken before a
|
||||||
|
// RemoteList, so looking it up inside the callback would deadlock.
|
||||||
|
targetHI := lhh.lh.ifce.GetHostInfo(punchNotifDest)
|
||||||
found, ln, err := lhh.lh.queryAndPrepMessage(whereToPunch, func(c *cache) (int, error) {
|
found, ln, err := lhh.lh.queryAndPrepMessage(whereToPunch, func(c *cache) (int, error) {
|
||||||
n = lhh.resetMeta()
|
n = lhh.resetMeta()
|
||||||
n.Type = NebulaMeta_HostPunchNotification
|
n.Type = NebulaMeta_HostPunchNotification
|
||||||
targetHI := lhh.lh.ifce.GetHostInfo(punchNotifDest)
|
|
||||||
var useVersion cert.Version
|
var useVersion cert.Version
|
||||||
if targetHI == nil {
|
if targetHI == nil {
|
||||||
useVersion = lhh.lh.ifce.GetCertState().initiatingVersion
|
useVersion = lhh.lh.ifce.GetCertState().initiatingVersion
|
||||||
|
|||||||
+369
-65
@@ -1,16 +1,21 @@
|
|||||||
package nebula
|
package nebula
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"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/test"
|
"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"
|
||||||
"go.yaml.in/yaml/v3"
|
"go.yaml.in/yaml/v3"
|
||||||
@@ -27,15 +32,27 @@ func TestOldIPv4Only(t *testing.T) {
|
|||||||
assert.Equal(t, binary.BigEndian.Uint32(bp[:]), m.GetAddr())
|
assert.Equal(t, binary.BigEndian.Uint32(bp[:]), m.GetAddr())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func testCertState(networks ...netip.Prefix) *CertState {
|
||||||
|
cs := &CertState{
|
||||||
|
myVpnNetworks: networks,
|
||||||
|
myVpnNetworksTable: new(bart.Lite),
|
||||||
|
myVpnAddrs: make([]netip.Addr, 0, len(networks)),
|
||||||
|
myVpnAddrsTable: new(bart.Lite),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, n := range networks {
|
||||||
|
cs.myVpnNetworksTable.Insert(n)
|
||||||
|
cs.myVpnAddrs = append(cs.myVpnAddrs, n.Addr())
|
||||||
|
cs.myVpnAddrsTable.Insert(netip.PrefixFrom(n.Addr(), n.Addr().BitLen()))
|
||||||
|
}
|
||||||
|
|
||||||
|
return cs
|
||||||
|
}
|
||||||
|
|
||||||
func Test_lhStaticMapping(t *testing.T) {
|
func Test_lhStaticMapping(t *testing.T) {
|
||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/16")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/16")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
lh1 := "10.128.0.2"
|
lh1 := "10.128.0.2"
|
||||||
|
|
||||||
c := config.NewC(l)
|
c := config.NewC(l)
|
||||||
@@ -55,12 +72,7 @@ func Test_lhStaticMapping(t *testing.T) {
|
|||||||
func TestReloadLighthouseInterval(t *testing.T) {
|
func TestReloadLighthouseInterval(t *testing.T) {
|
||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/16")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/16")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
lh1 := "10.128.0.2"
|
lh1 := "10.128.0.2"
|
||||||
|
|
||||||
c := config.NewC(l)
|
c := config.NewC(l)
|
||||||
@@ -75,27 +87,22 @@ func TestReloadLighthouseInterval(t *testing.T) {
|
|||||||
lh.ifce = &mockEncWriter{}
|
lh.ifce = &mockEncWriter{}
|
||||||
|
|
||||||
// The first one routine is kicked off by main.go currently, lets make sure that one dies
|
// The first one routine is kicked off by main.go currently, lets make sure that one dies
|
||||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 5"))
|
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 5").Err)
|
||||||
assert.Equal(t, int64(5), lh.interval.Load())
|
assert.Equal(t, int64(5), lh.interval.Load())
|
||||||
|
|
||||||
// Subsequent calls are killed off by the LightHouse.Reload function
|
// Subsequent calls are killed off by the LightHouse.Reload function
|
||||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 10"))
|
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 10").Err)
|
||||||
assert.Equal(t, int64(10), lh.interval.Load())
|
assert.Equal(t, int64(10), lh.interval.Load())
|
||||||
|
|
||||||
// If this completes then nothing is stealing our reload routine
|
// If this completes then nothing is stealing our reload routine
|
||||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 11"))
|
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 11").Err)
|
||||||
assert.Equal(t, int64(11), lh.interval.Load())
|
assert.Equal(t, int64(11), lh.interval.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkLighthouseHandleRequest(b *testing.B) {
|
func BenchmarkLighthouseHandleRequest(b *testing.B) {
|
||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/0")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/0")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
|
|
||||||
c := config.NewC(l)
|
c := config.NewC(l)
|
||||||
lh, err := NewLightHouseFromConfig(b.Context(), l, c, cs, nil, nil)
|
lh, err := NewLightHouseFromConfig(b.Context(), l, c, cs, nil, nil)
|
||||||
@@ -195,12 +202,7 @@ func TestLighthouse_Memory(t *testing.T) {
|
|||||||
c.Settings["listen"] = map[string]any{"port": 4242}
|
c.Settings["listen"] = map[string]any{"port": 4242}
|
||||||
|
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
||||||
lh.ifce = &mockEncWriter{}
|
lh.ifce = &mockEncWriter{}
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -280,12 +282,7 @@ func TestLighthouse_reload(t *testing.T) {
|
|||||||
c.Settings["listen"] = map[string]any{"port": 4242}
|
c.Settings["listen"] = map[string]any{"port": 4242}
|
||||||
|
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
|
|
||||||
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -299,7 +296,7 @@ func TestLighthouse_reload(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
c.ReloadConfigString(string(rc))
|
c.ReloadConfigString(string(rc))
|
||||||
|
|
||||||
err = lh.reload(c, false)
|
err = lh.reload(c, false, nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,12 +312,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
|
|
||||||
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -342,7 +334,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
rc, err := yaml.Marshal(nc)
|
rc, err := yaml.Marshal(nc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||||
|
|
||||||
rl := lh.Query(staticHost)
|
rl := lh.Query(staticHost)
|
||||||
require.NotNil(t, rl)
|
require.NotNil(t, rl)
|
||||||
@@ -358,7 +350,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
rc, err = yaml.Marshal(nc)
|
rc, err = yaml.Marshal(nc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||||
|
|
||||||
rl = lh.Query(staticHost)
|
rl = lh.Query(staticHost)
|
||||||
require.NotNil(t, rl)
|
require.NotNil(t, rl)
|
||||||
@@ -366,7 +358,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
assert.Equal(t, []netip.AddrPort{netip.MustParseAddrPort("1.1.1.1:4242")}, rl.CopyAddrs([]netip.Prefix{}))
|
assert.Equal(t, []netip.AddrPort{netip.MustParseAddrPort("1.1.1.1:4242")}, rl.CopyAddrs([]netip.Prefix{}))
|
||||||
|
|
||||||
// Reload with the same config. An unchanged entry must not duplicate.
|
// Reload with the same config. An unchanged entry must not duplicate.
|
||||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||||
|
|
||||||
rl = lh.Query(staticHost)
|
rl = lh.Query(staticHost)
|
||||||
require.NotNil(t, rl)
|
require.NotNil(t, rl)
|
||||||
@@ -381,7 +373,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
rc, err = yaml.Marshal(nc)
|
rc, err = yaml.Marshal(nc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||||
|
|
||||||
// Add a second host alongside the first. Both should be present, neither duplicated.
|
// Add a second host alongside the first. Both should be present, neither duplicated.
|
||||||
nc = map[string]any{
|
nc = map[string]any{
|
||||||
@@ -392,7 +384,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
rc, err = yaml.Marshal(nc)
|
rc, err = yaml.Marshal(nc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||||
|
|
||||||
rl = lh.Query(staticHost)
|
rl = lh.Query(staticHost)
|
||||||
require.NotNil(t, rl)
|
require.NotNil(t, rl)
|
||||||
@@ -414,7 +406,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
rc, err = yaml.Marshal(nc)
|
rc, err = yaml.Marshal(nc)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||||
|
|
||||||
_, isStatic := lh.GetStaticHostList()[staticHost]
|
_, isStatic := lh.GetStaticHostList()[staticHost]
|
||||||
assert.False(t, isStatic)
|
assert.False(t, isStatic)
|
||||||
@@ -429,7 +421,9 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
|||||||
assert.Equal(t, []netip.AddrPort{netip.MustParseAddrPort("3.3.3.3:4242")}, rl.CopyAddrs([]netip.Prefix{}))
|
assert.Equal(t, []netip.AddrPort{netip.MustParseAddrPort("3.3.3.3:4242")}, rl.CopyAddrs([]netip.Prefix{}))
|
||||||
}
|
}
|
||||||
|
|
||||||
func newLHHostRequest(fromAddr netip.AddrPort, myVpnIp, queryVpnIp netip.Addr, lhh *LightHouseHandler) testLhReply {
|
// sendLHHostRequest delivers a HostQuery to lhh and hands back the writer that
|
||||||
|
// captured what it emitted. Pass a nil filter to see every message.
|
||||||
|
func sendLHHostRequest(fromAddr netip.AddrPort, myVpnIp, queryVpnIp netip.Addr, lhh *LightHouseHandler, filter *NebulaMeta_MessageType) *testEncWriter {
|
||||||
req := &NebulaMeta{
|
req := &NebulaMeta{
|
||||||
Type: NebulaMeta_HostQuery,
|
Type: NebulaMeta_HostQuery,
|
||||||
Details: &NebulaMetaDetails{},
|
Details: &NebulaMetaDetails{},
|
||||||
@@ -447,12 +441,59 @@ func newLHHostRequest(fromAddr netip.AddrPort, myVpnIp, queryVpnIp netip.Addr, l
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
filter := NebulaMeta_HostQueryReply
|
w := &testEncWriter{metaFilter: filter}
|
||||||
w := &testEncWriter{
|
|
||||||
metaFilter: &filter,
|
|
||||||
}
|
|
||||||
lhh.HandleRequest(fromAddr, []netip.Addr{myVpnIp}, b, w)
|
lhh.HandleRequest(fromAddr, []netip.Addr{myVpnIp}, b, w)
|
||||||
return w.lastReply
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLHHostRequest(fromAddr netip.AddrPort, myVpnIp, queryVpnIp netip.Addr, lhh *LightHouseHandler) testLhReply {
|
||||||
|
filter := NebulaMeta_HostQueryReply
|
||||||
|
return sendLHHostRequest(fromAddr, myVpnIp, queryVpnIp, lhh, &filter).lastReply
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLighthouse_IgnoresHostQueryForItself(t *testing.T) {
|
||||||
|
// Validate that we don't answer host queries for our own address.
|
||||||
|
l := test.NewLogger()
|
||||||
|
|
||||||
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
|
myVpnIp := myVpnNet.Addr()
|
||||||
|
|
||||||
|
c := config.NewC(l)
|
||||||
|
c.Settings["lighthouse"] = map[string]any{"am_lighthouse": true}
|
||||||
|
c.Settings["listen"] = map[string]any{"port": 4242}
|
||||||
|
// Add a static_host_map entry for ourselves, so our address
|
||||||
|
// is in the addrMap.
|
||||||
|
c.Settings["static_host_map"] = map[string]any{
|
||||||
|
myVpnIp.String(): []any{"192.168.100.1:4242"},
|
||||||
|
}
|
||||||
|
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(myVpnNet), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
lh.ifce = &mockEncWriter{}
|
||||||
|
lhh := lh.NewRequestHandler()
|
||||||
|
|
||||||
|
peerVpnIp := netip.MustParseAddr("10.128.0.2")
|
||||||
|
peerUdpAddr := netip.MustParseAddrPort("10.0.0.2:4242")
|
||||||
|
otherVpnIp := netip.MustParseAddr("10.128.0.3")
|
||||||
|
otherUdpAddr := netip.MustParseAddrPort("10.0.0.3:4242")
|
||||||
|
|
||||||
|
newLHHostUpdate(peerUdpAddr, peerVpnIp, []netip.AddrPort{peerUdpAddr}, lhh)
|
||||||
|
newLHHostUpdate(otherUdpAddr, otherVpnIp, []netip.AddrPort{otherUdpAddr}, lhh)
|
||||||
|
|
||||||
|
// Control: a query about a real peer is still answered, and still ends with
|
||||||
|
// the punch notification aimed at the host that was asked about.
|
||||||
|
w := sendLHHostRequest(peerUdpAddr, peerVpnIp, otherVpnIp, lhh, nil)
|
||||||
|
require.NotNil(t, w.lastReply.msg)
|
||||||
|
assert.Equal(t, NebulaMeta_HostPunchNotification, w.lastReply.msg.Type)
|
||||||
|
assert.Equal(t, otherVpnIp, w.lastReply.vpnIp)
|
||||||
|
|
||||||
|
// Now validate that we don't send to ourselves.
|
||||||
|
found, _, err := lh.queryAndPrepMessage(myVpnIp, func(*cache) (int, error) { return 0, nil })
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.True(t, found, "the lighthouse should hold a cache entry for its own address")
|
||||||
|
|
||||||
|
w = sendLHHostRequest(peerUdpAddr, peerVpnIp, myVpnIp, lhh, nil)
|
||||||
|
assert.Nil(t, w.lastReply.msg, "a query about our own address must produce no reply and no punch notification")
|
||||||
}
|
}
|
||||||
|
|
||||||
func newLHHostUpdate(fromAddr netip.AddrPort, vpnIp netip.Addr, addrs []netip.AddrPort, lhh *LightHouseHandler) {
|
func newLHHostUpdate(fromAddr netip.AddrPort, vpnIp netip.Addr, addrs []netip.AddrPort, lhh *LightHouseHandler) {
|
||||||
@@ -498,7 +539,7 @@ type testEncWriter struct {
|
|||||||
protocolVersion cert.Version
|
protocolVersion cert.Version
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tw *testEncWriter) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool) {
|
func (tw *testEncWriter) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
|
||||||
}
|
}
|
||||||
func (tw *testEncWriter) Handshake(vpnIp netip.Addr) {
|
func (tw *testEncWriter) Handshake(vpnIp netip.Addr) {
|
||||||
}
|
}
|
||||||
@@ -642,12 +683,7 @@ func TestLighthouse_Dont_Delete_Static_Hosts(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
lh.ifce = &mockEncWriter{}
|
lh.ifce = &mockEncWriter{}
|
||||||
@@ -708,12 +744,7 @@ func TestLighthouse_DeletesWork(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
nt := new(bart.Lite)
|
cs := testCertState(myVpnNet)
|
||||||
nt.Insert(myVpnNet)
|
|
||||||
cs := &CertState{
|
|
||||||
myVpnNetworks: []netip.Prefix{myVpnNet},
|
|
||||||
myVpnNetworksTable: nt,
|
|
||||||
}
|
|
||||||
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
lh.ifce = &mockEncWriter{}
|
lh.ifce = &mockEncWriter{}
|
||||||
@@ -738,3 +769,276 @@ func TestLighthouse_DeletesWork(t *testing.T) {
|
|||||||
out = lh.Query(testHost)
|
out = lh.Query(testHost)
|
||||||
assert.Nil(t, out)
|
assert.Nil(t, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLightHouse_logLocalAddrsErr(t *testing.T) {
|
||||||
|
out := &bytes.Buffer{}
|
||||||
|
lh := &LightHouse{l: test.NewLoggerWithOutput(out)}
|
||||||
|
|
||||||
|
// The first sighting of a failure warns.
|
||||||
|
lh.logLocalAddrsErr(errors.New("permission denied"))
|
||||||
|
assert.Contains(t, out.String(), "level=WARN")
|
||||||
|
assert.Contains(t, out.String(), "permission denied")
|
||||||
|
|
||||||
|
// Repeating unchanged does not warn again, which is what keeps a permanent failure from warning
|
||||||
|
// on every lighthouse.interval for the life of the process.
|
||||||
|
out.Reset()
|
||||||
|
lh.logLocalAddrsErr(errors.New("permission denied"))
|
||||||
|
assert.NotContains(t, out.String(), "level=WARN")
|
||||||
|
|
||||||
|
// A different failure is a new event and warns.
|
||||||
|
out.Reset()
|
||||||
|
lh.logLocalAddrsErr(errors.New("something else"))
|
||||||
|
assert.Contains(t, out.String(), "level=WARN")
|
||||||
|
assert.Contains(t, out.String(), "something else")
|
||||||
|
|
||||||
|
// Recovering resets, so the same failure returning later warns again.
|
||||||
|
out.Reset()
|
||||||
|
lh.logLocalAddrsErr(nil)
|
||||||
|
assert.Empty(t, out.String())
|
||||||
|
lh.logLocalAddrsErr(errors.New("something else"))
|
||||||
|
assert.Contains(t, out.String(), "level=WARN")
|
||||||
|
}
|
||||||
|
|
||||||
|
// heldEncWriter holds the query worker in its first GetHostInfo until release closes.
|
||||||
|
type heldEncWriter struct {
|
||||||
|
mockEncWriter
|
||||||
|
once sync.Once
|
||||||
|
held chan struct{}
|
||||||
|
release chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *heldEncWriter) GetHostInfo(netip.Addr) *HostInfo {
|
||||||
|
w.once.Do(func() { close(w.held) })
|
||||||
|
<-w.release
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryServer never waits on the query worker, since the packet readers call it and nothing drains the channel at
|
||||||
|
// shutdown; a query that finds the channel full is dropped and counted. The worker is held on its first query so the
|
||||||
|
// channel fills.
|
||||||
|
func TestLighthouse_QueryServerDoesNotBlock(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
cs := testCertState(netip.MustParsePrefix("10.128.0.1/16"))
|
||||||
|
lh1 := "10.128.0.2"
|
||||||
|
c := config.NewC(l)
|
||||||
|
c.Settings["lighthouse"] = map[string]any{"hosts": []any{lh1}}
|
||||||
|
c.Settings["static_host_map"] = map[string]any{lh1: []any{"1.1.1.1:4242"}}
|
||||||
|
c.Settings["handshakes"] = map[string]any{"query_buffer": 1}
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
w := &heldEncWriter{held: make(chan struct{}), release: make(chan struct{})}
|
||||||
|
lh.ifce = w
|
||||||
|
t.Cleanup(func() { close(w.release) })
|
||||||
|
|
||||||
|
lh.QueryServer(netip.MustParseAddr("10.128.0.10"))
|
||||||
|
select {
|
||||||
|
case <-w.held:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("the query worker never took the first query")
|
||||||
|
}
|
||||||
|
dropped := lh.queryDropped.Count()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
lh.QueryServer(netip.MustParseAddr("10.128.0.11"))
|
||||||
|
lh.QueryServer(netip.MustParseAddr("10.128.0.12"))
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("QueryServer blocked on a full query channel")
|
||||||
|
}
|
||||||
|
assert.EqualValues(t, 1, lh.queryDropped.Count()-dropped)
|
||||||
|
}
|
||||||
|
|
||||||
|
// hostmapEncWriter answers GetHostInfo from a real hostmap, the way Interface does.
|
||||||
|
type hostmapEncWriter struct {
|
||||||
|
mockEncWriter
|
||||||
|
hm *HostMap
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *hostmapEncWriter) GetHostInfo(a netip.Addr) *HostInfo { return w.hm.QueryVpnAddr(a) }
|
||||||
|
func (w *hostmapEncWriter) GetCertState() *CertState {
|
||||||
|
return &CertState{initiatingVersion: cert.Version1}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A lighthouse runs four paths that each hold one lock while waiting for the next: CheckAndComplete
|
||||||
|
// holds the hostmap and takes the handshake manager, StartHandshake holds the handshake manager and
|
||||||
|
// takes the lighthouse, a host update holds the lighthouse and takes the sender's RemoteList, and a
|
||||||
|
// punch notification holds the querier's RemoteList while it resolves the target. If that last step
|
||||||
|
// reaches the hostmap under the RemoteList lock, the four deadlock. Drive them all at once.
|
||||||
|
func TestLighthouse_PunchNotificationDoesNotCloseLockCycle(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
myVpnNet := netip.MustParsePrefix("10.128.0.1/24")
|
||||||
|
|
||||||
|
c := config.NewC(l)
|
||||||
|
c.Settings["lighthouse"] = map[string]any{"am_lighthouse": true}
|
||||||
|
c.Settings["listen"] = map[string]any{"port": 4242}
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(myVpnNet), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
mainHM := newHostMap(l)
|
||||||
|
pr := []netip.Prefix{}
|
||||||
|
mainHM.preferredRanges.Store(&pr)
|
||||||
|
lh.ifce = &hostmapEncWriter{hm: mainHM}
|
||||||
|
|
||||||
|
hm := NewHandshakeManager(l, mainHM, lh, &udp.NoopConn{}, defaultHandshakeConfig)
|
||||||
|
f := &Interface{hostMap: mainHM, lightHouse: lh, handshakeManager: hm, l: l}
|
||||||
|
hm.f = f
|
||||||
|
|
||||||
|
peer := netip.MustParseAddr("10.128.0.2")
|
||||||
|
peerUdp := netip.MustParseAddrPort("10.0.0.2:4242")
|
||||||
|
target := netip.MustParseAddr("10.128.0.3")
|
||||||
|
targetUdp := netip.MustParseAddrPort("10.0.0.3:4242")
|
||||||
|
outbound := netip.MustParseAddr("10.128.0.4")
|
||||||
|
inbound := netip.MustParseAddr("10.128.0.5")
|
||||||
|
|
||||||
|
seed := lh.NewRequestHandler()
|
||||||
|
newLHHostUpdate(peerUdp, peer, []netip.AddrPort{peerUdp}, seed)
|
||||||
|
newLHHostUpdate(targetUdp, target, []netip.AddrPort{targetUdp}, seed)
|
||||||
|
|
||||||
|
stop := make(chan struct{})
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
loop := func(body func()) {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-stop:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
body()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wg.Add(4)
|
||||||
|
|
||||||
|
// Outbound handshakes keep starting and being dropped.
|
||||||
|
go loop(func() {
|
||||||
|
hm.DeleteHostInfo(hm.StartHandshake(outbound, nil))
|
||||||
|
})
|
||||||
|
|
||||||
|
// Inbound handshakes keep completing and being torn down.
|
||||||
|
var idx uint32
|
||||||
|
go loop(func() {
|
||||||
|
idx++
|
||||||
|
hi := &HostInfo{
|
||||||
|
vpnAddrs: []netip.Addr{inbound},
|
||||||
|
localIndexId: idx,
|
||||||
|
remoteIndexId: idx,
|
||||||
|
remotes: lh.QueryCache([]netip.Addr{inbound}),
|
||||||
|
HandshakePacket: map[uint8][]byte{handshakePacketStage0: {byte(idx)}},
|
||||||
|
}
|
||||||
|
if _, err := hm.CheckAndComplete(hi, handshakePacketStage0, f); err == nil {
|
||||||
|
mainHM.DeleteHostInfo(hi)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// The peer keeps sending host updates.
|
||||||
|
updates := lh.NewRequestHandler()
|
||||||
|
go loop(func() {
|
||||||
|
newLHHostUpdate(peerUdp, peer, []netip.AddrPort{peerUdp}, updates)
|
||||||
|
})
|
||||||
|
|
||||||
|
// The same peer keeps querying for the target, which ends in a punch notification.
|
||||||
|
queries := lh.NewRequestHandler()
|
||||||
|
go loop(func() {
|
||||||
|
sendLHHostRequest(peerUdp, peer, target, queries, nil)
|
||||||
|
})
|
||||||
|
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
close(stop)
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { wg.Wait(); close(done) }()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("deadlock: the lighthouse paths never finished after stop was signalled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLighthouse_reloadRelaysTriggersUpdate(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
c := config.NewC(l)
|
||||||
|
base := "lighthouse:\n am_lighthouse: true\nlisten:\n port: 4242\n"
|
||||||
|
require.NoError(t, c.LoadString(base+"relay:\n relays: [10.128.0.5]\n"))
|
||||||
|
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(netip.MustParsePrefix("10.128.0.1/24")), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, lh.updateTrigger)
|
||||||
|
|
||||||
|
require.NoError(t, c.ReloadConfigString(base+"relay:\n relays: [10.128.0.6]\n").Err)
|
||||||
|
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.128.0.6")}, lh.GetRelaysForMe())
|
||||||
|
require.Len(t, lh.updateTrigger, 1)
|
||||||
|
<-lh.updateTrigger
|
||||||
|
|
||||||
|
// The config changed but what we advertise did not, a bad entry is skipped
|
||||||
|
require.NoError(t, c.ReloadConfigString(base+"relay:\n relays: [10.128.0.6, nope]\n").Err)
|
||||||
|
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.128.0.6")}, lh.GetRelaysForMe())
|
||||||
|
assert.Empty(t, lh.updateTrigger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLighthouse_reloadAmRelayAlone(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
c := config.NewC(l)
|
||||||
|
base := "lighthouse:\n am_lighthouse: true\nlisten:\n port: 4242\nrelay:\n relays: [10.128.0.5]\n"
|
||||||
|
require.NoError(t, c.LoadString(base+" am_relay: false\n"))
|
||||||
|
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(netip.MustParsePrefix("10.128.0.1/24")), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.128.0.5")}, lh.GetRelaysForMe())
|
||||||
|
|
||||||
|
// Relays aren't allowed to have relays, flipping am_relay alone must drop them and tell the lighthouses
|
||||||
|
require.NoError(t, c.ReloadConfigString(base+" am_relay: true\n").Err)
|
||||||
|
assert.Empty(t, lh.GetRelaysForMe())
|
||||||
|
require.Len(t, lh.updateTrigger, 1)
|
||||||
|
<-lh.updateTrigger
|
||||||
|
|
||||||
|
require.NoError(t, c.ReloadConfigString(base+" am_relay: false\n").Err)
|
||||||
|
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.128.0.5")}, lh.GetRelaysForMe())
|
||||||
|
require.Len(t, lh.updateTrigger, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLighthouse_reloadRestartRequired(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
c := config.NewC(l)
|
||||||
|
base := "lighthouse:\n am_lighthouse: true\n"
|
||||||
|
require.NoError(t, c.LoadString(base+"listen:\n port: 4242\n"))
|
||||||
|
|
||||||
|
_, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(netip.MustParsePrefix("10.128.0.1/24")), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
res := c.ReloadConfigString(base + "listen:\n port: 4242\n")
|
||||||
|
require.NoError(t, res.Err)
|
||||||
|
assert.False(t, res.RestartRequired)
|
||||||
|
res = c.ReloadConfigString(base + "listen:\n port: 4243\n")
|
||||||
|
require.NoError(t, res.Err)
|
||||||
|
assert.True(t, res.RestartRequired)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A relay that doesn't parse is skipped and the rest are used, the reload says one was skipped
|
||||||
|
func TestLighthouse_reloadBadRelayFails(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
c := config.NewC(l)
|
||||||
|
require.NoError(t, c.LoadString("listen:\n port: 4242\n"))
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(netip.MustParsePrefix("10.128.0.1/24")), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
res := c.ReloadConfigString("listen:\n port: 4242\nrelay:\n relays: [10.128.0.2, nope]\n")
|
||||||
|
require.NoError(t, res.Err)
|
||||||
|
assert.True(t, res.Failed)
|
||||||
|
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.128.0.2")}, lh.GetRelaysForMe())
|
||||||
|
}
|
||||||
|
|
||||||
|
// An advertise_addrs entry inside our own network is skipped and the rest are used, the reload says one was skipped
|
||||||
|
func TestLighthouse_reloadAdvertiseAddrInNetworkFails(t *testing.T) {
|
||||||
|
l := test.NewLogger()
|
||||||
|
c := config.NewC(l)
|
||||||
|
require.NoError(t, c.LoadString("listen:\n port: 4242\n"))
|
||||||
|
lh, err := NewLightHouseFromConfig(t.Context(), l, c, testCertState(netip.MustParsePrefix("10.128.0.1/24")), nil, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
res := c.ReloadConfigString("listen:\n port: 4242\nlighthouse:\n advertise_addrs: [\"1.2.3.4:4242\", \"10.128.0.5:4242\"]\n")
|
||||||
|
require.NoError(t, res.Err)
|
||||||
|
assert.True(t, res.Failed)
|
||||||
|
assert.Equal(t, []netip.AddrPort{netip.MustParseAddrPort("1.2.3.4:4242")}, lh.GetAdvertiseAddrs())
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import "log/slog"
|
||||||
|
|
||||||
|
// RateLimiter is what RateLimited needs from a rate limiter, such as a *ratelimit.Limiter.
|
||||||
|
// Allow reports whether this call may proceed, and how many calls were denied since the last one that did.
|
||||||
|
type RateLimiter interface {
|
||||||
|
Allow() (denied uint64, ok bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimited checks lim before anything is built.
|
||||||
|
// When allowed it returns l, with a "suppressed" count attached if lim denied calls since its last allowed one.
|
||||||
|
// A nil lim allows everything.
|
||||||
|
//
|
||||||
|
// if l, ok := logging.RateLimited(f.l, f.udpTxErrLimiter); ok {
|
||||||
|
// hostinfo.logger(l).Error("Failed to write outgoing packet", "error", err)
|
||||||
|
// }
|
||||||
|
func RateLimited(l *slog.Logger, lim RateLimiter) (*slog.Logger, bool) {
|
||||||
|
if lim == nil {
|
||||||
|
return l, true
|
||||||
|
}
|
||||||
|
|
||||||
|
denied, ok := lim.Allow()
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if denied > 0 {
|
||||||
|
return l.With("suppressed", denied), true
|
||||||
|
}
|
||||||
|
return l, true
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/ratelimit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeLimiter struct {
|
||||||
|
denied uint64
|
||||||
|
ok bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fakeLimiter) Allow() (uint64, bool) { return f.denied, f.ok }
|
||||||
|
|
||||||
|
func TestRateLimited(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
base := NewLogger(&buf)
|
||||||
|
|
||||||
|
if l, ok := RateLimited(base, fakeLimiter{ok: false}); ok || l != nil {
|
||||||
|
t.Fatalf("denied call: ok=%v logger=%v", ok, l)
|
||||||
|
}
|
||||||
|
|
||||||
|
if l, ok := RateLimited(base, fakeLimiter{ok: true}); !ok || l != base {
|
||||||
|
t.Fatal("nothing denied should hand back the same logger")
|
||||||
|
}
|
||||||
|
|
||||||
|
if l, ok := RateLimited(base, nil); !ok || l != base {
|
||||||
|
t.Fatal("a nil limiter should allow with the same logger")
|
||||||
|
}
|
||||||
|
|
||||||
|
l, ok := RateLimited(base, fakeLimiter{denied: 7, ok: true})
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("allowed call denied")
|
||||||
|
}
|
||||||
|
l.Info("hello", "k", "v")
|
||||||
|
if !strings.Contains(buf.String(), "suppressed=7") {
|
||||||
|
t.Fatalf("want suppressed=7, got %q", buf.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The benchmarks compare a log line through slog directly against the same line behind RateLimited: logged with
|
||||||
|
// nothing denied, denied, and logged after denials.
|
||||||
|
|
||||||
|
var (
|
||||||
|
benchErr = errors.New("sendto: no buffer space available")
|
||||||
|
benchAddr = netip.MustParseAddrPort("192.0.2.1:4242")
|
||||||
|
)
|
||||||
|
|
||||||
|
func benchLogger() *slog.Logger {
|
||||||
|
return NewLogger(io.Discard).With("localIndex", 1234, "remoteIndex", 5678)
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkRateLimitedBaseline(b *testing.B) {
|
||||||
|
lg := benchLogger()
|
||||||
|
b.ReportAllocs()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
lg.Error("Failed to write outgoing packet", "error", benchErr, "udpAddr", benchAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkRateLimitedAllowed(b *testing.B) {
|
||||||
|
lg, lim := benchLogger(), mustLimiter(b, 1, 0)
|
||||||
|
b.ReportAllocs()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
if l, ok := RateLimited(lg, lim); ok {
|
||||||
|
l.Error("Failed to write outgoing packet", "error", benchErr, "udpAddr", benchAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkRateLimitedDenied(b *testing.B) {
|
||||||
|
lg, lim := benchLogger(), mustLimiter(b, 1, time.Hour)
|
||||||
|
lim.Allow()
|
||||||
|
b.ReportAllocs()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
if l, ok := RateLimited(lg, lim); ok {
|
||||||
|
l.Error("Failed to write outgoing packet", "error", benchErr, "udpAddr", benchAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkRateLimitedAfterDenied(b *testing.B) {
|
||||||
|
lg, lim := benchLogger(), fakeLimiter{denied: 5, ok: true}
|
||||||
|
b.ReportAllocs()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
if l, ok := RateLimited(lg, lim); ok {
|
||||||
|
l.Error("Failed to write outgoing packet", "error", benchErr, "udpAddr", benchAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustLimiter(b *testing.B, burst int, every time.Duration) *ratelimit.Limiter {
|
||||||
|
l, err := ratelimit.New(burst, every)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user