mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 07:56:52 +01:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3a252e64d | ||
|
|
13658b74a0 | ||
|
|
22cdb0739a | ||
|
|
45e449a591 | ||
|
|
a36ce25af4 | ||
|
|
2e5adfddc6 | ||
|
|
31f3d6435e | ||
|
|
8f9a631f6e |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# Goldens are compared byte for byte, so they must come out of git the way they went in.
|
||||
*.golden -text
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: Build
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: Build
|
||||
@@ -83,7 +83,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
# GitHub holds ARNs, not credentials, and ARNs outlive a rotation
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: add hashicorp source
|
||||
@@ -66,7 +66,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: add hashicorp source
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
# WSL2 + Ubuntu so the smoke can run a real linux peer with its own
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: Smoke Docker
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: build
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: Install goimports
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.14
|
||||
version: v2.12
|
||||
|
||||
test:
|
||||
name: Test ${{ matrix.name }}
|
||||
@@ -87,7 +87,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: Build
|
||||
@@ -132,7 +132,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.27'
|
||||
go-version: '1.26'
|
||||
check-latest: true
|
||||
|
||||
- name: Build ${{ matrix.name }}
|
||||
|
||||
@@ -7,26 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- A control socket that provides access to all of the ssh debug server's commands along with support
|
||||
for running `nebula ctl <command>` as a client from the CLI.
|
||||
- An info socket that provides access to information related to identity: identity, whoami, and print-cert.
|
||||
|
||||
### Removed
|
||||
|
||||
- The SSH debug server's `start-cpu-profile`, `stop-cpu-profile`, `save-heap-profile`, `save-mutex-profile`, and
|
||||
`mutex-profile-fraction` commands, and `sshd.sandbox_dir`, which is now ignored if set.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A peer whose certificate carries an unsafe network overlapping the overlay could send packets as any node in
|
||||
it: the firewall accepted any source inside the unsafe network. A source address inside this node's own
|
||||
networks must now be the sending peer's own; through an unsafe network it is dropped, counted as a dropped
|
||||
remote address.
|
||||
|
||||
- Signing a v2 certificate with an empty name, a name longer than 253 bytes, or an empty group now fails.
|
||||
These certificates were signed successfully but could not be loaded.
|
||||
- `create-tunnel -address <ip:port>` panicked on a nil RemoteList and, over the ssh debug server, took nebula
|
||||
down with it. A hostinfo returned by StartHandshake had no RemoteList until the handshake loop's first
|
||||
pass attached one, and `create-tunnel -address` set the remote before that. The list is now attached when
|
||||
|
||||
+1
-10
@@ -389,16 +389,7 @@ func (c *certificateV2) fromTBSCertificate(t *TBSCertificate) error {
|
||||
}
|
||||
|
||||
func (c *certificateV2) validate() error {
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
// Empty names are allowed
|
||||
|
||||
if len(c.publicKey) == 0 {
|
||||
return ErrInvalidPublicKey
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -136,47 +135,3 @@ func TestCertificate_SignP256_AlwaysNormalized(t *testing.T) {
|
||||
assert.True(t, normie)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateV2_SignRejectsUnparseable(t *testing.T) {
|
||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
var invalid *ErrInvalidCertificateProperties
|
||||
|
||||
newTBS := func() TBSCertificate {
|
||||
return TBSCertificate{
|
||||
Version: Version2,
|
||||
Name: "testing",
|
||||
Networks: []netip.Prefix{mustParsePrefixUnmapped("10.1.1.1/24")},
|
||||
Groups: []string{"test-group1"},
|
||||
NotBefore: time.Now().Add(-time.Minute),
|
||||
NotAfter: time.Now().Add(time.Minute),
|
||||
PublicKey: []byte("1234567890abcedfghij1234567890ab"),
|
||||
Curve: Curve_CURVE25519,
|
||||
IsCA: true,
|
||||
}
|
||||
}
|
||||
|
||||
tbs := newTBS()
|
||||
tbs.Name = strings.Repeat("a", MaxNameLength)
|
||||
c, err := tbs.Sign(nil, Curve_CURVE25519, priv)
|
||||
require.NoError(t, err)
|
||||
b, err := c.Marshal()
|
||||
require.NoError(t, err)
|
||||
_, err = unmarshalCertificateV2(b, nil, Curve_CURVE25519)
|
||||
require.NoError(t, err)
|
||||
|
||||
tbs = newTBS()
|
||||
tbs.Name = strings.Repeat("a", MaxNameLength+1)
|
||||
_, err = tbs.Sign(nil, Curve_CURVE25519, priv)
|
||||
require.ErrorAs(t, err, &invalid)
|
||||
|
||||
tbs = newTBS()
|
||||
tbs.Name = ""
|
||||
_, err = tbs.Sign(nil, Curve_CURVE25519, priv)
|
||||
require.ErrorAs(t, err, &invalid)
|
||||
|
||||
tbs = newTBS()
|
||||
tbs.Groups = []string{"test-group1", ""}
|
||||
_, err = tbs.Sign(nil, Curve_CURVE25519, priv)
|
||||
require.ErrorAs(t, err, &invalid)
|
||||
}
|
||||
@@ -1,420 +0,0 @@
|
||||
package ctl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
)
|
||||
|
||||
// Word is the argument that selects the control client instead of the daemon.
|
||||
const Word = "ctl"
|
||||
|
||||
// Subcommand handles the one bare word a daemon binary accepts before its flags. `nebula
|
||||
// ctl <command>` runs the client. Any other first argument that is not a flag is a
|
||||
// mistyped subcommand, reported with a usage line: the daemon's flag parser would ignore
|
||||
// the stray word and start nebula, so `nebula clt` would bring up a second daemon
|
||||
// instead of reporting a typo. It returns the exit code and true when the process is
|
||||
// done, and false when argv is the daemon's to parse. Both daemon binaries, cmd/nebula
|
||||
// and cmd/nebula-service, call it before anything else, so each has a nebula ctl and
|
||||
// neither has the hazard. A word that follows the daemon's flags instead is Trailing's.
|
||||
func Subcommand(argv []string) (code int, done bool) {
|
||||
if len(argv) < 2 || strings.HasPrefix(argv[1], "-") {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
if argv[1] == Word {
|
||||
return Run(argv[2:]), true
|
||||
}
|
||||
|
||||
return unknownCommand(argv[1]), true
|
||||
}
|
||||
|
||||
// Trailing handles the words the daemon's flag parser leaves unparsed: flag.Parse stops
|
||||
// at the first argument that is not a flag and hands the rest back. rest is flag.Args()
|
||||
// after the daemon has parsed, and configPath is the config the daemon's -config named,
|
||||
// "" when it did not. Both daemon binaries call it right after flag.Parse, so that
|
||||
// `nebula -config x ctl identity` runs the client and `nebula -config x clt` reports a
|
||||
// typo, as Subcommand does for a word at the front of the line; a daemon that ignored
|
||||
// the words would start in their place.
|
||||
//
|
||||
// A leading ctl word runs the client on what follows, with the daemon's -config carried
|
||||
// over: an operator who typed it meant the daemon running on that config, and the client
|
||||
// derives the same socket from it. Any other word is a mistake, reported as Subcommand
|
||||
// reports one.
|
||||
func Trailing(rest []string, configPath string) (code int, done bool) {
|
||||
if len(rest) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
if rest[0] != Word {
|
||||
return unknownCommand(rest[0]), true
|
||||
}
|
||||
|
||||
args := rest[1:]
|
||||
if configPath != "" {
|
||||
// First, so a -config on the ctl side of the line still wins: Parse applies
|
||||
// flags in order and the last value set is the one read.
|
||||
args = append([]string{"-" + commands.FlagConfig, configPath}, args...)
|
||||
}
|
||||
|
||||
return Run(args), true
|
||||
}
|
||||
|
||||
// unknownCommand reports a bare word that is neither a flag nor ctl, with the one usage
|
||||
// line that says what the two forms of the command line are.
|
||||
func unknownCommand(word string) int {
|
||||
fmt.Fprintf(os.Stderr, "nebula: unknown command %q\n\n", word)
|
||||
fmt.Fprintf(os.Stderr, "Run nebula with flags to start it, or `nebula %s <command>` to control one that is already running.\n", Word)
|
||||
return 1
|
||||
}
|
||||
|
||||
// Run implements `nebula ctl <command> [args]`
|
||||
//
|
||||
// args is everything after the `ctl` word.
|
||||
func Run(args []string) int {
|
||||
fs := flag.NewFlagSet("nebula ctl", flag.ContinueOnError)
|
||||
fs.SetOutput(os.Stderr)
|
||||
|
||||
configPath := fs.String(commands.FlagConfig, "", "Path to the config of the running nebula, used to locate its control socket")
|
||||
socketPath := fs.String(commands.FlagSocket, "", "Path to the control socket, instead of the one the config implies")
|
||||
fs.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: nebula ctl [flags] <command> [command flags]\n\n")
|
||||
fmt.Fprintf(os.Stderr, "Inspects and controls a nebula already running on this machine.\n")
|
||||
fmt.Fprintf(os.Stderr, "Run it as the user who ran nebula, or as a member of the group %s names.\n\n", localapi.CtlGroupKey)
|
||||
fmt.Fprintf(os.Stderr, "Flags, which may come before or after the command:\n")
|
||||
fs.PrintDefaults()
|
||||
fmt.Fprintf(os.Stderr, "\nRun `nebula ctl help` for the available commands.\n")
|
||||
}
|
||||
|
||||
own, cmdArgs := splitLine(fs, args)
|
||||
if err := fs.Parse(own); err != nil {
|
||||
// fs has already printed the usage, or the problem. Asking for help is not a
|
||||
// failure, and a script that chains on `nebula ctl -h` should not see one.
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
if len(cmdArgs) == 0 {
|
||||
cmdArgs = []string{"help"}
|
||||
}
|
||||
|
||||
path, err := resolveSocket(*socketPath, *configPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
client := &localapi.Client{Path: path}
|
||||
|
||||
// Ask the daemon what it serves before parsing anything. The flags belong to the
|
||||
// command, which lives over there, so this is what lets the CLI keep its usual shape
|
||||
// while the wire protocol stays a named-parameter API rather than a shipped argv.
|
||||
schema, err := client.Describe()
|
||||
if err != nil {
|
||||
// A daemon that answered was reached, and what it said, or that it could not be
|
||||
// read, is the whole message.
|
||||
var refused *localapi.DaemonError
|
||||
var unread *localapi.ReplyError
|
||||
if errors.As(err, &refused) || errors.As(err, &unread) {
|
||||
fmt.Fprintf(os.Stderr, "nebula: %s\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
// Otherwise the operating system said why, and it is passed on as it came: a
|
||||
// permission denied or a missing socket says more about what to do than a
|
||||
// guess at the operator's setup would.
|
||||
fmt.Fprintf(os.Stderr, "nebula: could not reach the control socket at %s: %s\n", path, err)
|
||||
return 1
|
||||
}
|
||||
|
||||
req, printedHelp, err := parseCommand(schema, cmdArgs)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
if printedHelp {
|
||||
return 0
|
||||
}
|
||||
|
||||
res, err := client.Invoke(string(req.name), req.Params, req.Args, wireFormat(req.Format))
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "nebula: %s\n", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
out := output(res, req.Format)
|
||||
if out != "" {
|
||||
fmt.Fprint(os.Stdout, out)
|
||||
if !strings.HasSuffix(out, "\n") {
|
||||
fmt.Fprintln(os.Stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// Error set is the one failure signal, whether the request never ran or the command
|
||||
// ran and refused. A refusal asked for in JSON has already gone to stdout as the
|
||||
// {ok, reason} object, and is not said again on stderr; the exit status carries it.
|
||||
if res.Error == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
if len(res.Result) == 0 && len(res.Text) == 0 {
|
||||
msg := res.Error
|
||||
if !strings.HasSuffix(msg, "\n") {
|
||||
msg += "\n"
|
||||
}
|
||||
fmt.Fprint(os.Stderr, msg)
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
// output renders what the daemon answered for the format the line asked for. A text
|
||||
// request is answered in Text with the bytes the command wrote, printed as they are; a
|
||||
// JSON request is answered in Result with the value itself, printed as it came, since a
|
||||
// value that happens to be a string is still JSON to the script reading it. Indentation
|
||||
// is the client's business: whitespace does not survive a JSON envelope, and the daemon
|
||||
// has no reason to care how its answer is laid out. The bytes are re-indented rather
|
||||
// than decoded and encoded again, which would sort the keys and round the numbers.
|
||||
func output(res *localapi.Response, format commands.Format) string {
|
||||
switch format {
|
||||
case commands.FormatJSON:
|
||||
return string(res.Result)
|
||||
case commands.FormatPrettyJSON:
|
||||
var buf bytes.Buffer
|
||||
if err := json.Indent(&buf, res.Result, "", " "); err != nil {
|
||||
return string(res.Result)
|
||||
}
|
||||
return buf.String()
|
||||
default:
|
||||
return string(res.Text)
|
||||
}
|
||||
}
|
||||
|
||||
// ctlRequest is one parsed nebula ctl command line: the command's name, which only the
|
||||
// daemon can resolve, and the line as every surface parses it. The Request's Command is
|
||||
// nil here, since the CLI holds a schema rather than the command, and its Format is
|
||||
// FormatUnset when the line named none, which to nebula ctl means text: its default
|
||||
// differs from the API's.
|
||||
type ctlRequest struct {
|
||||
name commands.Name
|
||||
commands.Request
|
||||
}
|
||||
|
||||
// wireFormat is what a request asks the daemon for. Pretty is the client's business,
|
||||
// since whitespace does not survive a JSON envelope, so it travels as json. No
|
||||
// preference is text, nebula ctl's default: a person gets the human rendering wherever
|
||||
// one exists.
|
||||
func wireFormat(f commands.Format) string {
|
||||
switch f {
|
||||
case commands.FormatJSON, commands.FormatPrettyJSON:
|
||||
return "json"
|
||||
default:
|
||||
return "text"
|
||||
}
|
||||
}
|
||||
|
||||
// parseCommand turns the user's command line into a ctlRequest, using the schema the
|
||||
// daemon supplied. The line is parsed with the same rules the daemon applies to an ssh
|
||||
// line, through ParseArgs, and ParseLine reads what was set into the Request to send, so
|
||||
// a line means the same on both.
|
||||
//
|
||||
// printedHelp reports that help was written for the command instead, and there is
|
||||
// nothing to send.
|
||||
func parseCommand(schema []commands.CommandSchema, argv []string) (req ctlRequest, printedHelp bool, err error) {
|
||||
name := commands.Name(argv[0])
|
||||
|
||||
var found *commands.CommandSchema
|
||||
for i := range schema {
|
||||
if schema[i].Name == name {
|
||||
found = &schema[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if found == nil {
|
||||
// Let the daemon answer. It knows whether this is a typo or a command it holds
|
||||
// back, and its message for the second case is better than anything guessable
|
||||
// from the schema alone.
|
||||
return ctlRequest{name: name, Request: commands.Request{Args: argv[1:]}}, false, nil
|
||||
}
|
||||
|
||||
// The flag package's own report is a bare message followed by a usage dump in a layout
|
||||
// that does not match WriteCommandHelp, so it is silenced and the error is reported
|
||||
// once, below, with a pointer at the help this command actually prints.
|
||||
fs := flag.NewFlagSet(string(name), flag.ContinueOnError)
|
||||
fs.SetOutput(io.Discard)
|
||||
|
||||
for _, f := range found.Flags {
|
||||
if f.Bool {
|
||||
fs.Bool(f.Name, f.Default == "true", f.Usage)
|
||||
continue
|
||||
}
|
||||
fs.String(f.Name, f.Default, f.Usage)
|
||||
}
|
||||
|
||||
operands, err := commands.ParseArgs(fs, argv[1:])
|
||||
if err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
// The same rendering the daemon uses for `help <command>`, so -h and help agree.
|
||||
_ = commands.WriteCommandHelp(*found, os.Stdout)
|
||||
return ctlRequest{}, true, nil
|
||||
}
|
||||
|
||||
// Say what flag did: an unknown flag, a missing value and a malformed value are
|
||||
// different mistakes, and "does not take" would be wrong for two of them.
|
||||
return ctlRequest{}, false, fmt.Errorf("nebula: %s: %s (see 'nebula ctl %s -h')", name, err, name)
|
||||
}
|
||||
|
||||
// Only what the user actually set travels. A parameter left alone is the daemon's
|
||||
// default to apply, not the client's to assert, and the presentation flags are the
|
||||
// client's to interpret, never sent.
|
||||
//
|
||||
// Where the command has no human form the daemon says so, and only once the command
|
||||
// has run: a refusal ("No vpn address was provided") always has a human form, so
|
||||
// telling the user to pass -json before finding out whether the command would even
|
||||
// accept the line sends them to fix the wrong thing. That is why the schema does not
|
||||
// say which commands have a human form: nothing should decide on it before running.
|
||||
return ctlRequest{name: name, Request: commands.ParseLine(fs, operands)}, false, nil
|
||||
}
|
||||
|
||||
// splitLine divides a nebula ctl line into the client's own flags, for fs to parse, and
|
||||
// the command line to send, which begins with the command word. The client's flags may
|
||||
// come before the command or after it: `nebula ctl -config x identity` and
|
||||
// `nebula ctl identity -config x` mean the same, so an operator who has typed a command
|
||||
// and then remembers which daemon they meant does not have to retype the line.
|
||||
//
|
||||
// Before the command word every flag is the client's, whatever it is, so an unknown one
|
||||
// is reported by fs, and -h is the client's usage. After it only the
|
||||
// flags fs defines are lifted out, and only those: the command's own flags are unknown
|
||||
// here, since they come from the daemon the line has yet to name, and -h after the
|
||||
// command asks for that command's help. Which command flags take a value is unknown too,
|
||||
// so the client's names are reserved in the commands package and no command can give
|
||||
// one a value that would be lifted from here. A "--" before the command is consumed, as
|
||||
// fs.Parse would have; one after it belongs to the command line and ends the lifting,
|
||||
// so an operand spelled like a client flag can still be passed.
|
||||
func splitLine(fs *flag.FlagSet, args []string) (own, cmd []string) {
|
||||
seenCommand := false
|
||||
for i := 0; i < len(args); i++ {
|
||||
a := args[i]
|
||||
|
||||
if a == "--" {
|
||||
if seenCommand {
|
||||
return own, append(cmd, args[i:]...)
|
||||
}
|
||||
seenCommand = true
|
||||
continue
|
||||
}
|
||||
|
||||
if !seenCommand {
|
||||
if len(a) < 2 || a[0] != '-' {
|
||||
seenCommand = true
|
||||
cmd = append(cmd, a)
|
||||
continue
|
||||
}
|
||||
|
||||
own = append(own, a)
|
||||
if f, hasValue := commands.LookupArg(fs, a); f != nil && !hasValue && !commands.IsBoolFlag(f) && i+1 < len(args) {
|
||||
i++
|
||||
own = append(own, args[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if len(a) >= 2 && a[0] == '-' {
|
||||
// The same reading of the argument ParseArgs makes, so a word this lifts as a
|
||||
// client flag's value is one the daemon's parser would have read the same way.
|
||||
if f, hasValue := commands.LookupArg(fs, a); f != nil {
|
||||
own = append(own, a)
|
||||
if !hasValue && !commands.IsBoolFlag(f) && i+1 < len(args) {
|
||||
i++
|
||||
own = append(own, args[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
cmd = append(cmd, a)
|
||||
}
|
||||
|
||||
return own, cmd
|
||||
}
|
||||
|
||||
// resolveSocket decides which socket to talk to. It never searches: the answer is the
|
||||
// socket the operator named, or the one the config implies, and nothing else.
|
||||
//
|
||||
// An explicit flag wins. Otherwise the config is read, the one the operator named or the
|
||||
// one found next to the executable, and the path is the socket that config implies: its
|
||||
// local_api.control.socket if set, else the same derivation the daemon applies.
|
||||
func resolveSocket(socketFlag, configFlag string) (string, error) {
|
||||
if socketFlag != "" {
|
||||
return socketFlag, nil
|
||||
}
|
||||
|
||||
return pathFromConfig(configFlag)
|
||||
}
|
||||
|
||||
// pathFromConfig returns the socket path the daemon would be serving: the one
|
||||
// local_api.control.socket names in the config, so an operator who moved the socket does
|
||||
// not have to repeat themselves on every invocation, else the default.
|
||||
//
|
||||
// A config the operator did not name is a guess: config.DefaultPath looks next to the
|
||||
// executable, and a package that installs a default config there while systemd starts
|
||||
// the daemon with another will make it the wrong guess. It is still the only answer
|
||||
// that involves no searching. A guess that cannot be read is not an error, it is no
|
||||
// guess: a member of the socket's group cannot read a root daemon's config, and is
|
||||
// answered by the default path, where the daemon serves unless that config moved it.
|
||||
// A config the operator named is theirs to make readable.
|
||||
func pathFromConfig(configFlag string) (string, error) {
|
||||
return socketFromConfigFile(configFlag, configFlag != "")
|
||||
}
|
||||
|
||||
func socketFromConfigFile(configPath string, named bool) (string, error) {
|
||||
if !named {
|
||||
p, err := config.DefaultPath()
|
||||
if err != nil {
|
||||
return localapi.DefaultSocketPath, nil
|
||||
}
|
||||
configPath = p
|
||||
}
|
||||
|
||||
// The config is loaded only to find the socket path. Loading logs lines that belong
|
||||
// to the daemon, not to someone running a read only command, and mixing them into
|
||||
// the CLI's output would corrupt a -json result, so they are discarded.
|
||||
c := config.NewC(slog.New(slog.DiscardHandler))
|
||||
if err := c.Load(configPath); err != nil {
|
||||
if !named {
|
||||
return localapi.DefaultSocketPath, nil
|
||||
}
|
||||
// The operating system's error, as it came: permission denied on a root daemon's
|
||||
// config says what to do.
|
||||
return "", fmt.Errorf("nebula: could not read %s: %w", configPath, err)
|
||||
}
|
||||
|
||||
// A daemon running this config serves no socket; dialing the path would only say
|
||||
// that nothing is there.
|
||||
if !localapi.ControlEnabled(c) {
|
||||
return "", fmt.Errorf("nebula: the control socket is disabled in %s by %s", configPath, localapi.CtlEnabledKey)
|
||||
}
|
||||
|
||||
// The same call the daemon makes, so the two agree on the path and on what makes a
|
||||
// path unusable.
|
||||
p, err := localapi.SocketPathFromConfig(c)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("nebula: %w", err)
|
||||
}
|
||||
|
||||
return p, nil
|
||||
}
|
||||
@@ -1,294 +0,0 @@
|
||||
package ctl
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestResolveSocketReportsAnUnreadableConfig: an operator who named a config must hear
|
||||
// that it could not be read, rather than have the command steered anywhere else.
|
||||
func TestResolveSocketReportsAnUnreadableConfig(t *testing.T) {
|
||||
missing := filepath.Join(t.TempDir(), "typo.yml")
|
||||
|
||||
_, err := resolveSocket("", missing)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), missing)
|
||||
}
|
||||
|
||||
// TestResolveSocketGuessedConfigNeedNotBeReadable: a config nobody named is a guess, and
|
||||
// one that cannot be read, a root daemon's config read by a member of the socket's
|
||||
// group, means the default path rather than an error.
|
||||
func TestResolveSocketGuessedConfigNeedNotBeReadable(t *testing.T) {
|
||||
missing := filepath.Join(t.TempDir(), "config.yml")
|
||||
|
||||
p, err := socketFromConfigFile(missing, false)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, localapi.DefaultSocketPath, p)
|
||||
|
||||
_, err = socketFromConfigFile(missing, true)
|
||||
require.ErrorContains(t, err, missing)
|
||||
}
|
||||
|
||||
// nowhereSocket is a socket name nothing listens on, spelled the way the platform
|
||||
// requires: a full pipe name on windows, an absolute path elsewhere.
|
||||
var nowhereSocket = map[bool]string{true: `\\.\pipe\nebula-nowhere`, false: "/nowhere/ctl.sock"}[runtime.GOOS == "windows"]
|
||||
|
||||
// namedSocketConfig is a config that names nowhereSocket as the control socket. Single
|
||||
// quotes keep a pipe name's backslashes literal in YAML.
|
||||
var namedSocketConfig = "local_api:\n control:\n socket: '" + nowhereSocket + "'\n"
|
||||
|
||||
// TestResolveSocketTrustsANamedConfig: a config the operator named yields the socket it
|
||||
// implies even when nothing is listening there, so a dial failure names that socket.
|
||||
func TestResolveSocketTrustsANamedConfig(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
||||
require.NoError(t, os.WriteFile(cfg, []byte(namedSocketConfig), 0600))
|
||||
|
||||
p, err := resolveSocket("", cfg)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, nowhereSocket, p)
|
||||
}
|
||||
|
||||
// TestResolveSocketSaysTheSocketIsDisabled: a config that turns the control socket off
|
||||
// is answered with that, not with a dial to a path nothing serves. -socket still wins.
|
||||
func TestResolveSocketSaysTheSocketIsDisabled(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
||||
require.NoError(t, os.WriteFile(cfg, []byte("local_api:\n control:\n enabled: false\n"), 0600))
|
||||
|
||||
_, err := resolveSocket("", cfg)
|
||||
require.ErrorContains(t, err, "the control socket is disabled in "+cfg+" by local_api.control.enabled")
|
||||
|
||||
p, err := resolveSocket("/explicit.sock", cfg)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/explicit.sock", p)
|
||||
}
|
||||
|
||||
// TestResolveSocketUsesTheDefaultWithoutAnOverride: a config that does not name the
|
||||
// socket means the default path, the same one the daemon serves with that config, and
|
||||
// no config at all means the default too, since that is where a daemon started without
|
||||
// an override serves. Nothing is searched for.
|
||||
func TestResolveSocketUsesTheDefaultWithoutAnOverride(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
||||
require.NoError(t, os.WriteFile(cfg, []byte("static_host_map: {}\n"), 0600))
|
||||
|
||||
p, err := resolveSocket("", cfg)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, localapi.DefaultSocketPath, p)
|
||||
|
||||
// The test binary has no config next to it.
|
||||
p, err = resolveSocket("", "")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, localapi.DefaultSocketPath, p)
|
||||
}
|
||||
|
||||
func TestResolveSocketFlagWins(t *testing.T) {
|
||||
p, err := resolveSocket("/explicit.sock", "/does/not/matter.yml")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/explicit.sock", p)
|
||||
}
|
||||
|
||||
// TestParseCommandReportsWhatFlagSaid covers the three ways a flag line goes wrong, which
|
||||
// are different mistakes: an unknown flag, a valid flag with a missing value, and a
|
||||
// valid flag with a value it cannot parse.
|
||||
func TestParseCommandReportsWhatFlagSaid(t *testing.T) {
|
||||
schema := []commands.CommandSchema{{
|
||||
Name: "change-remote",
|
||||
Flags: []commands.FlagSchema{
|
||||
{Name: "address"},
|
||||
{Name: "by-index", Bool: true},
|
||||
},
|
||||
}}
|
||||
|
||||
cases := map[string]struct {
|
||||
argv []string
|
||||
want string
|
||||
}{
|
||||
"missing value": {[]string{"change-remote", "-address"}, "flag needs an argument: -address"},
|
||||
"bad bool": {[]string{"change-remote", "-by-index=maybe"}, "invalid boolean value \"maybe\" for -by-index"},
|
||||
"unknown flag": {[]string{"change-remote", "-nope"}, "flag provided but not defined: -nope"},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, _, err := parseCommand(schema, tc.argv)
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "nebula: change-remote: "+tc.want)
|
||||
require.ErrorContains(t, err, "see 'nebula ctl change-remote -h'")
|
||||
assert.NotContains(t, err.Error(), "does not take")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseCommandOffPresentationFlagIsNoPreference: the daemon treats -json=false as
|
||||
// no preference, so nebula ctl must too, or the same line renders differently on the
|
||||
// two surfaces. Only a true value asks for JSON, and -pretty implies it.
|
||||
func TestParseCommandOffPresentationFlagIsNoPreference(t *testing.T) {
|
||||
schema := []commands.CommandSchema{{
|
||||
Name: "device-info",
|
||||
Flags: []commands.FlagSchema{
|
||||
{Name: commands.FlagJSON, Bool: true, Default: "false"},
|
||||
{Name: commands.FlagPretty, Bool: true, Default: "false"},
|
||||
},
|
||||
}}
|
||||
|
||||
for _, tc := range []struct {
|
||||
argv []string
|
||||
want commands.Format
|
||||
wire string
|
||||
}{
|
||||
{[]string{"device-info"}, commands.FormatUnset, "text"},
|
||||
{[]string{"device-info", "-json=false"}, commands.FormatUnset, "text"},
|
||||
{[]string{"device-info", "-json"}, commands.FormatJSON, "json"},
|
||||
{[]string{"device-info", "-pretty"}, commands.FormatPrettyJSON, "json"},
|
||||
} {
|
||||
t.Run(strings.Join(tc.argv[1:], " "), func(t *testing.T) {
|
||||
req, printedHelp, err := parseCommand(schema, tc.argv)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, printedHelp)
|
||||
assert.Equal(t, tc.want, req.Format)
|
||||
assert.Equal(t, tc.wire, wireFormat(req.Format))
|
||||
assert.Nil(t, req.Params, "presentation flags are never sent as parameters")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseCommandReadsTheLineAsTheDaemonDoes: nebula ctl parses the line with the same
|
||||
// rules as the daemon, so an operand after "--" reaches the command on both and a
|
||||
// negative number before it is the flag it would be at an ssh prompt.
|
||||
func TestParseCommandReadsTheLineAsTheDaemonDoes(t *testing.T) {
|
||||
schema := []commands.CommandSchema{{Name: "set"}}
|
||||
|
||||
req, printedHelp, err := parseCommand(schema, []string{"set", "--", "-1"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, printedHelp)
|
||||
assert.Equal(t, commands.Name("set"), req.name)
|
||||
assert.Nil(t, req.Params)
|
||||
assert.Equal(t, []string{"-1"}, req.Args)
|
||||
|
||||
_, _, err = parseCommand(schema, []string{"set", "-1"})
|
||||
require.ErrorContains(t, err, "flag provided but not defined: -1")
|
||||
}
|
||||
|
||||
// TestOutputRendersForTheFormatAsked: what the daemon answered is read by the format the
|
||||
// line asked for, never by sniffing the bytes. A text answer is the command's rendering,
|
||||
// printed as it came; a JSON answer whose value is a string stays quoted, since to the
|
||||
// script reading it that string is the JSON.
|
||||
func TestOutputRendersForTheFormatAsked(t *testing.T) {
|
||||
text := &localapi.Response{Text: []byte("Log level is: info\n")}
|
||||
assert.Equal(t, "Log level is: info\n", output(text, commands.FormatUnset))
|
||||
assert.Equal(t, "Log level is: info\n", output(text, commands.FormatText))
|
||||
|
||||
str := &localapi.Response{Result: json.RawMessage(`"some string"`)}
|
||||
assert.Equal(t, `"some string"`, output(str, commands.FormatJSON))
|
||||
assert.Equal(t, `"some string"`, output(str, commands.FormatPrettyJSON))
|
||||
|
||||
// Keys stay in the order the daemon wrote them and a uint64 past 2^53 is not rounded,
|
||||
// which decoding into `any` and encoding again would do.
|
||||
obj := &localapi.Response{Result: json.RawMessage(`{"z":18446744073709551615,"a":{"y":[1,2],"b":true}}`)}
|
||||
//nolint:testifylint // the layout is what is under test, which JSONEq would not see
|
||||
assert.Equal(t, `{"z":18446744073709551615,"a":{"y":[1,2],"b":true}}`, output(obj, commands.FormatJSON))
|
||||
//nolint:testifylint // as above
|
||||
assert.Equal(t, "{\n \"z\": 18446744073709551615,\n \"a\": {\n \"y\": [\n 1,\n 2\n ],\n \"b\": true\n }\n}", output(obj, commands.FormatPrettyJSON))
|
||||
|
||||
bad := &localapi.Response{Result: json.RawMessage(`{"a":`)}
|
||||
assert.Equal(t, `{"a":`, output(bad, commands.FormatPrettyJSON), "what cannot be indented is printed as it came")
|
||||
|
||||
none := &localapi.Response{}
|
||||
assert.Empty(t, output(none, commands.FormatJSON))
|
||||
assert.Empty(t, output(none, commands.FormatUnset))
|
||||
}
|
||||
|
||||
// TestSplitLineLiftsOwnFlagsFromAnywhere: -config and -socket are the client's wherever
|
||||
// they appear, before the command or after it, in either spelling, so the two orders
|
||||
// mean the same line. Everything else after the command word stays in order for the
|
||||
// command's own parse, including flags and operands that happen to look like values.
|
||||
func TestSplitLineLiftsOwnFlagsFromAnywhere(t *testing.T) {
|
||||
newFS := func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("nebula ctl", flag.ContinueOnError)
|
||||
fs.String(commands.FlagConfig, "", "")
|
||||
fs.String(commands.FlagSocket, "", "")
|
||||
return fs
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
wantOwn []string
|
||||
wantCmd []string
|
||||
}{
|
||||
{nil, nil, nil},
|
||||
{[]string{"identity"}, nil, []string{"identity"}},
|
||||
{[]string{"-config", "x", "identity"}, []string{"-config", "x"}, []string{"identity"}},
|
||||
{[]string{"identity", "-config", "x"}, []string{"-config", "x"}, []string{"identity"}},
|
||||
{[]string{"identity", "-config=x"}, []string{"-config=x"}, []string{"identity"}},
|
||||
{[]string{"identity", "--socket", "s"}, []string{"--socket", "s"}, []string{"identity"}},
|
||||
{[]string{"-socket", "s", "identity", "-config", "x"}, []string{"-socket", "s", "-config", "x"}, []string{"identity"}},
|
||||
// The command's flags and operands are left where they are, around the lifted ones.
|
||||
{[]string{"print-tunnel", "10.0.0.1", "-config", "x", "-json"}, []string{"-config", "x"}, []string{"print-tunnel", "10.0.0.1", "-json"}},
|
||||
{[]string{"change-remote", "-address", "1.2.3.4:5", "-socket", "s", "10.0.0.1"}, []string{"-socket", "s"}, []string{"change-remote", "-address", "1.2.3.4:5", "10.0.0.1"}},
|
||||
// -h before the command is the client's usage; after it, the command's help.
|
||||
{[]string{"-h"}, []string{"-h"}, nil},
|
||||
{[]string{"identity", "-h"}, nil, []string{"identity", "-h"}},
|
||||
// An unknown flag before the command is the client's to report, and does not
|
||||
// swallow the command word as its value.
|
||||
{[]string{"-nope", "identity"}, []string{"-nope"}, []string{"identity"}},
|
||||
// A -config with nothing after it is left for fs.Parse to report.
|
||||
{[]string{"identity", "-config"}, []string{"-config"}, []string{"identity"}},
|
||||
// "--" before the command is consumed, as fs.Parse consumed it; after the command
|
||||
// it belongs to the line and ends the lifting.
|
||||
{[]string{"--", "identity", "-config", "x"}, []string{"-config", "x"}, []string{"identity"}},
|
||||
{[]string{"identity", "--", "-config", "x"}, nil, []string{"identity", "--", "-config", "x"}},
|
||||
} {
|
||||
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
|
||||
own, cmd := splitLine(newFS(), tc.args)
|
||||
assert.Equal(t, tc.wantOwn, own)
|
||||
assert.Equal(t, tc.wantCmd, cmd)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrailingHandlesWordsAfterTheDaemonsFlags: what flag.Parse leaves behind is never
|
||||
// a daemon to start. A leading ctl runs the client on the rest, with the daemon's
|
||||
// -config carried over; anything else is a mistyped subcommand. Only -h is run here,
|
||||
// since the client's help needs no daemon: it proves the words reach Run and that a
|
||||
// carried -config is accepted by it.
|
||||
func TestTrailingHandlesWordsAfterTheDaemonsFlags(t *testing.T) {
|
||||
code, done := Trailing(nil, "")
|
||||
assert.False(t, done)
|
||||
assert.Equal(t, 0, code)
|
||||
|
||||
code, done = Trailing([]string{"clt"}, "")
|
||||
assert.True(t, done)
|
||||
assert.Equal(t, 1, code)
|
||||
|
||||
code, done = Trailing([]string{Word, "-h"}, "")
|
||||
assert.True(t, done)
|
||||
assert.Equal(t, 0, code)
|
||||
|
||||
code, done = Trailing([]string{Word, "-h"}, "/etc/nebula/config.yml")
|
||||
assert.True(t, done)
|
||||
assert.Equal(t, 0, code)
|
||||
}
|
||||
|
||||
// TestSubcommandOnlyReadsTheFirstWord: a flag first means the line is the daemon's to
|
||||
// parse, and whatever follows the flags is Trailing's to judge.
|
||||
func TestSubcommandOnlyReadsTheFirstWord(t *testing.T) {
|
||||
_, done := Subcommand([]string{"nebula", "-config", "x", Word})
|
||||
assert.False(t, done)
|
||||
|
||||
code, done := Subcommand([]string{"nebula", "clt"})
|
||||
assert.True(t, done)
|
||||
assert.Equal(t, 1, code)
|
||||
|
||||
code, done = Subcommand([]string{"nebula", Word, "-h"})
|
||||
assert.True(t, done)
|
||||
assert.Equal(t, 0, code)
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package ctl
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestResolveSocketDiagnosesAnOverlongOverride: the CLI applies the daemon's own rule to
|
||||
// the override, so it says what the daemon's log says rather than dialing a path the
|
||||
// kernel would truncate and reporting the generic failure. The rule is sun_path's, which
|
||||
// a named pipe does not have, so this is a unix test.
|
||||
func TestResolveSocketDiagnosesAnOverlongOverride(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
||||
long := "/" + strings.Repeat("x", 120)
|
||||
require.NoError(t, os.WriteFile(cfg, []byte("local_api:\n control:\n socket: "+long+"\n"), 0600))
|
||||
|
||||
_, err := resolveSocket("", cfg)
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "too long for this platform")
|
||||
assert.ErrorContains(t, err, localapi.CtlSocketKey)
|
||||
}
|
||||
|
||||
// TestResolveSocketRefusesARelativeOverride: the CLI applies the daemon's rule here too,
|
||||
// so a relative path in the config is reported as the daemon's log reports it rather
|
||||
// than resolved against wherever nebula ctl happened to be run from.
|
||||
func TestResolveSocketRefusesARelativeOverride(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "config.yml")
|
||||
require.NoError(t, os.WriteFile(cfg, []byte("local_api:\n control:\n socket: run/ctl.sock\n"), 0600))
|
||||
|
||||
_, err := resolveSocket("", cfg)
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "must be an absolute path")
|
||||
assert.ErrorContains(t, err, localapi.CtlSocketKey)
|
||||
}
|
||||
@@ -8,9 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/cmd/internal/ctl"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
"github.com/slackhq/nebula/util"
|
||||
)
|
||||
@@ -34,11 +32,6 @@ func init() {
|
||||
}
|
||||
|
||||
func main() {
|
||||
// commands are either `nebula ctl ...` or `nebula -<flag> ...`
|
||||
if code, done := ctl.Subcommand(os.Args); done {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
serviceFlag := flag.String("service", "", "Control the system service.")
|
||||
configPath := flag.String("config", "", "Path to either a file or directory to load configuration from")
|
||||
configTest := flag.Bool("test", false, "Test the config and print the end result. Non zero exit indicates a faulty config")
|
||||
@@ -47,12 +40,6 @@ func main() {
|
||||
|
||||
flag.Parse()
|
||||
|
||||
// A word after the daemon's flags is `ctl` in the other place an operator puts it,
|
||||
// or a mistyped subcommand, and either way not a daemon to start; see Trailing.
|
||||
if code, done := ctl.Trailing(flag.Args(), *configPath); done {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
if *printVersion {
|
||||
fmt.Printf("Version: %s\n", Build)
|
||||
os.Exit(0)
|
||||
@@ -98,10 +85,9 @@ func main() {
|
||||
fmt.Printf("failed to apply logging config: %s", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
if err := logging.ApplyConfig(l, c); err != nil {
|
||||
l.Error("Failed to reconfigure logger on reload", "error", err)
|
||||
r.Failed()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -117,17 +103,9 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
local := localapi.Wire(ctrl.Context(), l, c, ctrl.Commands())
|
||||
|
||||
go ctrl.ShutdownBlock()
|
||||
|
||||
err := ctrl.Wait()
|
||||
|
||||
// os.Exit skips deferred calls, so the sockets are removed here, before either
|
||||
// exit below, rather than left to a deferred Stop that would never run.
|
||||
local.Stop()
|
||||
|
||||
if err != nil {
|
||||
if err := ctrl.Wait(); err != nil {
|
||||
l.Error("Nebula stopped due to fatal error", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"github.com/kardianos/service"
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
)
|
||||
|
||||
@@ -18,7 +17,6 @@ type program struct {
|
||||
configPath *string
|
||||
build string
|
||||
control *nebula.Control
|
||||
local *localapi.Endpoints
|
||||
}
|
||||
|
||||
func (p *program) Start(s service.Service) error {
|
||||
@@ -36,10 +34,9 @@ func (p *program) Start(s service.Service) error {
|
||||
if err := logging.ApplyConfig(l, c); err != nil {
|
||||
return fmt.Errorf("failed to apply logging config: %s", err)
|
||||
}
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
if err := logging.ApplyConfig(l, c); err != nil {
|
||||
l.Error("Failed to reconfigure logger on reload", "error", err)
|
||||
r.Failed()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -52,16 +49,10 @@ func (p *program) Start(s service.Service) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Now that we're started, stand up the local APIs.
|
||||
p.local = localapi.Wire(p.control.Context(), l, c, p.control.Commands())
|
||||
|
||||
// Nebula can stop itself on a fatal packet reader error, make sure to log it if it happens.
|
||||
go func() {
|
||||
if err := p.control.Wait(); err != nil {
|
||||
logger.Error(fmt.Sprintf("Nebula stopped due to fatal error: %v", err))
|
||||
// os.Exit skips deferred calls and races the sockets' own context watchers,
|
||||
// so they are removed here, as cmd/nebula does.
|
||||
p.local.Stop()
|
||||
os.Exit(2)
|
||||
}
|
||||
}()
|
||||
@@ -71,11 +62,6 @@ func (p *program) Start(s service.Service) error {
|
||||
|
||||
func (p *program) Stop(s service.Service) error {
|
||||
logger.Info("Nebula service stopping.")
|
||||
|
||||
if p.local != nil {
|
||||
p.local.Stop()
|
||||
}
|
||||
|
||||
if p.control == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
+2
-24
@@ -8,9 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/cmd/internal/ctl"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
"github.com/slackhq/nebula/util"
|
||||
)
|
||||
@@ -34,11 +32,6 @@ func init() {
|
||||
}
|
||||
|
||||
func main() {
|
||||
// commands are either `nebula ctl ...` or `nebula -<flag> ...`
|
||||
if code, done := ctl.Subcommand(os.Args); done {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
configPath := flag.String("config", "", "Path to either a file or directory to load configuration from")
|
||||
configTest := flag.Bool("test", false, "Test the config and print the end result. Non zero exit indicates a faulty config")
|
||||
printVersion := flag.Bool("version", false, "Print version")
|
||||
@@ -46,12 +39,6 @@ func main() {
|
||||
|
||||
flag.Parse()
|
||||
|
||||
// A word after the daemon's flags is `ctl` in the other place an operator puts it,
|
||||
// or a mistyped subcommand, and either way not a daemon to start; see Trailing.
|
||||
if code, done := ctl.Trailing(flag.Args(), *configPath); done {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
if *printVersion {
|
||||
fmt.Printf("Version: %s\n", Build)
|
||||
os.Exit(0)
|
||||
@@ -84,10 +71,9 @@ func main() {
|
||||
fmt.Printf("failed to apply logging config: %s", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
if err := logging.ApplyConfig(l, c); err != nil {
|
||||
l.Error("Failed to reconfigure logger on reload", "error", err)
|
||||
r.Failed()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -103,18 +89,10 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
local := localapi.Wire(ctrl.Context(), l, c, ctrl.Commands())
|
||||
|
||||
go ctrl.ShutdownBlock()
|
||||
notifyReady(l)
|
||||
|
||||
err := ctrl.Wait()
|
||||
|
||||
// os.Exit skips deferred calls, so the sockets are removed here, before either
|
||||
// exit below, rather than left to a deferred Stop that would never run.
|
||||
local.Stop()
|
||||
|
||||
if err != nil {
|
||||
if err := ctrl.Wait(); err != nil {
|
||||
l.Error("Nebula stopped due to fatal error", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
-683
@@ -1,683 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
)
|
||||
|
||||
// The commands nebula serves. attachCommands builds the one registry every surface
|
||||
// reads; the ssh debug server is a consumer of it, not its owner, which is why this
|
||||
// is not ssh.go. See the commands package for what a Command is.
|
||||
|
||||
type listHostMapFlags struct {
|
||||
ByIndex bool
|
||||
}
|
||||
|
||||
type printCertFlags struct {
|
||||
Raw bool
|
||||
|
||||
// Address is the -address form of the vpn addr, which the info API needs since a
|
||||
// query string has no operands; see identityFlags for why presence is recorded.
|
||||
Address string
|
||||
addressSet bool
|
||||
}
|
||||
|
||||
func (f *printCertFlags) setAddress(v string) error {
|
||||
f.Address = v
|
||||
f.addressSet = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type changeRemoteFlags struct {
|
||||
Address string
|
||||
}
|
||||
|
||||
type closeTunnelFlags struct {
|
||||
LocalOnly bool
|
||||
}
|
||||
|
||||
type createTunnelFlags struct {
|
||||
Address string
|
||||
}
|
||||
|
||||
// lighthouseInfo is one entry of list-lighthouse-addrmap.
|
||||
type lighthouseInfo struct {
|
||||
VpnAddr string `json:"vpnAddr"`
|
||||
Addrs *CacheMap `json:"addrs"`
|
||||
}
|
||||
|
||||
// deviceInfo is the result of device-info.
|
||||
type deviceInfo struct {
|
||||
Name string `json:"name"`
|
||||
Cidr []netip.Prefix `json:"cidr"`
|
||||
}
|
||||
|
||||
// certPEM is the result of print-cert -raw. The PEM form is a different thing to emit,
|
||||
// not a different formatting of the certificate, so it is its own shape.
|
||||
type certPEM struct {
|
||||
PEM string `json:"pem"`
|
||||
}
|
||||
|
||||
// Result shapes for print-relays. Field names are the JSON keys; changing them would
|
||||
// change the output.
|
||||
type relayFor struct {
|
||||
Error string `json:",omitempty"`
|
||||
Type string
|
||||
State string
|
||||
PeerAddr netip.Addr
|
||||
LocalIndex uint32
|
||||
RemoteIndex uint32
|
||||
RelayedThrough []netip.Addr
|
||||
}
|
||||
|
||||
type relayOutput struct {
|
||||
NebulaAddr netip.Addr
|
||||
RelayForAddrs []relayFor
|
||||
}
|
||||
|
||||
type relaysOutput struct {
|
||||
Relays []*relayOutput
|
||||
}
|
||||
|
||||
type versionInfo struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type logLevelInfo struct {
|
||||
Level string `json:"level"`
|
||||
}
|
||||
|
||||
type logFormatInfo struct {
|
||||
Format string `json:"format"`
|
||||
}
|
||||
|
||||
// defineListHostMapFlags declares the flags list-hostmap and list-pending-hostmap share.
|
||||
func defineListHostMapFlags(fl *flag.FlagSet, s *listHostMapFlags) {
|
||||
fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
|
||||
}
|
||||
|
||||
func attachCommands(l *slog.Logger, c *config.C, reg *commands.Registry, f *Interface) {
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.ListHostmap,
|
||||
ShortDescription: "List all known previously connected hosts",
|
||||
Text: commands.Typed(textListHostMap),
|
||||
}, defineListHostMapFlags, func(s *listHostMapFlags, a []string) (commands.Result, error) {
|
||||
return runListHostMap(f.hostMap, s)
|
||||
}))
|
||||
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.ListPendingHostmap,
|
||||
ShortDescription: "List all handshaking hosts",
|
||||
Text: commands.Typed(textListHostMap),
|
||||
}, defineListHostMapFlags, func(s *listHostMapFlags, a []string) (commands.Result, error) {
|
||||
return runListHostMap(f.handshakeManager, s)
|
||||
}))
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.ListLighthouseAddrmap,
|
||||
ShortDescription: "List all lighthouse map entries",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return runListLighthouseMap(f.lightHouse)
|
||||
},
|
||||
Text: commands.Typed(textListLighthouseMap),
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.Reload,
|
||||
ShortDescription: "Reloads configuration from disk, same as sending HUP to the process",
|
||||
// The line goes out before the reload: a reload that restarts the ssh server ends
|
||||
// the session that asked, and this is what it sees.
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Did("Reloading config"), nil
|
||||
},
|
||||
Then: func() commands.Result {
|
||||
return runReload(l, c)
|
||||
},
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.LogLevel,
|
||||
ShortDescription: "Gets or sets the current log level",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return runLogLevel(l, a)
|
||||
},
|
||||
Text: commands.Typed(textLogLevel),
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.LogFormat,
|
||||
ShortDescription: "Gets or sets the current log format",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return runLogFormat(l, a)
|
||||
},
|
||||
Text: commands.Typed(textLogFormat),
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.Version,
|
||||
ShortDescription: "Prints the currently running version of nebula",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value(versionInfo{Version: f.version}), nil
|
||||
},
|
||||
Text: commands.Typed(textVersion),
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.DeviceInfo,
|
||||
ShortDescription: "Prints information about the network device.",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value(runDeviceInfo(f)), nil
|
||||
},
|
||||
Text: commands.Typed(textDeviceInfo),
|
||||
})
|
||||
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.PrintCert,
|
||||
ShortDescription: "Prints the current certificate being used or the certificate for the provided vpn addr",
|
||||
Help: "The vpn addr is an operand or -address, which may carry a port so a connection's remote address can be passed through as is. For a peer it is the certificate nebula verified when the tunnel came up; with no address it is this node's own, the v2 certificate when both versions are loaded. -raw prints the PEM.",
|
||||
Identity: true,
|
||||
Text: textPrintCert,
|
||||
}, func(fl *flag.FlagSet, s *printCertFlags) {
|
||||
fl.BoolVar(&s.Raw, "raw", false, "prints the PEM encoded certificate; with -json, an object holding it")
|
||||
fl.Func("address", "The vpn addr to look up, optionally with a port", s.setAddress)
|
||||
}, func(s *printCertFlags, a []string) (commands.Result, error) {
|
||||
return runPrintCert(f, s, a)
|
||||
}))
|
||||
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.Identity,
|
||||
ShortDescription: "Prints the certificate identity of the host owning the provided vpn addr",
|
||||
Help: "Identity is what the certificate says: name, vpn addrs, networks, groups, fingerprint, issuer and validity. The address may carry a port, so a connection's remote address can be passed through as is. For this node's own identity use whoami.",
|
||||
Identity: true,
|
||||
Text: commands.Typed(textIdentity),
|
||||
}, func(fl *flag.FlagSet, s *identityFlags) {
|
||||
fl.Func("address", "The vpn addr to look up, optionally with a port", s.setAddress)
|
||||
}, func(s *identityFlags, a []string) (commands.Result, error) {
|
||||
return runIdentity(f, s, a)
|
||||
}))
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.Whoami,
|
||||
ShortDescription: "Prints the certificate identity of this node",
|
||||
Help: "The fields identity prints, read from this node's own certificate.",
|
||||
Identity: true,
|
||||
Text: commands.Typed(textIdentity),
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
if len(a) > 0 {
|
||||
return commands.Failed("whoami takes no arguments"), nil
|
||||
}
|
||||
return runWhoami(f)
|
||||
},
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.PrintTunnel,
|
||||
ShortDescription: "Prints json details about a tunnel for the provided vpn addr",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return runPrintTunnel(f, a)
|
||||
},
|
||||
// No Text on purpose: nothing human readable exists yet, and shipping an interim
|
||||
// form would invite scripts against it. ssh defaults these to JSON; ctl asks.
|
||||
JSONOnly: true,
|
||||
})
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.PrintRelays,
|
||||
ShortDescription: "Prints json details about all relay info",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value(runPrintRelays(f)), nil
|
||||
},
|
||||
// No Text on purpose; see print-tunnel.
|
||||
JSONOnly: true,
|
||||
})
|
||||
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.ChangeRemote,
|
||||
ShortDescription: "Changes the remote address used in the tunnel for the provided vpn addr",
|
||||
}, func(fl *flag.FlagSet, s *changeRemoteFlags) {
|
||||
fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
|
||||
}, func(s *changeRemoteFlags, a []string) (commands.Result, error) {
|
||||
return runChangeRemote(f, s, a)
|
||||
}))
|
||||
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.CloseTunnel,
|
||||
ShortDescription: "Closes a tunnel for the provided vpn addr",
|
||||
}, func(fl *flag.FlagSet, s *closeTunnelFlags) {
|
||||
fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
|
||||
}, func(s *closeTunnelFlags, a []string) (commands.Result, error) {
|
||||
return runCloseTunnel(f, s, a)
|
||||
}))
|
||||
|
||||
reg.Register(commands.Flagged(&commands.Command{
|
||||
Name: commands.CreateTunnel,
|
||||
ShortDescription: "Creates a tunnel for the provided vpn address",
|
||||
Help: "The lighthouses will be queried for real addresses but you can provide one as well.",
|
||||
}, func(fl *flag.FlagSet, s *createTunnelFlags) {
|
||||
fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
|
||||
}, func(s *createTunnelFlags, a []string) (commands.Result, error) {
|
||||
return runCreateTunnel(f, s, a)
|
||||
}))
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: commands.QueryLighthouse,
|
||||
ShortDescription: "Query the lighthouses for the provided vpn address",
|
||||
Help: "This command is asynchronous. Only currently known udp addresses will be printed.",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return runQueryLighthouse(f, a)
|
||||
},
|
||||
// No Text on purpose; see print-tunnel.
|
||||
JSONOnly: true,
|
||||
})
|
||||
}
|
||||
|
||||
// runListHostMap computes the hostmap listing. Presentation is Render's job.
|
||||
func runListHostMap(hl controlHostLister, fs *listHostMapFlags) (commands.Result, error) {
|
||||
var hm []ControlHostInfo
|
||||
if fs.ByIndex {
|
||||
hm = listHostMapIndexes(hl)
|
||||
} else {
|
||||
hm = listHostMapHosts(hl)
|
||||
}
|
||||
|
||||
sort.Slice(hm, func(i, j int) bool {
|
||||
return hm[i].VpnAddrs[0].Compare(hm[j].VpnAddrs[0]) < 0
|
||||
})
|
||||
|
||||
return commands.Value(hm), nil
|
||||
}
|
||||
|
||||
// textListHostMap is the human rendering, shared by every surface.
|
||||
func textListHostMap(hm []ControlHostInfo, w io.Writer) error {
|
||||
for _, h := range hm {
|
||||
if _, err := fmt.Fprintf(w, "%s: %s\n", h.VpnAddrs, h.RemoteAddrs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func runListLighthouseMap(lightHouse *LightHouse) (commands.Result, error) {
|
||||
lightHouse.RLock()
|
||||
addrMap := make([]lighthouseInfo, len(lightHouse.addrMap))
|
||||
x := 0
|
||||
for k, v := range lightHouse.addrMap {
|
||||
addrMap[x] = lighthouseInfo{
|
||||
VpnAddr: k.String(),
|
||||
Addrs: v.CopyCache(),
|
||||
}
|
||||
x++
|
||||
}
|
||||
lightHouse.RUnlock()
|
||||
|
||||
sort.Slice(addrMap, func(i, j int) bool {
|
||||
return strings.Compare(addrMap[i].VpnAddr, addrMap[j].VpnAddr) < 0
|
||||
})
|
||||
|
||||
return commands.Value(addrMap), nil
|
||||
}
|
||||
|
||||
func textListLighthouseMap(addrMap []lighthouseInfo, w io.Writer) error {
|
||||
for _, e := range addrMap {
|
||||
b, err := json.Marshal(e.Addrs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "%s: %s\n", e.VpnAddr, string(b)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func textVersion(vi versionInfo, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w, "%s\n", vi.Version)
|
||||
return err
|
||||
}
|
||||
|
||||
// vpnAddrOperand parses the vpn address a command takes as its first operand. noun is
|
||||
// how the command's messages name it, "vpn address" or "vpn addr", which the output
|
||||
// golden pins per command. With no operand, or one that does not parse, ok is false and
|
||||
// res is the refusal to return.
|
||||
func vpnAddrOperand(a []string, noun string) (vpnAddr netip.Addr, res commands.Result, ok bool) {
|
||||
if len(a) == 0 {
|
||||
return netip.Addr{}, commands.Failed("No vpn address was provided"), false
|
||||
}
|
||||
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return netip.Addr{}, commands.Failed("The provided %s could not be parsed: %s", noun, a[0]), false
|
||||
}
|
||||
|
||||
return vpnAddr, commands.Result{}, true
|
||||
}
|
||||
|
||||
// tunnelOperand is vpnAddrOperand followed by the lookup of the tunnel it names.
|
||||
func tunnelOperand(ifce *Interface, a []string, noun string) (*HostInfo, commands.Result, bool) {
|
||||
vpnAddr, res, ok := vpnAddrOperand(a, noun)
|
||||
if !ok {
|
||||
return nil, res, false
|
||||
}
|
||||
|
||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo == nil {
|
||||
return nil, commands.Failed("Could not find tunnel for %s: %v", noun, a[0]), false
|
||||
}
|
||||
|
||||
return hostInfo, commands.Result{}, true
|
||||
}
|
||||
|
||||
func runQueryLighthouse(ifce *Interface, a []string) (commands.Result, error) {
|
||||
vpnAddr, res, ok := vpnAddrOperand(a, "vpn address")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
var cm *CacheMap
|
||||
rl := ifce.lightHouse.Query(vpnAddr)
|
||||
if rl != nil {
|
||||
cm = rl.CopyCache()
|
||||
}
|
||||
return commands.Value(cm), nil
|
||||
}
|
||||
|
||||
func runCloseTunnel(ifce *Interface, flags *closeTunnelFlags, a []string) (commands.Result, error) {
|
||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn address")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if !flags.LocalOnly {
|
||||
ifce.send(
|
||||
header.CloseTunnel,
|
||||
0,
|
||||
hostInfo.ConnectionState,
|
||||
hostInfo,
|
||||
[]byte{},
|
||||
make([]byte, 12, 12),
|
||||
make([]byte, mtu),
|
||||
)
|
||||
}
|
||||
|
||||
ifce.closeTunnel(hostInfo)
|
||||
return commands.Did("Closed"), nil
|
||||
}
|
||||
|
||||
func runCreateTunnel(ifce *Interface, flags *createTunnelFlags, a []string) (commands.Result, error) {
|
||||
|
||||
vpnAddr, res, ok := vpnAddrOperand(a, "vpn address")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr); hostInfo != nil {
|
||||
return commands.Failed("Tunnel already exists"), nil
|
||||
}
|
||||
|
||||
if hostInfo := ifce.handshakeManager.QueryVpnAddr(vpnAddr); hostInfo != nil {
|
||||
return commands.Failed("Tunnel already handshaking"), nil
|
||||
}
|
||||
|
||||
var addr netip.AddrPort
|
||||
if flags.Address != "" {
|
||||
var err error
|
||||
addr, err = netip.ParseAddrPort(flags.Address)
|
||||
if err != nil {
|
||||
return commands.Failed("Address could not be parsed"), nil
|
||||
}
|
||||
}
|
||||
|
||||
// Set the remote from the callback, which StartHandshake runs under the handshake manager lock
|
||||
// before the hostinfo reaches the handshake loop or the static-host trigger, so the address is
|
||||
// in the RemoteList before the first handshake is sent.
|
||||
ifce.handshakeManager.StartHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
|
||||
if addr.IsValid() {
|
||||
hh.hostinfo.SetRemote(addr)
|
||||
}
|
||||
})
|
||||
|
||||
return commands.Did("Created"), nil
|
||||
}
|
||||
|
||||
func runChangeRemote(ifce *Interface, flags *changeRemoteFlags, a []string) (commands.Result, error) {
|
||||
|
||||
if len(a) == 0 {
|
||||
return commands.Failed("No vpn address was provided"), nil
|
||||
}
|
||||
|
||||
if flags.Address == "" {
|
||||
return commands.Failed("No address was provided"), nil
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddrPort(flags.Address)
|
||||
if err != nil {
|
||||
return commands.Failed("Address could not be parsed"), nil
|
||||
}
|
||||
|
||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn address")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
hostInfo.SetRemote(addr)
|
||||
return commands.Did("Changed"), nil
|
||||
}
|
||||
|
||||
func runLogLevel(l *slog.Logger, a []string) (commands.Result, error) {
|
||||
ctrl, ok := l.Handler().(interface {
|
||||
GetLevel() slog.Level
|
||||
SetLevel(slog.Level)
|
||||
})
|
||||
if !ok {
|
||||
return commands.Failed("Log level is not reconfigurable on this logger"), nil
|
||||
}
|
||||
|
||||
if len(a) > 0 {
|
||||
level, err := logging.ParseLevel(strings.ToLower(a[0]))
|
||||
if err != nil {
|
||||
return commands.Failed("Unknown log level %s. Possible log levels: trace, debug, info, warn, error", a), nil
|
||||
}
|
||||
|
||||
ctrl.SetLevel(level)
|
||||
}
|
||||
|
||||
return commands.Value(logLevelInfo{Level: logging.LevelName(ctrl.GetLevel())}), nil
|
||||
}
|
||||
|
||||
func textLogLevel(li logLevelInfo, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w, "Log level is: %s\n", li.Level)
|
||||
return err
|
||||
}
|
||||
|
||||
func runLogFormat(l *slog.Logger, a []string) (commands.Result, error) {
|
||||
ctrl, ok := l.Handler().(interface {
|
||||
GetFormat() string
|
||||
SetFormat(string) error
|
||||
})
|
||||
if !ok {
|
||||
return commands.Failed("Log format is not reconfigurable on this logger"), nil
|
||||
}
|
||||
|
||||
if len(a) > 0 {
|
||||
if err := ctrl.SetFormat(strings.ToLower(a[0])); err != nil {
|
||||
return commands.Failed("Unable to set log format: %s", err), nil
|
||||
}
|
||||
}
|
||||
|
||||
return commands.Value(logFormatInfo{Format: ctrl.GetFormat()}), nil
|
||||
}
|
||||
|
||||
func textLogFormat(fi logFormatInfo, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w, "Log format is: %s\n", fi.Format)
|
||||
return err
|
||||
}
|
||||
|
||||
// runPrintCert prints a certificate: this node's own, or the one the host owning a vpn
|
||||
// addr presented. The addr is an operand, as it always was over ssh, or -address, which
|
||||
// is how the info API names it, and an address of our own answers with our own
|
||||
// certificate as identity does. A tunnel still handshaking, or one being torn down, has
|
||||
// no certificate and is reported as not found.
|
||||
func runPrintCert(ifce *Interface, args *printCertFlags, a []string) (commands.Result, error) {
|
||||
if len(a) > 0 && args.addressSet {
|
||||
return commands.Failed("print-cert takes one vpn addr, as -address or as an operand, not both"), nil
|
||||
}
|
||||
|
||||
cs := ifce.pki.getCertState()
|
||||
var c cert.Certificate
|
||||
switch {
|
||||
case len(a) > 0:
|
||||
vpnAddr, res, ok := vpnAddrOperand(a, "vpn addr")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
if c, _ = findCertificateForVpnAddr(cs, ifce.hostMap, vpnAddr); c == nil {
|
||||
return commands.NotFound("Could not find tunnel for vpn addr: %v", a[0]), nil
|
||||
}
|
||||
case args.addressSet:
|
||||
vpnAddr, err := parseVpnAddrWithOptionalPort(args.Address)
|
||||
if err != nil {
|
||||
return commands.Failed("The provided vpn addr could not be parsed: %s", args.Address), nil
|
||||
}
|
||||
if c, _ = findCertificateForVpnAddr(cs, ifce.hostMap, vpnAddr); c == nil {
|
||||
return commands.NotFound("Could not find tunnel for vpn addr: %v", args.Address), nil
|
||||
}
|
||||
default:
|
||||
if c = ownCertificate(cs); c == nil {
|
||||
return commands.Failed("No certificate is loaded"), nil
|
||||
}
|
||||
}
|
||||
|
||||
if args.Raw {
|
||||
b, err := c.MarshalPEM()
|
||||
if err != nil {
|
||||
return commands.Failed("Unable to marshal the certificate: %s", err), nil
|
||||
}
|
||||
return commands.Value(certPEM{PEM: string(b)}), nil
|
||||
}
|
||||
|
||||
return commands.Value(c), nil
|
||||
}
|
||||
|
||||
// textPrintCert takes the value untyped: print-cert returns a certificate or, with -raw,
|
||||
// its PEM, and those are two things to emit rather than two renderings of one.
|
||||
func textPrintCert(v any, w io.Writer) error {
|
||||
switch c := v.(type) {
|
||||
case certPEM:
|
||||
_, err := io.WriteString(w, c.PEM)
|
||||
return err
|
||||
case cert.Certificate:
|
||||
_, err := io.WriteString(w, c.String()+"\n")
|
||||
return err
|
||||
default:
|
||||
return fmt.Errorf("expected a certificate, got %T", v)
|
||||
}
|
||||
}
|
||||
|
||||
func runPrintRelays(ifce *Interface) any {
|
||||
ifce.hostMap.RLock()
|
||||
relays := maps.Clone(ifce.hostMap.Relays)
|
||||
ifce.hostMap.RUnlock()
|
||||
|
||||
co := relaysOutput{}
|
||||
|
||||
for k, v := range relays {
|
||||
ro := relayOutput{NebulaAddr: v.vpnAddrs[0]}
|
||||
co.Relays = append(co.Relays, &ro)
|
||||
relayHI := ifce.hostMap.QueryVpnAddr(v.vpnAddrs[0])
|
||||
if relayHI == nil {
|
||||
ro.RelayForAddrs = append(ro.RelayForAddrs, relayFor{Error: "could not find hostinfo"})
|
||||
continue
|
||||
}
|
||||
for _, vpnAddr := range relayHI.relayState.CopyRelayForIps() {
|
||||
rf := relayFor{}
|
||||
r, ok := relayHI.relayState.GetRelayForByAddr(vpnAddr)
|
||||
if ok {
|
||||
t := ""
|
||||
switch r.Type {
|
||||
case ForwardingType:
|
||||
t = "forwarding"
|
||||
case TerminalType:
|
||||
t = "terminal"
|
||||
default:
|
||||
t = "unknown"
|
||||
}
|
||||
|
||||
st := ""
|
||||
switch r.State {
|
||||
case Requested:
|
||||
st = "requested"
|
||||
case Established:
|
||||
st = "established"
|
||||
default:
|
||||
st = "unknown"
|
||||
}
|
||||
|
||||
rf.LocalIndex = r.LocalIndex
|
||||
rf.RemoteIndex = r.RemoteIndex
|
||||
rf.PeerAddr = r.PeerAddr
|
||||
rf.Type = t
|
||||
rf.State = st
|
||||
if rf.LocalIndex != k {
|
||||
rf.Error = fmt.Sprintf("hostmap LocalIndex '%v' does not match RelayState LocalIndex", k)
|
||||
}
|
||||
}
|
||||
relayedHI := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if relayedHI != nil {
|
||||
rf.RelayedThrough = append(rf.RelayedThrough, relayedHI.relayState.CopyRelayIps()...)
|
||||
}
|
||||
|
||||
ro.RelayForAddrs = append(ro.RelayForAddrs, rf)
|
||||
}
|
||||
}
|
||||
|
||||
return co
|
||||
}
|
||||
|
||||
func runPrintTunnel(ifce *Interface, a []string) (commands.Result, error) {
|
||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn addr")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
return commands.Value(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges())), nil
|
||||
}
|
||||
|
||||
func runDeviceInfo(ifce *Interface) deviceInfo {
|
||||
d := deviceInfo{
|
||||
Name: ifce.inside.Name(),
|
||||
Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
|
||||
}
|
||||
copy(d.Cidr, ifce.inside.Networks())
|
||||
return d
|
||||
}
|
||||
|
||||
func textDeviceInfo(d deviceInfo, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w, "name=%v cidr=%v\n", d.Name, d.Cidr)
|
||||
return err
|
||||
}
|
||||
|
||||
// runReload reloads the config and reports how it went. A reload that failed is a
|
||||
// refusal, exit 1 over ssh; one that merely needs a restart is not.
|
||||
func runReload(l *slog.Logger, c *config.C) commands.Result {
|
||||
res := c.ReloadConfig()
|
||||
res.Log(l)
|
||||
if res.Err != nil || res.Failed {
|
||||
return commands.Failed("%s", res.String())
|
||||
}
|
||||
return commands.Did("%s", res.String())
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CommandFlags is called before help or command execution to parse command line flags.
|
||||
// It should return a flag.FlagSet instance and a pointer to the struct that will contain parsed flags
|
||||
//
|
||||
// Every call must build a fresh FlagSet and a fresh struct. Nothing may be shared between
|
||||
// calls: a command runs on more than one surface and on more than one goroutine.
|
||||
type CommandFlags func() (*flag.FlagSet, any)
|
||||
|
||||
// RunFunc computes a command's Result.
|
||||
//
|
||||
// fs is the pointer returned by Command.Flags, if there was one; -h, -help, -json and
|
||||
// -pretty are reserved and handled before Run is called. a is the operands: whatever
|
||||
// was not consumed as a flag. The Result is rendered by whichever surface asked: Value
|
||||
// for a command that reports, Did or Failed for one that acts, Nothing for one with
|
||||
// nothing to say. An error is for a failure of the command itself; a bad argument is
|
||||
// Failed, so the caller hears why in its own format.
|
||||
type RunFunc func(fs any, a []string) (Result, error)
|
||||
|
||||
// TextFunc renders a Result's Value for a person. See Typed for declaring one against
|
||||
// the type the command actually returns.
|
||||
type TextFunc func(v any, w io.Writer) error
|
||||
|
||||
type Command struct {
|
||||
Name Name
|
||||
ShortDescription string
|
||||
Help string
|
||||
|
||||
// Identity indicates this command should be made available via the info socket.
|
||||
Identity bool
|
||||
|
||||
Flags CommandFlags
|
||||
|
||||
// Run produces the command's Result, leaving presentation to Render.
|
||||
Run RunFunc
|
||||
|
||||
// Text renders a Result's Value for a person. Both surfaces call it, so a command
|
||||
// reads the same over ssh as it does through the control socket. It never sees an
|
||||
// outcome: Render prints those itself, the same way for every command. Leaving it
|
||||
// nil declares that no human rendering of the Value exists yet, which JSONOnly says
|
||||
// up front; Render then refuses text rather than inventing an interim form for
|
||||
// people to script against.
|
||||
Text TextFunc
|
||||
|
||||
// JSONOnly declares that the command's Value has no human rendering yet, so a surface
|
||||
// whose default is text asks for JSON instead, and the schema says so to a client. It
|
||||
// is a statement that no such form exists, not a fallback. A refusal is still
|
||||
// rendered as a sentence, since that always has a human form.
|
||||
JSONOnly bool
|
||||
|
||||
// Then, when set, is the second half of a command that acts: Run says what is about
|
||||
// to happen and Then does it and says how it went, with its Result rendered after
|
||||
// Run's and deciding the outcome. A Run that refused is the outcome, and Then does
|
||||
// not run. It exists for a command whose action can cut off
|
||||
// its own reply: reload restarts the ssh server when the sshd keys changed, which
|
||||
// ends the session that asked, so Run's line has to be on the wire before the reload
|
||||
// begins. A surface that answers in one piece, the control socket, runs Then before
|
||||
// it answers and carries both.
|
||||
Then func() Result
|
||||
}
|
||||
|
||||
// Failure is the error a surface gets for a refusal the person has already been shown:
|
||||
// a Run that returned Failed, a command that is not there, a line that would not parse.
|
||||
// The message it rendered is the whole story, so the surface reports the failure, exit
|
||||
// status 1 over ssh, and does not log it.
|
||||
type Failure struct {
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (f *Failure) Error() string {
|
||||
return f.Msg
|
||||
}
|
||||
|
||||
// commandFlags returns the FlagSet a command is driven through, on any surface: the
|
||||
// command's own flags, if it declares any, with the two presentation flags added. own
|
||||
// reports whether the command declared any of its own, which is what tells a caller
|
||||
// whether to say a parameter is unknown or that the command takes none at all.
|
||||
//
|
||||
// The presentation flags are defined here rather than by each command, because how a
|
||||
// result is displayed is not a property of the command that produced it. This is also
|
||||
// the one definition of them: the ssh line parses into it, nebula ctl parses its line
|
||||
// against the schema derived from it, and help renders from that schema. They are
|
||||
// command line flags only: a socket request chooses its rendering with the envelope's
|
||||
// format field, and Invoke refuses them as parameters.
|
||||
func commandFlags(c *Command) (fl *flag.FlagSet, fs any, own bool) {
|
||||
if c.Flags != nil {
|
||||
fl, fs = c.Flags()
|
||||
}
|
||||
own = fl != nil
|
||||
if fl == nil {
|
||||
fl = flag.NewFlagSet(string(c.Name), flag.ContinueOnError)
|
||||
}
|
||||
|
||||
addPresentationFlags(fl)
|
||||
|
||||
// What Parse prints after a bad flag, and for -h: the command's usage as help renders
|
||||
// it, so a line that went wrong is answered with the same text as `help <command>`.
|
||||
fl.Usage = func() { _ = WriteCommandHelp(schemaOf(c, fl), fl.Output()) }
|
||||
|
||||
return fl, fs, own
|
||||
}
|
||||
|
||||
// addPresentationFlags defines the two presentation flags on fl.
|
||||
func addPresentationFlags(fl *flag.FlagSet) {
|
||||
fl.Bool(FlagJSON, false, "outputs as json")
|
||||
fl.Bool(FlagPretty, false, "pretty prints json, assumes -json")
|
||||
}
|
||||
|
||||
// Flagged fills in c's Flags and Run as a pair: define declares the flags on a fresh F,
|
||||
// and run is handed that F. The struct the flags fill is the struct Run reads by
|
||||
// construction, so no Run has to assert the type it was given or decide what to do
|
||||
// when the assertion fails.
|
||||
func Flagged[F any](c *Command, define func(*flag.FlagSet, *F), run func(*F, []string) (Result, error)) *Command {
|
||||
c.Flags = func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := new(F)
|
||||
define(fl, s)
|
||||
return fl, s
|
||||
}
|
||||
c.Run = func(fs any, a []string) (Result, error) {
|
||||
s, ok := fs.(*F)
|
||||
if !ok {
|
||||
return Result{}, fmt.Errorf("%s was handed %T for its flags, not %T", c.Name, fs, s)
|
||||
}
|
||||
return run(s, a)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// isPresentationFlag reports whether name is one of the two flags commandFlags adds.
|
||||
func isPresentationFlag(name string) bool {
|
||||
return name == FlagJSON || name == FlagPretty
|
||||
}
|
||||
|
||||
// execLine runs an ssh command line against c, reporting problems to w. The line is
|
||||
// parsed into the command's own FlagSet and Run reads it directly, so a flag.Value whose
|
||||
// String does not re-parse, flag.Func above all, arrives as the line said. Invoke fills
|
||||
// the same FlagSet through Set.
|
||||
func (r *Registry) execLine(c *Command, args []string, w Output) error {
|
||||
fl, fs, _ := commandFlags(c)
|
||||
|
||||
// Parse reports a bad flag to this writer, with the command's usage after it. -h,
|
||||
// -help and --help take the same path with nothing wrong: the usage is the whole
|
||||
// answer, and Parse says so with ErrHelp. A -h that is a flag's value or follows --
|
||||
// is read as the operand it is, since ParseArgs is the one reading of the line.
|
||||
fl.SetOutput(w.Err)
|
||||
operands, err := ParseArgs(fl, args)
|
||||
if err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
format := presentationFormat(fl)
|
||||
|
||||
// An error from Run is something the command could not do rather than a refusal it
|
||||
// chose, but the person at the prompt still hears it; the surface logs it too.
|
||||
res, err := c.Run(fs, operands)
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintln(w.Err, err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
// Run's reply goes out first, and then the action, if the command has one and Run
|
||||
// did not refuse, whose Result is the outcome. In JSON only the outcome travels:
|
||||
// the promise is for a person to read, and a program expects one document.
|
||||
if c.Then == nil || !res.OK || r.formatFor(c, res, format) == FormatText {
|
||||
if err := r.renderLine(c, res, format, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if c.Then != nil && res.OK {
|
||||
res = c.Then()
|
||||
if err := r.renderLine(c, res, format, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if !res.OK {
|
||||
return &Failure{Msg: res.Reason}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// formatFor is the format a Result is rendered in. The line wins when it asked for one;
|
||||
// otherwise the surface that owns the registry decides, from the command and its
|
||||
// Result, so each surface can keep its own default.
|
||||
func (r *Registry) formatFor(c *Command, res Result, format Format) Format {
|
||||
if format == FormatUnset {
|
||||
return r.defaultFormatFor(c, res)
|
||||
}
|
||||
return format
|
||||
}
|
||||
|
||||
// renderLine writes one Result of a command line to w; see formatFor. An empty Result
|
||||
// writes nothing.
|
||||
func (r *Registry) renderLine(c *Command, res Result, format Format, w Output) error {
|
||||
if res.Empty() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := Render(c, res, r.formatFor(c, res, format), w.Out); err != nil {
|
||||
if errors.Is(err, ErrNoTextRendering) {
|
||||
_, _ = fmt.Fprintln(w.Err, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseArgs parses args with fl and returns the operands.
|
||||
//
|
||||
// It differs from fl.Parse in two ways, and both surfaces parse through here so a line
|
||||
// means the same typed at an ssh prompt or to nebula ctl.
|
||||
//
|
||||
// Flags and operands may come in any order, which is the one way it differs from
|
||||
// fl.Parse. Parse stops at the first operand, so `print-tunnel 10.0.0.1 -json` would
|
||||
// reach the command with "-json" as a second operand and the flag silently dropped. Here
|
||||
// an operand ends nothing: parsing resumes after it, and only "--" ends the flags, with
|
||||
// everything after it an operand. What counts as a flag is Parse's rule: every argument
|
||||
// that starts with "-", a negative number included, so one that is meant as an operand
|
||||
// goes after "--".
|
||||
func ParseArgs(fl *flag.FlagSet, args []string) ([]string, error) {
|
||||
operands := make([]string, 0, len(args))
|
||||
|
||||
for len(args) > 0 {
|
||||
// Walk the flags the way Parse will, to the first argument it would not read as a
|
||||
// flag: an operand or the terminator. Everything before it is Parse's.
|
||||
end := len(args)
|
||||
for i := 0; i < len(args); {
|
||||
a := args[i]
|
||||
if a == "--" {
|
||||
if err := fl.Parse(args[:i]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(operands, args[i+1:]...), nil
|
||||
}
|
||||
|
||||
if len(a) < 2 || a[0] != '-' {
|
||||
end = i
|
||||
break
|
||||
}
|
||||
|
||||
f, hasValue := LookupArg(fl, a)
|
||||
if f == nil {
|
||||
// An undefined flag: leave it for Parse to report.
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
if hasValue || IsBoolFlag(f) {
|
||||
i++
|
||||
} else {
|
||||
// The flag's value is the next argument, whatever it looks like.
|
||||
i += 2
|
||||
}
|
||||
}
|
||||
|
||||
if err := fl.Parse(args[:end]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if end == len(args) {
|
||||
break
|
||||
}
|
||||
|
||||
operands = append(operands, args[end])
|
||||
args = args[end+1:]
|
||||
}
|
||||
|
||||
return operands, nil
|
||||
}
|
||||
|
||||
// LookupArg reads arg the way Parse does: one or two leading dashes, the flag's name, and
|
||||
// an optional "=value". f is the flag of fl by that name, nil when fl has none, and
|
||||
// hasValue reports that the value came with the argument rather than in the one after it.
|
||||
// It is the one reading of an argument's shape: ParseArgs walks a line with it, and
|
||||
// nebula ctl lifts its own flags out of a line with it, so the two cannot disagree about
|
||||
// which word is a flag's value.
|
||||
func LookupArg(fl *flag.FlagSet, arg string) (f *flag.Flag, hasValue bool) {
|
||||
name := strings.TrimPrefix(strings.TrimPrefix(arg, "-"), "-")
|
||||
if eq := strings.IndexByte(name, '='); eq >= 0 {
|
||||
name, hasValue = name[:eq], true
|
||||
}
|
||||
return fl.Lookup(name), hasValue
|
||||
}
|
||||
|
||||
// IsBoolFlag reports whether f is satisfied by its presence alone and never reads the
|
||||
// argument after it as its value. The flag package marks these with an unexported
|
||||
// interface, which is the only way to tell.
|
||||
func IsBoolFlag(f *flag.Flag) bool {
|
||||
bf, ok := f.Value.(interface{ IsBoolFlag() bool })
|
||||
return ok && bf.IsBoolFlag()
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestParseArgsAllowsFlagsAfterOperands pins the one way ParseArgs departs from fl.Parse,
|
||||
// that a flag may follow an operand, and that it departs in no other: a negative number
|
||||
// is a flag, as Parse reads it, and goes after "--" when it is meant as an operand.
|
||||
func TestParseArgsAllowsFlagsAfterOperands(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
args []string
|
||||
wantOps []string
|
||||
wantN string
|
||||
wantV bool
|
||||
wantJSON bool
|
||||
wantErr string
|
||||
}{
|
||||
"flag after operand": {args: []string{"x", "-json"}, wantOps: []string{"x"}, wantJSON: true},
|
||||
"flags around": {args: []string{"-v", "x", "-n", "1", "y"}, wantOps: []string{"x", "y"}, wantV: true, wantN: "1"},
|
||||
"value after operand": {args: []string{"x", "-n", "-1"}, wantOps: []string{"x"}, wantN: "-1"},
|
||||
"equals value": {args: []string{"-n=-1", "x"}, wantOps: []string{"x"}, wantN: "-1"},
|
||||
"terminator after": {args: []string{"x", "--", "-json", "-1"}, wantOps: []string{"x", "-json", "-1"}},
|
||||
"terminator": {args: []string{"--", "-json"}, wantOps: []string{"-json"}},
|
||||
"defined numeric": {args: []string{"-2", "x"}, wantOps: []string{"x"}, wantV: true},
|
||||
"negative number": {args: []string{"-1"}, wantErr: "flag provided but not defined: -1"},
|
||||
"bad flag after": {args: []string{"x", "-nope"}, wantErr: "flag provided but not defined: -nope"},
|
||||
"undefined flag": {args: []string{"-nope", "x"}, wantErr: "flag provided but not defined: -nope"},
|
||||
"missing value": {args: []string{"-n"}, wantErr: "flag needs an argument: -n"},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fl := flag.NewFlagSet("t", flag.ContinueOnError)
|
||||
fl.SetOutput(&bytes.Buffer{})
|
||||
n := fl.String("n", "", "")
|
||||
v := fl.Bool("v", false, "")
|
||||
two := fl.Bool("2", false, "a flag that happens to be a number")
|
||||
asJSON := fl.Bool(FlagJSON, false, "")
|
||||
|
||||
ops, err := ParseArgs(fl, tc.args)
|
||||
if tc.wantErr != "" {
|
||||
require.ErrorContains(t, err, tc.wantErr)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.wantOps, ops)
|
||||
assert.Equal(t, tc.wantN, *n)
|
||||
assert.Equal(t, tc.wantV, *v || *two)
|
||||
assert.Equal(t, tc.wantJSON, *asJSON)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchFlagAfterOperand: the same through a registered command with no Flags of
|
||||
// its own, which only has the presentation flags to find.
|
||||
func TestDispatchFlagAfterOperand(t *testing.T) {
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, testRegistry().DispatchArgs([]string{"served", "x", "-json"}, MergedOutput(out)))
|
||||
assert.Equal(t, "\"read x\"\n", out.String())
|
||||
}
|
||||
|
||||
// TestLookupArg pins the reading of an argument's shape that ParseArgs and nebula ctl
|
||||
// share.
|
||||
func TestLookupArg(t *testing.T) {
|
||||
fl := flag.NewFlagSet("t", flag.ContinueOnError)
|
||||
fl.String("n", "", "")
|
||||
fl.Bool("v", false, "")
|
||||
|
||||
for _, tc := range []struct {
|
||||
arg string
|
||||
name string
|
||||
hasValue bool
|
||||
}{
|
||||
{"-n", "n", false},
|
||||
{"--n", "n", false},
|
||||
{"-n=1", "n", true},
|
||||
{"--n=", "n", true},
|
||||
{"-v", "v", false},
|
||||
{"-nope", "", false},
|
||||
{"-1", "", false},
|
||||
} {
|
||||
f, hasValue := LookupArg(fl, tc.arg)
|
||||
if tc.name == "" {
|
||||
assert.Nil(t, f, tc.arg)
|
||||
} else {
|
||||
require.NotNil(t, f, tc.arg)
|
||||
assert.Equal(t, tc.name, f.Name, tc.arg)
|
||||
}
|
||||
assert.Equal(t, tc.hasValue, hasValue, tc.arg)
|
||||
}
|
||||
|
||||
assert.True(t, IsBoolFlag(fl.Lookup("v")))
|
||||
assert.False(t, IsBoolFlag(fl.Lookup("n")))
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package commands
|
||||
|
||||
// Name identifies a command. Every command nebula serves is a constant here, so a
|
||||
// surface, a client and a test spell it the same way and are told at compile time when
|
||||
// they do not. It is a string rather than an integer so a test can register a throwaway
|
||||
// command without adding it here, and so the wire carries the name as the string it has
|
||||
// always been.
|
||||
type Name string
|
||||
|
||||
const (
|
||||
ChangeRemote Name = "change-remote"
|
||||
CloseTunnel Name = "close-tunnel"
|
||||
CreateTunnel Name = "create-tunnel"
|
||||
DeviceInfo Name = "device-info"
|
||||
Help Name = "help"
|
||||
Identity Name = "identity"
|
||||
ListHostmap Name = "list-hostmap"
|
||||
ListLighthouseAddrmap Name = "list-lighthouse-addrmap"
|
||||
ListPendingHostmap Name = "list-pending-hostmap"
|
||||
LogFormat Name = "log-format"
|
||||
LogLevel Name = "log-level"
|
||||
Logout Name = "logout"
|
||||
PrintCert Name = "print-cert"
|
||||
PrintRelays Name = "print-relays"
|
||||
PrintTunnel Name = "print-tunnel"
|
||||
QueryLighthouse Name = "query-lighthouse"
|
||||
Reload Name = "reload"
|
||||
Version Name = "version"
|
||||
Whoami Name = "whoami"
|
||||
)
|
||||
@@ -1,456 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/anmitsu/go-shlex"
|
||||
)
|
||||
|
||||
// Registry holds a set of commands.
|
||||
//
|
||||
// It is safe for concurrent use: the ssh server clones it per session and the control
|
||||
// socket serves it as it is, while the daemon fills it once at startup.
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
commands map[Name]*Command
|
||||
|
||||
// full is set on a filtered registry and points at the registry it was filtered
|
||||
// from, so a command that's filtered can be reported as such.
|
||||
full *Registry
|
||||
|
||||
// reason explains, in the terms an operator cares about, why this registry withholds
|
||||
// a command they can name. It is supplied by whoever built the filter, because why a
|
||||
// surface declines a command is that surface's business, not the registry's.
|
||||
reason string
|
||||
|
||||
// DefaultFormat decides how a result is rendered when the command line named no
|
||||
// format. It sees the command and its Result, and applies to values and refusals
|
||||
// alike: the registry does not special-case either. The renderer is shared between
|
||||
// surfaces; what each asks for by default is not, so the surface that owns this
|
||||
// registry sets it. Nil means text.
|
||||
DefaultFormat func(c *Command, r Result) Format
|
||||
}
|
||||
|
||||
// defaultFormatFor resolves the surface's default for c's Result.
|
||||
func (r *Registry) defaultFormatFor(c *Command, res Result) Format {
|
||||
if r.DefaultFormat == nil {
|
||||
return FormatText
|
||||
}
|
||||
return r.DefaultFormat(c, res)
|
||||
}
|
||||
|
||||
// New returns an empty Registry with only `help` available.
|
||||
func New() *Registry {
|
||||
r := &Registry{commands: map[Name]*Command{}}
|
||||
r.registerHelp()
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *Registry) registerHelp() {
|
||||
r.Register(&Command{
|
||||
Name: Help,
|
||||
ShortDescription: "prints available commands or help <command> for specific usage info",
|
||||
Run: func(a any, args []string) (Result, error) {
|
||||
if len(args) == 0 {
|
||||
return Value(r.Schema()), nil
|
||||
}
|
||||
|
||||
c, err := r.Resolve(Name(args[0]))
|
||||
if err != nil {
|
||||
var withheld *WithheldError
|
||||
if errors.As(err, &withheld) {
|
||||
return Failed("%s", err), nil
|
||||
}
|
||||
return Failed("Command not available %s", args[0]), nil
|
||||
}
|
||||
|
||||
return Value(r.SchemaFor(c)), nil
|
||||
},
|
||||
Text: renderHelp,
|
||||
})
|
||||
}
|
||||
|
||||
// renderHelp is help's human rendering: the command list, or one command's usage.
|
||||
func renderHelp(v any, w io.Writer) error {
|
||||
switch h := v.(type) {
|
||||
case []CommandSchema:
|
||||
return writeCommandList(h, w)
|
||||
case CommandSchema:
|
||||
return WriteCommandHelp(h, w)
|
||||
default:
|
||||
return fmt.Errorf("expected a command schema, got %T", v)
|
||||
}
|
||||
}
|
||||
|
||||
func writeCommandList(cmds []CommandSchema, w io.Writer) error {
|
||||
if _, err := io.WriteString(w, "Available commands:\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// In the order the schema came, which is the display order; see Registry.All.
|
||||
lines := make([]string, 0, len(cmds))
|
||||
for _, c := range cmds {
|
||||
lines = append(lines, fmt.Sprintf("%s - %s", c.Name, c.Short))
|
||||
}
|
||||
|
||||
_, err := io.WriteString(w, strings.Join(lines, "\n")+"\n\n")
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteCommandHelp renders one command's usage. It is the single rendering of a
|
||||
// CommandSchema for a person: the daemon uses it for `help <command>` on both surfaces,
|
||||
// and a client that already holds the schema uses it for `-h`, so the two cannot drift.
|
||||
func WriteCommandHelp(c CommandSchema, w io.Writer) error {
|
||||
if _, err := fmt.Fprintf(w, "%s - %s\n", c.Name, c.Short); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if c.Help != "" {
|
||||
if _, err := fmt.Fprintf(w, " %s\n", c.Help); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Same layout as flag.PrintDefaults, including its habit of leaving out a default
|
||||
// that is the zero value.
|
||||
for _, f := range c.Flags {
|
||||
kind := ""
|
||||
if !f.Bool {
|
||||
kind = " string"
|
||||
}
|
||||
def := ""
|
||||
if f.Default != "" && f.Default != "false" {
|
||||
def = fmt.Sprintf(" (default %s)", f.Default)
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, " -%s%s\n \t%s%s\n", f.Name, kind, f.Usage, def); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Register adds a command that can be run by a user.
|
||||
//
|
||||
// It panics if the command declares a reserved flag. That is a programming error, and
|
||||
// surfacing it here, at startup, is better than at the moment an operator first types
|
||||
// the command.
|
||||
func (r *Registry) Register(c *Command) {
|
||||
if c.Run == nil {
|
||||
panic(fmt.Sprintf("commands: %s has no Run", c.Name))
|
||||
}
|
||||
|
||||
if c.Flags != nil {
|
||||
if fl, _ := c.Flags(); fl != nil {
|
||||
for _, name := range reservedFlags {
|
||||
if fl.Lookup(name) != nil {
|
||||
panic(fmt.Sprintf("commands: %s declares reserved flag -%s", c.Name, name))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r.insert(c)
|
||||
}
|
||||
|
||||
// insert adds c without the reserved flag check, for commands that have already passed
|
||||
// it on another registry.
|
||||
func (r *Registry) insert(c *Command) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.commands[c.Name] = c
|
||||
}
|
||||
|
||||
// Get returns the command registered under name, or nil if there is no such command.
|
||||
func (r *Registry) Get(name Name) *Command {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.commands[name]
|
||||
}
|
||||
|
||||
// Match returns the names of every command starting with prefix, sorted, as strings for
|
||||
// a prompt to complete and print.
|
||||
func (r *Registry) Match(prefix string) []string {
|
||||
cmds := make([]string, 0)
|
||||
r.mu.RLock()
|
||||
for n := range r.commands {
|
||||
if strings.HasPrefix(string(n), prefix) {
|
||||
cmds = append(cmds, string(n))
|
||||
}
|
||||
}
|
||||
r.mu.RUnlock()
|
||||
slices.Sort(cmds)
|
||||
return cmds
|
||||
}
|
||||
|
||||
// All returns every registered command sorted by name, which is the order help lists
|
||||
// them and the schema describes them.
|
||||
func (r *Registry) All() []*Command {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
cmds := slices.Collect(maps.Values(r.commands))
|
||||
slices.SortFunc(cmds, func(a, b *Command) int { return cmp.Compare(a.Name, b.Name) })
|
||||
return cmds
|
||||
}
|
||||
|
||||
// Clone returns a copy holding the same commands.
|
||||
//
|
||||
// help is re-registered on the copy rather than carried over, because the source's help
|
||||
// is bound to the source and would list its commands, not the copy's, once a caller
|
||||
// registers something on the copy.
|
||||
func (r *Registry) Clone() *Registry {
|
||||
r.mu.RLock()
|
||||
out := &Registry{
|
||||
commands: maps.Clone(r.commands),
|
||||
full: r.full,
|
||||
reason: r.reason,
|
||||
DefaultFormat: r.DefaultFormat,
|
||||
}
|
||||
r.mu.RUnlock()
|
||||
|
||||
out.registerHelp()
|
||||
return out
|
||||
}
|
||||
|
||||
// Filter returns a filtered copy of the registry.
|
||||
//
|
||||
// Keep should return true for commands that should be included in the copy. reason
|
||||
// says, to an operator who names a command the copy left out, why this surface does
|
||||
// not serve it; "" leaves the registry to say only that it does not.
|
||||
func (r *Registry) Filter(keep func(*Command) bool, reason string) *Registry {
|
||||
out := &Registry{commands: map[Name]*Command{}, full: r, reason: reason, DefaultFormat: r.DefaultFormat}
|
||||
|
||||
for _, cmd := range r.All() {
|
||||
if keep(cmd) {
|
||||
out.insert(cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// Bind help to the filtered set so it only advertises what this surface serves.
|
||||
out.registerHelp()
|
||||
return out
|
||||
}
|
||||
|
||||
// Dispatch parses a command line and runs it, reporting problems to w. The error is for
|
||||
// the caller to log, not to show; see RunFunc and Failure.
|
||||
func (r *Registry) Dispatch(line string, w Output) error {
|
||||
// A line shlex cannot split, an unbalanced quote. Reported on Err so the output
|
||||
// stream stays parseable.
|
||||
args, err := shlex.Split(line, true)
|
||||
if err != nil {
|
||||
msg := "could not parse the command line: " + err.Error()
|
||||
if _, err := fmt.Fprintln(w.Err, msg); err != nil {
|
||||
return err
|
||||
}
|
||||
return &Failure{Msg: msg}
|
||||
}
|
||||
|
||||
return r.DispatchArgs(args, w)
|
||||
}
|
||||
|
||||
// DispatchArgs runs an already tokenized command line. The error is as for Dispatch.
|
||||
//
|
||||
// An empty line and an unknown command both end up running `help`, the first with the
|
||||
// arguments help itself would take; `<command> -h` is answered by the command's own
|
||||
// FlagSet, with the same rendering, in execLine.
|
||||
func (r *Registry) DispatchArgs(args []string, w Output) error {
|
||||
if len(args) == 0 {
|
||||
args = []string{"help"}
|
||||
}
|
||||
|
||||
c, err := r.Resolve(Name(args[0]))
|
||||
if err != nil {
|
||||
var withheld *WithheldError
|
||||
if errors.As(err, &withheld) {
|
||||
// Saying why, rather than "did not understand", keeps the rule legible and
|
||||
// points at a surface that will actually run the command.
|
||||
_, _ = fmt.Fprintln(w.Err, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Only the first word was looked up, so only it is named.
|
||||
msg := fmt.Sprintf("did not understand: %s", args[0])
|
||||
if _, err := fmt.Fprintln(w.Out, msg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := r.DispatchArgs([]string{"help"}, w); err != nil {
|
||||
return err
|
||||
}
|
||||
return &Failure{Msg: msg}
|
||||
}
|
||||
|
||||
return r.execLine(c, args[1:], w)
|
||||
}
|
||||
|
||||
// unavailable explains why name cannot be run here when this registry was filtered from
|
||||
// one that holds it: the command exists, and this surface withholds it, for the reason
|
||||
// whoever built the filter gave. It is nil when name is simply unknown, so the two cases
|
||||
// read differently to an operator.
|
||||
func (r *Registry) unavailable(name Name) error {
|
||||
if r.full == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
c := r.full.Get(name)
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
reason := r.reason
|
||||
if reason == "" {
|
||||
reason = "this surface does not serve it"
|
||||
}
|
||||
|
||||
return &WithheldError{msg: fmt.Sprintf("%s is not available on this surface: %s", c.Name, reason)}
|
||||
}
|
||||
|
||||
// WithheldError indicates that the command is supported by Nebula, but not via this path.
|
||||
type WithheldError struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e *WithheldError) Error() string { return e.msg }
|
||||
|
||||
// Resolve returns the command registered under name, or says why there is none: a
|
||||
// WithheldError with the filter's reason, or unknown for a name that does not exist.
|
||||
func (r *Registry) Resolve(name Name) (*Command, error) {
|
||||
if c := r.Get(name); c != nil {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
if err := r.unavailable(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unknown command %q", name)
|
||||
}
|
||||
|
||||
// ParamError is what Invoke returns for a parameter the command would not take: one it
|
||||
// does not have, or a value its flag would not parse. It is the caller's mistake rather
|
||||
// than the command's failure, and a surface with status codes tells the two apart by
|
||||
// it; every other error from Invoke came out of Run.
|
||||
type ParamError struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e *ParamError) Error() string { return e.msg }
|
||||
|
||||
func paramErrorf(format string, args ...any) error {
|
||||
return &ParamError{msg: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
|
||||
// setParams sets each named parameter on fl, in the order of names, and stops at the
|
||||
// first that is unknown or does not parse. own says whether the command declared flags
|
||||
// of its own, which decides between "takes no parameters" and "has no parameter".
|
||||
//
|
||||
// The presentation flags are on fl, since commandFlags put them there, but they are not
|
||||
// parameters: a request has one place to choose its rendering, the envelope's format
|
||||
// field, and a client that sends them here is told where that is rather than having a
|
||||
// second, weaker way to say the same thing.
|
||||
func setParams(fl *flag.FlagSet, name string, names []string, params map[string]string, own bool) error {
|
||||
for _, k := range names {
|
||||
if isPresentationFlag(k) {
|
||||
return paramErrorf("%s is a command line flag, not a parameter; choose the rendering with the request's format field", k)
|
||||
}
|
||||
|
||||
f := fl.Lookup(k)
|
||||
if f == nil {
|
||||
if !own {
|
||||
return paramErrorf("%s takes no parameters", name)
|
||||
}
|
||||
return paramErrorf("%s has no parameter %q", name, k)
|
||||
}
|
||||
|
||||
if err := setFlag(fl, f, params[k]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// setFlag applies one value to f, reporting a refusal as a ParamError in words that
|
||||
// name the value: the flag package's own words for a bad boolean are "parse error".
|
||||
func setFlag(fl *flag.FlagSet, f *flag.Flag, v string) error {
|
||||
if err := fl.Set(f.Name, v); err != nil {
|
||||
if IsBoolFlag(f) {
|
||||
return paramErrorf("%s: expected a boolean, got %q", f.Name, v)
|
||||
}
|
||||
return paramErrorf("%s: %v", f.Name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Schema describes every command in the registry, so a client can offer them without
|
||||
// having been built against this daemon.
|
||||
func (r *Registry) Schema() []CommandSchema {
|
||||
all := r.All()
|
||||
out := make([]CommandSchema, 0, len(all))
|
||||
for _, c := range all {
|
||||
out = append(out, r.SchemaFor(c))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SchemaFor describes one command. It is the one derivation, for the whole schema and
|
||||
// for `help <command>` alike.
|
||||
func (r *Registry) SchemaFor(c *Command) CommandSchema {
|
||||
fl, _, _ := commandFlags(c)
|
||||
return schemaOf(c, fl)
|
||||
}
|
||||
|
||||
// schemaOf describes c as driven through fl, the FlagSet commandFlags built for it. The
|
||||
// presentation flags are included because a command line client parses its line
|
||||
// against this and help renders from it; they are listed after the command's own,
|
||||
// which is where readers expect them. Invoke refuses them as parameters.
|
||||
func schemaOf(c *Command, fl *flag.FlagSet) CommandSchema {
|
||||
cs := CommandSchema{Name: c.Name, Short: c.ShortDescription, Help: c.Help}
|
||||
|
||||
var own, shared []FlagSchema
|
||||
fl.VisitAll(func(f *flag.Flag) {
|
||||
fs := FlagSchema{
|
||||
Name: f.Name,
|
||||
Bool: IsBoolFlag(f),
|
||||
Default: f.DefValue,
|
||||
Usage: f.Usage,
|
||||
}
|
||||
if isPresentationFlag(f.Name) {
|
||||
shared = append(shared, fs)
|
||||
return
|
||||
}
|
||||
own = append(own, fs)
|
||||
})
|
||||
cs.Flags = append(own, shared...)
|
||||
|
||||
return cs
|
||||
}
|
||||
|
||||
// CommandSchema describes one command well enough for a client to offer it.
|
||||
type CommandSchema struct {
|
||||
Name Name `json:"name"`
|
||||
Short string `json:"short,omitempty"`
|
||||
Help string `json:"help,omitempty"`
|
||||
Flags []FlagSchema `json:"flags,omitempty"`
|
||||
}
|
||||
|
||||
// FlagSchema describes one of a command's named parameters.
|
||||
type FlagSchema struct {
|
||||
Name string `json:"name"`
|
||||
|
||||
// Bool reports a parameter that takes no value, which is what tells a command line
|
||||
// client whether `-pretty` swallows the word after it.
|
||||
Bool bool `json:"bool,omitempty"`
|
||||
|
||||
Default string `json:"default,omitempty"`
|
||||
Usage string `json:"usage,omitempty"`
|
||||
}
|
||||
@@ -1,481 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"flag"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// notWithheld is a stand in for a surface's own policy, which the registry knows nothing
|
||||
// of; see Command.Identity for the one the info API applies.
|
||||
func notWithheld(c *Command) bool { return c.Name != "withheld" }
|
||||
|
||||
const testReason = "this surface does not run commands that write"
|
||||
|
||||
// textLine is a Text renderer for test commands whose result is one string.
|
||||
func textLine(v any, w io.Writer) error {
|
||||
_, err := io.WriteString(w, v.(string)+"\n")
|
||||
return err
|
||||
}
|
||||
|
||||
func testRegistry() *Registry {
|
||||
r := New()
|
||||
r.Register(&Command{
|
||||
Name: "served",
|
||||
ShortDescription: "a command this surface serves",
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
return Value("read " + strings.Join(a, ",")), nil
|
||||
},
|
||||
Text: textLine,
|
||||
})
|
||||
r.Register(&Command{
|
||||
Name: "withheld",
|
||||
ShortDescription: "a command this surface withholds",
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
return Value("wrote"), nil
|
||||
},
|
||||
Text: textLine,
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
// TestFilterKeepsWhatKeepSays: the copy holds the commands keep accepted, and help.
|
||||
func TestFilterKeepsWhatKeepSays(t *testing.T) {
|
||||
ro := testRegistry().Filter(notWithheld, testReason)
|
||||
|
||||
names := make([]string, 0)
|
||||
for _, c := range ro.All() {
|
||||
names = append(names, string(c.Name))
|
||||
}
|
||||
|
||||
assert.ElementsMatch(t, []string{"help", "served"}, names)
|
||||
}
|
||||
|
||||
// TestRefusesWithheldByName covers a client that knows a command exists and asks for it
|
||||
// anyway. The filter lives on the serving side, so the answer must not depend on what
|
||||
// the client was told was available.
|
||||
func TestRefusesWithheldByName(t *testing.T) {
|
||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
w := Output{Out: out, Err: errOut}
|
||||
|
||||
err := testRegistry().Filter(notWithheld, testReason).DispatchArgs([]string{"withheld"}, w)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "withheld is not available on this surface")
|
||||
assert.Empty(t, out.String(), "a withheld command must produce no output")
|
||||
assert.Contains(t, errOut.String(), "withheld is not available on this surface")
|
||||
assert.Contains(t, errOut.String(), testReason,
|
||||
"the registry should render the explanation the filter supplied, not one of its own")
|
||||
}
|
||||
|
||||
// TestWithheldIsNotReportedAsUnknown keeps the two cases distinct: an operator who
|
||||
// mistypes and one who asked for a real command should not get the same answer.
|
||||
func TestWithheldIsNotReportedAsUnknown(t *testing.T) {
|
||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
err := testRegistry().Filter(notWithheld, testReason).DispatchArgs([]string{"no-such-command"}, Output{Out: out, Err: errOut})
|
||||
|
||||
var f *Failure
|
||||
require.ErrorAs(t, err, &f, "an unknown command is a failure to the surface")
|
||||
assert.Contains(t, out.String(), "did not understand: no-such-command")
|
||||
}
|
||||
|
||||
// TestResolveTellsUnknownFromWithheld: the two cases read differently to an operator,
|
||||
// and a surface with status codes tells them apart by the error's type, never by asking
|
||||
// the unfiltered registry, which is the one thing a filtered surface must not consult.
|
||||
func TestResolveTellsUnknownFromWithheld(t *testing.T) {
|
||||
r := testRegistry().Filter(notWithheld, testReason)
|
||||
|
||||
c, err := r.Resolve("served")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, Name("served"), c.Name)
|
||||
|
||||
_, err = r.Resolve("withheld")
|
||||
var withheld *WithheldError
|
||||
require.ErrorAs(t, err, &withheld)
|
||||
require.ErrorContains(t, err, "withheld is not available on this surface")
|
||||
require.ErrorContains(t, err, testReason)
|
||||
|
||||
_, err = r.Resolve("no-such-command")
|
||||
require.ErrorContains(t, err, `unknown command "no-such-command"`)
|
||||
assert.NotErrorAs(t, err, &withheld, "an unknown name is not a withheld one")
|
||||
}
|
||||
|
||||
// paramRegistry holds one command with a bool flag and a duration flag, and reports what
|
||||
// the command saw when it ran.
|
||||
func paramRegistry(t *testing.T) (*Registry, *[]paramsSeen) {
|
||||
t.Helper()
|
||||
|
||||
var seen []paramsSeen
|
||||
r := New()
|
||||
r.Register(&Command{
|
||||
Name: "set",
|
||||
ShortDescription: "sets things",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := paramsSeen{}
|
||||
fl.BoolVar(&s.Verbose, "verbose", false, "say more")
|
||||
fl.DurationVar(&s.Wait, "wait", 0, "how long")
|
||||
return fl, &s
|
||||
},
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
seen = append(seen, *fs.(*paramsSeen))
|
||||
return Value("ok"), nil
|
||||
},
|
||||
})
|
||||
|
||||
return r, &seen
|
||||
}
|
||||
|
||||
type paramsSeen struct {
|
||||
Verbose bool
|
||||
Wait time.Duration
|
||||
}
|
||||
|
||||
// TestInvokeReportsParametersInNameOrder: parameters arrive as an unordered object, so
|
||||
// with two bad ones the error must not depend on map iteration. Name order decides.
|
||||
func TestInvokeReportsParametersInNameOrder(t *testing.T) {
|
||||
r, _ := paramRegistry(t)
|
||||
|
||||
cases := map[string]struct {
|
||||
params map[string]string
|
||||
want string
|
||||
}{
|
||||
"two unknown": {map[string]string{"zed": "1", "alpha": "1"}, `set has no parameter "alpha"`},
|
||||
"unknown before bad bool": {map[string]string{"aaa": "1", "verbose": "maybe"}, `set has no parameter "aaa"`},
|
||||
"bad bool before unknown": {map[string]string{"verbose": "maybe", "zzz": "1"}, `verbose: expected a boolean, got "maybe"`},
|
||||
"bad value before bad bool": {map[string]string{"wait": "soon", "verbose": "maybe"}, `verbose: expected a boolean`},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
// Enough runs that a map-order dependence would show.
|
||||
for i := 0; i < 50; i++ {
|
||||
_, err := Invoke(Request{Command: r.Get("set"), Params: tc.params})
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestInvokeWithABadParameterSetsNothing: a request with any bad parameter must not run
|
||||
// the command, and must leave nothing behind for the next request to see. The good
|
||||
// parameter sorts before the bad one, so a one-pass Invoke would have applied it.
|
||||
func TestInvokeWithABadParameterSetsNothing(t *testing.T) {
|
||||
r, seen := paramRegistry(t)
|
||||
|
||||
_, err := Invoke(Request{Command: r.Get("set"), Params: map[string]string{"verbose": "true", "wait": "soon"}})
|
||||
require.ErrorContains(t, err, "wait:")
|
||||
assert.Empty(t, *seen, "the command must not run with a partial parameter set")
|
||||
|
||||
v, err := Invoke(Request{Command: r.Get("set")})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "ok", v.Value)
|
||||
require.Len(t, *seen, 1)
|
||||
assert.Equal(t, paramsSeen{}, (*seen)[0], "nothing from the failed request carried over")
|
||||
|
||||
_, err = Invoke(Request{Command: r.Get("set"), Params: map[string]string{"verbose": "true", "wait": "2s"}})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, *seen, 2)
|
||||
assert.Equal(t, paramsSeen{Verbose: true, Wait: 2 * time.Second}, (*seen)[1])
|
||||
}
|
||||
|
||||
func TestHelpListsOnlyServedCommands(t *testing.T) {
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, testRegistry().Filter(notWithheld, testReason).DispatchArgs(nil, MergedOutput(out)))
|
||||
|
||||
assert.Contains(t, out.String(), "served")
|
||||
assert.NotContains(t, out.String(), "withheld")
|
||||
}
|
||||
|
||||
// TestDispatchReportsUnparseableLine pins that a line shlex rejects says so on Err rather
|
||||
// than coming back silent, so an operator with an unbalanced quote learns the quote is the
|
||||
// problem instead of assuming the command is broken.
|
||||
func TestDispatchReportsUnparseableLine(t *testing.T) {
|
||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
testRegistry().Dispatch(`served "unterminated`, Output{Out: out, Err: errOut})
|
||||
assert.Empty(t, out.String())
|
||||
assert.Contains(t, errOut.String(), "could not parse the command line")
|
||||
}
|
||||
|
||||
// TestRegisterRejectsReservedFlags: a command that declares a reserved flag is refused
|
||||
// at Register rather than when an operator first runs it; see reservedFlags.
|
||||
func TestRegisterRejectsReservedFlags(t *testing.T) {
|
||||
for _, name := range []string{"json", "pretty", "h", "help", "config", "socket"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
r := New()
|
||||
assert.PanicsWithValue(t, "commands: clash declares reserved flag -"+name, func() {
|
||||
r.Register(&Command{
|
||||
Name: "clash",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("clash", flag.ContinueOnError)
|
||||
fl.Bool(name, false, "")
|
||||
return fl, nil
|
||||
},
|
||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryIsSafeForConcurrentUse runs the operations the surfaces perform, filtering
|
||||
// and cloning per request or session, against a stream of registrations. It exists to
|
||||
// be run under the race detector: the map underneath is not goroutine safe.
|
||||
func TestRegistryIsSafeForConcurrentUse(t *testing.T) {
|
||||
r := testRegistry()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 50; j++ {
|
||||
r.Register(&Command{
|
||||
Name: Name("late-" + strings.Repeat("a", i) + "-" + strings.Repeat("b", j)),
|
||||
ShortDescription: "registered after the surfaces started",
|
||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
||||
})
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 50; j++ {
|
||||
f := r.Filter(notWithheld, testReason)
|
||||
_ = f.Get("served")
|
||||
_ = f.Schema()
|
||||
_ = r.Clone().Match("late-")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
f := r.Filter(notWithheld, testReason)
|
||||
assert.Len(t, f.Match("late-"), 8*50, "every late registration is visible once the writers finish")
|
||||
}
|
||||
|
||||
// TestCloneHelpSeesCloneCommands: the ssh session registers logout on its clone, and
|
||||
// the source does not learn of it. Help on the clone answers for the clone, and -h on a
|
||||
// command prints what `help <name>` does, on a clone as on the source: both render
|
||||
// through WriteCommandHelp, and Clone rebinds help to the copy.
|
||||
func TestCloneHelpSeesCloneCommands(t *testing.T) {
|
||||
r := testRegistry()
|
||||
c := r.Clone()
|
||||
c.Register(&Command{
|
||||
Name: Logout,
|
||||
ShortDescription: "ends the session",
|
||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
||||
})
|
||||
assert.Nil(t, r.Get(Logout), "the source is not affected")
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, c.DispatchArgs([]string{"help"}, MergedOutput(out)))
|
||||
assert.Contains(t, out.String(), "logout")
|
||||
|
||||
for _, name := range []string{"logout", "served"} {
|
||||
flag := &bytes.Buffer{}
|
||||
c.Dispatch(name+" -h", MergedOutput(flag))
|
||||
cmd := &bytes.Buffer{}
|
||||
c.Dispatch("help "+name, MergedOutput(cmd))
|
||||
assert.Equal(t, cmd.String(), flag.String(), name)
|
||||
assert.Contains(t, flag.String(), name+" - ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestThenRunsAfterTheReply pins the order Then exists for: Run's line is on the writer
|
||||
// before the action begins, Then's Result follows it, and Then's outcome is the
|
||||
// command's.
|
||||
func TestThenRunsAfterTheReply(t *testing.T) {
|
||||
out := &bytes.Buffer{}
|
||||
seen := "never ran"
|
||||
outcome := Did("acted")
|
||||
|
||||
r := New()
|
||||
r.Register(&Command{
|
||||
Name: "act",
|
||||
ShortDescription: "replies, then acts",
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
return Did("about to act"), nil
|
||||
},
|
||||
Then: func() Result {
|
||||
seen = out.String()
|
||||
return outcome
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, r.DispatchArgs([]string{"act"}, MergedOutput(out)))
|
||||
assert.Equal(t, "about to act\n", seen, "the line was written before the action")
|
||||
assert.Equal(t, "about to act\nacted\n", out.String())
|
||||
|
||||
out.Reset()
|
||||
outcome = Failed("could not act")
|
||||
var f *Failure
|
||||
require.ErrorAs(t, r.DispatchArgs([]string{"act"}, MergedOutput(out)), &f)
|
||||
assert.Equal(t, "about to act\ncould not act\n", out.String())
|
||||
|
||||
// In JSON only the outcome travels: one document for the program that asked.
|
||||
out.Reset()
|
||||
require.ErrorAs(t, r.DispatchArgs([]string{"act", "-json"}, MergedOutput(out)), &f)
|
||||
assert.JSONEq(t, `{"ok":false,"reason":"could not act"}`, out.String())
|
||||
|
||||
// A Run that refused is the outcome; the action does not happen.
|
||||
ran := false
|
||||
r.Register(&Command{
|
||||
Name: "refuse",
|
||||
ShortDescription: "refuses, so never acts",
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
return Failed("not like that"), nil
|
||||
},
|
||||
Then: func() Result {
|
||||
ran = true
|
||||
return Did("acted anyway")
|
||||
},
|
||||
})
|
||||
out.Reset()
|
||||
require.ErrorAs(t, r.DispatchArgs([]string{"refuse"}, MergedOutput(out)), &f)
|
||||
assert.Equal(t, "not like that\n", out.String())
|
||||
assert.False(t, ran)
|
||||
out.Reset()
|
||||
require.ErrorAs(t, r.DispatchArgs([]string{"refuse", "-json"}, MergedOutput(out)), &f)
|
||||
assert.JSONEq(t, `{"ok":false,"reason":"not like that"}`, out.String())
|
||||
assert.False(t, ran)
|
||||
}
|
||||
|
||||
// TestWriteCommandHelpIsTheOneRendering pins the layout both `help <command>` on the
|
||||
// daemon and `-h` in the client print, so the two cannot drift apart again.
|
||||
func TestWriteCommandHelpIsTheOneRendering(t *testing.T) {
|
||||
cs := CommandSchema{
|
||||
Name: "change-remote",
|
||||
Short: "changes a remote",
|
||||
Help: "Give it an address.",
|
||||
Flags: []FlagSchema{
|
||||
{Name: "address", Usage: "the new remote", Default: "1.2.3.4:4242"},
|
||||
{Name: "by-index", Bool: true, Usage: "match by index"},
|
||||
{Name: "json", Bool: true, Usage: "outputs as json"},
|
||||
},
|
||||
}
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, WriteCommandHelp(cs, out))
|
||||
|
||||
assert.Equal(t, "change-remote - changes a remote\n"+
|
||||
" Give it an address.\n"+
|
||||
" -address string\n \tthe new remote (default 1.2.3.4:4242)\n"+
|
||||
" -by-index\n \tmatch by index\n"+
|
||||
" -json\n \toutputs as json\n", out.String())
|
||||
}
|
||||
|
||||
// addrFlags is the flag struct of a test command that takes -address.
|
||||
type addrFlags struct{ Address string }
|
||||
|
||||
// TestHelpFlagIsReadWhereParseReadsIt: -h asks for help only where the line's parser
|
||||
// reads it as a flag. As a flag's value or after -- it reaches the command as the
|
||||
// operand it is, and help is rendered by the same function `help <command>` uses.
|
||||
func TestHelpFlagIsReadWhereParseReadsIt(t *testing.T) {
|
||||
var seen []string
|
||||
r := New()
|
||||
r.Register(Flagged(&Command{Name: "x", ShortDescription: "takes an address"},
|
||||
func(fl *flag.FlagSet, s *addrFlags) { fl.StringVar(&s.Address, "address", "", "an address") },
|
||||
func(s *addrFlags, a []string) (Result, error) {
|
||||
seen = append(seen, s.Address+"|"+strings.Join(a, ","))
|
||||
return Nothing(), nil
|
||||
}))
|
||||
|
||||
for _, line := range []string{"x -h", "x -help", "x --help", "x 10.0.0.1 -h", "x -address=1 -h"} {
|
||||
out := &bytes.Buffer{}
|
||||
r.Dispatch(line, MergedOutput(out))
|
||||
assert.Contains(t, out.String(), "x - takes an address\n", line)
|
||||
assert.Contains(t, out.String(), "-address string", line)
|
||||
}
|
||||
assert.Empty(t, seen, "asking for help must not run the command")
|
||||
|
||||
for _, line := range []string{"x -address -h", "x -- -h"} {
|
||||
out := &bytes.Buffer{}
|
||||
r.Dispatch(line, MergedOutput(out))
|
||||
assert.Empty(t, out.String(), line)
|
||||
}
|
||||
assert.Equal(t, []string{"-h|", "|-h"}, seen)
|
||||
}
|
||||
|
||||
// TestBadFlagIsAnsweredWithTheCommandsHelp: a flag the command does not have is reported
|
||||
// on the error stream followed by the command's usage, in the rendering help uses.
|
||||
func TestBadFlagIsAnsweredWithTheCommandsHelp(t *testing.T) {
|
||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
r := New()
|
||||
r.Register(&Command{Name: "x", ShortDescription: "has no flags", Run: func(fs any, a []string) (Result, error) { return Nothing(), nil }})
|
||||
|
||||
require.Error(t, r.DispatchArgs([]string{"x", "-nope"}, Output{Out: out, Err: errOut}))
|
||||
assert.Empty(t, out.String())
|
||||
assert.Equal(t, "flag provided but not defined: -nope\nx - has no flags\n -json\n \toutputs as json\n -pretty\n \tpretty prints json, assumes -json\n", errOut.String())
|
||||
}
|
||||
|
||||
// TestParameterMistakesAreParamErrors: a surface with status codes needs to tell a
|
||||
// parameter the caller got wrong from a command that failed, and Invoke says which by
|
||||
// the error's type rather than its words.
|
||||
func TestParameterMistakesAreParamErrors(t *testing.T) {
|
||||
r := New()
|
||||
r.Register(&Command{
|
||||
Name: "flagged",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := struct{ N int }{}
|
||||
fl.IntVar(&s.N, "n", 0, "")
|
||||
return fl, &s
|
||||
},
|
||||
Run: func(fs any, a []string) (Result, error) { return Result{}, errors.New("ran and failed") },
|
||||
})
|
||||
r.Register(&Command{
|
||||
Name: "bare",
|
||||
Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
|
||||
})
|
||||
|
||||
var pe *ParamError
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
params map[string]string
|
||||
}{
|
||||
{"flagged", map[string]string{"nope": "1"}},
|
||||
{"flagged", map[string]string{"n": "x"}},
|
||||
{"flagged", map[string]string{FlagJSON: "true"}},
|
||||
{"bare", map[string]string{"n": "1"}},
|
||||
} {
|
||||
_, err := Invoke(Request{Command: r.Get(Name(tc.name)), Params: tc.params})
|
||||
require.Error(t, err, "%s %v", tc.name, tc.params)
|
||||
require.ErrorAs(t, err, &pe, "%s %v: %v", tc.name, tc.params, err)
|
||||
}
|
||||
|
||||
_, err := Invoke(Request{Command: r.Get("flagged"), Params: map[string]string{"n": "1"}})
|
||||
require.EqualError(t, err, "ran and failed")
|
||||
assert.NotErrorAs(t, err, &pe, "a Run error is the command's, not the caller's")
|
||||
}
|
||||
|
||||
// TestRunErrorIsShown: an error Run returns reaches the person at the prompt on the
|
||||
// error stream, as well as the surface that logs it.
|
||||
func TestRunErrorIsShown(t *testing.T) {
|
||||
r := New()
|
||||
r.Register(&Command{
|
||||
Name: "broken",
|
||||
ShortDescription: "cannot do what it is asked",
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
return Result{}, errors.New("no certificate is loaded")
|
||||
},
|
||||
})
|
||||
|
||||
out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
require.EqualError(t, r.DispatchArgs([]string{"broken"}, Output{Out: out, Err: errOut}), "no certificate is loaded")
|
||||
assert.Empty(t, out.String())
|
||||
assert.Equal(t, "no certificate is loaded\n", errOut.String())
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// ErrNoTextRendering is returned by Render when a command's Value has no human rendering
|
||||
// and text was asked for anyway. A command declares this by leaving Text nil and saying
|
||||
// so with JSONOnly; it is not a fallback situation but a statement that no such form
|
||||
// exists yet, so nobody builds a script around an interim one. Each surface's default
|
||||
// policy avoids ever asking.
|
||||
var ErrNoTextRendering = errors.New("no human readable output yet; pass -json or -pretty")
|
||||
|
||||
// Format is how a result should be presented.
|
||||
type Format int
|
||||
|
||||
const (
|
||||
// FormatUnset is a request that expressed no preference. A surface resolves it with
|
||||
// its own default before rendering; Render itself treats it as FormatText.
|
||||
FormatUnset Format = iota
|
||||
|
||||
// FormatText renders for a person. It is what an operator gets by default on every
|
||||
// surface with a human at the other end.
|
||||
FormatText
|
||||
|
||||
// FormatJSON renders the result as compact JSON.
|
||||
FormatJSON
|
||||
|
||||
// FormatPrettyJSON renders the result as indented JSON.
|
||||
FormatPrettyJSON
|
||||
)
|
||||
|
||||
// Flag names for the two presentation flags. They are offered on every command rather
|
||||
// than declared by each one, because how a result is displayed is not a property of the
|
||||
// command that produced it.
|
||||
const (
|
||||
FlagJSON = "json"
|
||||
FlagPretty = "pretty"
|
||||
)
|
||||
|
||||
// Flag names nebula ctl takes for itself, anywhere on its line, to say which daemon to
|
||||
// talk to; see reservedFlags.
|
||||
const (
|
||||
FlagConfig = "config"
|
||||
FlagSocket = "socket"
|
||||
)
|
||||
|
||||
// reservedFlags are handled before a command's Run is called, so a command may not
|
||||
// declare them itself. -h and -help are intercepted as a request for usage; -json and
|
||||
// -pretty are added to every command's FlagSet by commandFlags, on every surface, so a
|
||||
// command that defined either would make that definition panic with "flag redefined"
|
||||
// on whichever goroutine ran the command; and -config and -socket are nebula ctl's own,
|
||||
// taken off the line before the client knows which command it names, so a command
|
||||
// that declared either would never receive it there.
|
||||
var reservedFlags = []string{"h", "help", FlagJSON, FlagPretty, FlagConfig, FlagSocket}
|
||||
|
||||
// Render writes r in the requested format. Every surface calls it, so a hostmap looks
|
||||
// the same over ssh as it does through the control socket, and a change to either
|
||||
// rendering happens once.
|
||||
func Render(c *Command, r Result, f Format, w io.Writer) error {
|
||||
switch f {
|
||||
case FormatJSON:
|
||||
return renderJSON(r.Payload(), w, false)
|
||||
|
||||
case FormatPrettyJSON:
|
||||
return renderJSON(r.Payload(), w, true)
|
||||
|
||||
default:
|
||||
// An outcome reads the same for every command: its reason, as a sentence. Only a
|
||||
// Value needs the command's own rendering, so Text never sees anything else.
|
||||
if r.Value == nil {
|
||||
_, err := io.WriteString(w, r.Reason+"\n")
|
||||
return err
|
||||
}
|
||||
|
||||
if c != nil && c.Text != nil {
|
||||
return c.Text(r.Value, w)
|
||||
}
|
||||
|
||||
name := "this command"
|
||||
if c != nil {
|
||||
name = string(c.Name)
|
||||
}
|
||||
return fmt.Errorf("%s has %w", name, ErrNoTextRendering)
|
||||
}
|
||||
}
|
||||
|
||||
func renderJSON(v any, w io.Writer, indent bool) error {
|
||||
enc := json.NewEncoder(w)
|
||||
if indent {
|
||||
enc.SetIndent("", " ")
|
||||
}
|
||||
|
||||
return enc.Encode(v)
|
||||
}
|
||||
|
||||
// Result is what every Run returns: whether the command worked, a sentence saying so,
|
||||
// and, for a command that reports rather than acts, the value it produced.
|
||||
//
|
||||
// Value and Reason are alternatives. A command that reports returns Value(v), and the
|
||||
// surfaces render v, as JSON or through the command's Text. A command that acts, or any
|
||||
// command refusing its arguments, returns Did or Failed, and the surfaces render the
|
||||
// Outcome: its Reason is the sentence these commands have always printed. Nothing is for
|
||||
// a command with nothing to say.
|
||||
//
|
||||
// The envelope itself never reaches a caller. Payload is what JSON carries, and Render
|
||||
// hands Text only the Value, so a command's renderer sees the one type it returns on
|
||||
// success and is never asked to recognise an Outcome.
|
||||
type Result struct {
|
||||
Outcome
|
||||
Value any
|
||||
|
||||
// NotFound marks a refusal that is about the thing asked for rather than the asking:
|
||||
// a vpn address with no tunnel behind it, as opposed to one that would not parse. It
|
||||
// renders exactly as any other refusal, and never reaches the wire; the distinction
|
||||
// is for a surface whose protocol has a word for it, so an HTTP client is told 404
|
||||
// rather than 400 and never has to parse the sentence.
|
||||
NotFound bool
|
||||
}
|
||||
|
||||
// Outcome is the part of a Result that says whether the command worked and, in words a
|
||||
// caller can show someone, why. It is what a program receives from a command that acts
|
||||
// rather than reports: closing a tunnel, changing a remote, reloading config.
|
||||
//
|
||||
// One shape serves all of them. Designing a payload per outcome would be work without a
|
||||
// reader. Reason is set either way, so a success says what it did rather than leaving
|
||||
// the caller to infer it from a bare true.
|
||||
type Outcome struct {
|
||||
OK bool `json:"ok"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// Value is the Result of a command that reports: v is what it has to show, and it must
|
||||
// marshal to JSON.
|
||||
func Value(v any) Result {
|
||||
return Result{Outcome: Outcome{OK: true}, Value: v}
|
||||
}
|
||||
|
||||
// Failed is a convenience for the common "it did not work, here is why" case.
|
||||
func Failed(format string, args ...any) Result {
|
||||
return Result{Outcome: Outcome{Reason: fmt.Sprintf(format, args...)}}
|
||||
}
|
||||
|
||||
// NotFound is Failed for a command asked about something that does not exist. See
|
||||
// Result.NotFound.
|
||||
func NotFound(format string, args ...any) Result {
|
||||
r := Failed(format, args...)
|
||||
r.NotFound = true
|
||||
return r
|
||||
}
|
||||
|
||||
// Did is a convenience for the common "it worked, here is what happened" case.
|
||||
func Did(format string, args ...any) Result {
|
||||
return Result{Outcome: Outcome{OK: true, Reason: fmt.Sprintf(format, args...)}}
|
||||
}
|
||||
|
||||
// Nothing is the Result of a command with nothing to say: it did its work, and the
|
||||
// surface sends an empty, successful reply without rendering anything.
|
||||
func Nothing() Result {
|
||||
return Result{Outcome: Outcome{OK: true}}
|
||||
}
|
||||
|
||||
// Empty reports a Result with nothing to render: no Value and no Reason. The zero Result
|
||||
// counts, so a Run that returns Result{} says nothing rather than failing silently.
|
||||
func (r Result) Empty() bool {
|
||||
return r.Value == nil && r.Reason == ""
|
||||
}
|
||||
|
||||
// Payload is what a program receives: the Value when there is one, otherwise the
|
||||
// Outcome. No surface sends the envelope itself, so print-tunnel -json emits the tunnel
|
||||
// and close-tunnel -json emits {ok, reason}.
|
||||
func (r Result) Payload() any {
|
||||
if r.Value != nil {
|
||||
return r.Value
|
||||
}
|
||||
return r.Outcome
|
||||
}
|
||||
|
||||
// Typed adapts a renderer for one result type to the TextFunc a Command declares. The
|
||||
// value Render passes is the command's own, see Result, so all that is left is to name
|
||||
// its type once here instead of asserting it at the top of every renderer. A renderer
|
||||
// paired with a command that returns something else fails here, saying what arrived.
|
||||
func Typed[T any](render func(T, io.Writer) error) TextFunc {
|
||||
return func(v any, w io.Writer) error {
|
||||
t, ok := v.(T)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected %T, got %T", t, v)
|
||||
}
|
||||
return render(t, w)
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestRenderPrintsAnOutcomeWithoutText: a command that acts declares no Text. Its
|
||||
// outcome renders as the reason, the same for every command, and as {ok, reason} in
|
||||
// JSON, which is the shape these commands have always emitted.
|
||||
func TestRenderPrintsAnOutcomeWithoutText(t *testing.T) {
|
||||
c := &Command{Name: "act"}
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, Render(c, Did("Closed"), FormatText, out))
|
||||
assert.Equal(t, "Closed\n", out.String())
|
||||
|
||||
out.Reset()
|
||||
require.NoError(t, Render(c, Failed("No vpn address was provided"), FormatText, out))
|
||||
assert.Equal(t, "No vpn address was provided\n", out.String())
|
||||
|
||||
out.Reset()
|
||||
require.NoError(t, Render(c, Failed("nope"), FormatJSON, out))
|
||||
assert.JSONEq(t, `{"ok":false,"reason":"nope"}`, out.String())
|
||||
}
|
||||
|
||||
// TestRenderHandsTextOnlyTheValue pins the guarantee Result exists for: a command's
|
||||
// renderer sees the type it returns on success and never the envelope or an outcome, so
|
||||
// a report command that refuses its arguments needs nothing in its Text to cope.
|
||||
func TestRenderHandsTextOnlyTheValue(t *testing.T) {
|
||||
var got any
|
||||
c := &Command{
|
||||
Name: "report",
|
||||
Text: func(v any, w io.Writer) error {
|
||||
got = v
|
||||
_, err := io.WriteString(w, "rendered\n")
|
||||
return err
|
||||
},
|
||||
}
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, Render(c, Value("data"), FormatText, out))
|
||||
assert.Equal(t, "data", got)
|
||||
assert.Equal(t, "rendered\n", out.String())
|
||||
|
||||
got, out = nil, &bytes.Buffer{}
|
||||
require.NoError(t, Render(c, Failed("refused"), FormatText, out))
|
||||
assert.Nil(t, got, "Text must not be called for an outcome")
|
||||
assert.Equal(t, "refused\n", out.String())
|
||||
|
||||
out.Reset()
|
||||
require.NoError(t, Render(c, Value("data"), FormatJSON, out))
|
||||
assert.JSONEq(t, `"data"`, out.String(), "JSON carries the value, never the envelope")
|
||||
}
|
||||
|
||||
// TestRenderRefusesTextForAValueWithoutText: leaving Text nil is a statement that no
|
||||
// human form of the value exists yet, and asking for one is an error that says so.
|
||||
func TestRenderRefusesTextForAValueWithoutText(t *testing.T) {
|
||||
out := &bytes.Buffer{}
|
||||
err := Render(&Command{Name: "print-tunnel"}, Value(map[string]int{"index": 7}), FormatText, out)
|
||||
require.ErrorIs(t, err, ErrNoTextRendering)
|
||||
require.ErrorContains(t, err, "print-tunnel has no human readable output yet")
|
||||
assert.Empty(t, out.String())
|
||||
}
|
||||
|
||||
// TestTypedNamesTheTypeOnce: Typed replaces the assertion at the top of every renderer.
|
||||
// The right type reaches the renderer; the wrong one is reported, naming both.
|
||||
func TestTypedNamesTheTypeOnce(t *testing.T) {
|
||||
type info struct{ Name string }
|
||||
render := Typed(func(i info, w io.Writer) error {
|
||||
_, err := io.WriteString(w, i.Name+"\n")
|
||||
return err
|
||||
})
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, render(info{Name: "tun0"}, out))
|
||||
assert.Equal(t, "tun0\n", out.String())
|
||||
|
||||
err := render("not an info", out)
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "expected commands.info, got string")
|
||||
}
|
||||
|
||||
// TestResultShapes pins what each constructor means to a surface: Empty is the one that
|
||||
// renders nothing, Payload is what a program receives, and OK is set wherever a reason
|
||||
// or value says the command worked.
|
||||
func TestResultShapes(t *testing.T) {
|
||||
assert.True(t, Nothing().Empty())
|
||||
assert.True(t, Result{}.Empty(), "the zero Result says nothing rather than failing silently")
|
||||
assert.False(t, Did("done").Empty())
|
||||
assert.False(t, Failed("no").Empty())
|
||||
assert.False(t, Value("x").Empty())
|
||||
|
||||
assert.True(t, Value("x").OK)
|
||||
assert.True(t, Did("done").OK)
|
||||
assert.False(t, Failed("no").OK)
|
||||
|
||||
assert.Equal(t, "x", Value("x").Payload())
|
||||
assert.Equal(t, Outcome{OK: true, Reason: "done"}, Did("done").Payload())
|
||||
assert.Equal(t, Outcome{Reason: "no"}, Failed("no").Payload())
|
||||
}
|
||||
|
||||
// TestNotFoundIsARefusalLikeAnyOther: NotFound renders and marshals exactly as Failed
|
||||
// does, so no surface's output changes by a command adopting it. The mark is on the
|
||||
// Result alone, for a surface whose protocol has a word for it.
|
||||
func TestNotFoundIsARefusalLikeAnyOther(t *testing.T) {
|
||||
r := NotFound("No active tunnel for vpn addr: %s", "10.0.0.5")
|
||||
assert.False(t, r.OK)
|
||||
assert.True(t, r.NotFound)
|
||||
assert.False(t, Failed("nope").NotFound)
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, Render(&Command{Name: "look"}, r, FormatText, out))
|
||||
assert.Equal(t, "No active tunnel for vpn addr: 10.0.0.5\n", out.String())
|
||||
|
||||
out.Reset()
|
||||
require.NoError(t, Render(&Command{Name: "look"}, r, FormatJSON, out))
|
||||
assert.JSONEq(t, `{"ok":false,"reason":"No active tunnel for vpn addr: 10.0.0.5"}`, out.String(), "the mark never reaches the wire")
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"maps"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// Request is one command to run, as every surface hands it to Invoke: the command, its
|
||||
// options by name in the form their flags parse, its operands, and the rendering the
|
||||
// line asked for, if any.
|
||||
//
|
||||
// nebula ctl builds one with ParseLine and it travels as a JSON object to the control
|
||||
// socket. An ssh line never becomes one: it is parsed straight into the command's own
|
||||
// FlagSet; see execLine.
|
||||
type Request struct {
|
||||
// Command is the command to run, resolved by the surface at its edge. See
|
||||
// Registry.Resolve for the one that tells an unknown name from a withheld one.
|
||||
Command *Command
|
||||
|
||||
// Params carries the options the line set, by flag name, each in the form its flag
|
||||
// parses from. An option left alone is absent, so the command's default applies.
|
||||
Params map[string]string
|
||||
|
||||
// Args carries the operands: whatever the line did not consume as a flag.
|
||||
Args []string
|
||||
|
||||
// Format is the rendering the line asked for with -json or -pretty, or FormatUnset
|
||||
// when it expressed no preference. It is ParseLine's reading of the line for the
|
||||
// client that sends the Request; Invoke does not read it, since the surface that
|
||||
// runs a Request renders with the format it agreed with its caller.
|
||||
Format Format
|
||||
}
|
||||
|
||||
// ParseLine reads a FlagSet that ParseArgs has filled, and the operands it returned,
|
||||
// into a Request to send over the wire. Command is left for the caller to set.
|
||||
//
|
||||
// Every flag the line set other than the presentation flags travels by name, as its
|
||||
// flag's String, which is what the daemon's Set parses. That round trip is exact for
|
||||
// the bool and string flags a client builds from the schema; it is the client's to make,
|
||||
// and the ssh path does not make it, since it runs the FlagSet it parsed.
|
||||
func ParseLine(fl *flag.FlagSet, operands []string) Request {
|
||||
req := Request{Args: operands, Format: presentationFormat(fl)}
|
||||
|
||||
fl.Visit(func(f *flag.Flag) {
|
||||
if isPresentationFlag(f.Name) {
|
||||
return
|
||||
}
|
||||
if req.Params == nil {
|
||||
req.Params = map[string]string{}
|
||||
}
|
||||
req.Params[f.Name] = f.Value.String()
|
||||
})
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
// presentationFormat is the one reading of -json and -pretty from a parsed line, so a
|
||||
// line means the same on every surface: only a flag set to true asks for JSON, since one
|
||||
// set to false expresses no preference, and -pretty implies -json. FormatUnset means the
|
||||
// line expressed no preference and the surface's own default applies.
|
||||
func presentationFormat(fl *flag.FlagSet) Format {
|
||||
var asJSON, pretty bool
|
||||
fl.Visit(func(f *flag.Flag) {
|
||||
switch f.Name {
|
||||
case FlagJSON:
|
||||
asJSON = flagIsTrue(f)
|
||||
case FlagPretty:
|
||||
pretty = flagIsTrue(f)
|
||||
}
|
||||
})
|
||||
|
||||
switch {
|
||||
case pretty:
|
||||
return FormatPrettyJSON
|
||||
case asJSON:
|
||||
return FormatJSON
|
||||
default:
|
||||
return FormatUnset
|
||||
}
|
||||
}
|
||||
|
||||
// PresentationFormat is presentationFormat for a surface that takes a command's options
|
||||
// by name rather than from a line: the info API's query string. Only the two presentation
|
||||
// flags are read from params; the command's own parameters are the caller's to pass to
|
||||
// Invoke, which refuses these two among them. A flag given with no value counts as set,
|
||||
// as -pretty does on a line, and one that is not a boolean is a ParamError.
|
||||
func PresentationFormat(params map[string]string) (Format, error) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
addPresentationFlags(fl)
|
||||
|
||||
for _, k := range []string{FlagJSON, FlagPretty} {
|
||||
v, ok := params[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if v == "" {
|
||||
v = "true"
|
||||
}
|
||||
if err := setFlag(fl, fl.Lookup(k), v); err != nil {
|
||||
return FormatUnset, err
|
||||
}
|
||||
}
|
||||
|
||||
return presentationFormat(fl), nil
|
||||
}
|
||||
|
||||
// flagIsTrue reports whether a bool flag was set to true. The flag package's bool value
|
||||
// is a flag.Getter whose Get returns the bool, so this never falls back to parsing text.
|
||||
func flagIsTrue(f *flag.Flag) bool {
|
||||
g, ok := f.Value.(flag.Getter)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
b, _ := g.Get().(bool)
|
||||
return b
|
||||
}
|
||||
|
||||
// Invoke runs one Request and returns the command's Result, unrendered.
|
||||
//
|
||||
// The parameters are applied by flag name, in name order: a request from the wire is a
|
||||
// JSON object with no order of its own, and which of two bad parameters is reported must
|
||||
// not change from one request to the next. An unknown parameter is an error rather than
|
||||
// something quietly ignored, because a caller that misspells one deserves to hear about
|
||||
// it instead of getting a default. A bad parameter means Run is never called, and the
|
||||
// FlagSet is fresh for this call, so nothing set before it is seen by anyone.
|
||||
//
|
||||
// Nothing here writes anywhere and nothing here renders. What a surface does with the
|
||||
// Result, marshal its Payload or run the command's own text rendering through Render,
|
||||
// is the surface's decision, and keeping that out of here is what lets a caller tell a
|
||||
// refusal from a success after the text has been produced. The presentation flags are
|
||||
// not parameters: a Request says how it wants rendering in Format, and sending them as
|
||||
// parameters is refused rather than read as a preference.
|
||||
func Invoke(req Request) (Result, error) {
|
||||
c := req.Command
|
||||
|
||||
fl, fs, own := commandFlags(c)
|
||||
if err := setParams(fl, string(c.Name), slices.Sorted(maps.Keys(req.Params)), req.Params, own); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
return c.Run(fs, req.Args)
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func lineFlags() *flag.FlagSet {
|
||||
fl := flag.NewFlagSet("set", flag.ContinueOnError)
|
||||
fl.Bool("verbose", false, "")
|
||||
fl.Duration("wait", 0, "")
|
||||
fl.String("label", "none", "")
|
||||
fl.Bool(FlagJSON, false, "")
|
||||
fl.Bool(FlagPretty, false, "")
|
||||
return fl
|
||||
}
|
||||
|
||||
// TestParseLineReadsThePresentationFlagsOnce: presentationFormat is the one reading of
|
||||
// -json and -pretty, for every surface, and ParseLine carries its answer. A flag set to
|
||||
// false expresses no preference, and neither flag ever travels as a parameter.
|
||||
func TestParseLineReadsThePresentationFlagsOnce(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
want Format
|
||||
}{
|
||||
{nil, FormatUnset},
|
||||
{[]string{"-json=false"}, FormatUnset},
|
||||
{[]string{"-pretty=false"}, FormatUnset},
|
||||
{[]string{"-json"}, FormatJSON},
|
||||
{[]string{"-pretty"}, FormatPrettyJSON},
|
||||
{[]string{"-pretty", "-json=false"}, FormatPrettyJSON},
|
||||
} {
|
||||
fl := lineFlags()
|
||||
operands, err := ParseArgs(fl, tc.args)
|
||||
require.NoError(t, err)
|
||||
|
||||
req := ParseLine(fl, operands)
|
||||
assert.Equal(t, tc.want, req.Format, "%v", tc.args)
|
||||
assert.Nil(t, req.Params, "%v: presentation flags are not parameters", tc.args)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseLineCarriesWhatWasSetInParseableForm: only the flags the line set travel,
|
||||
// each as the string its flag parses from, so the daemon's Invoke can apply them to a
|
||||
// fresh FlagSet and get the same values back. Operands come through untouched, those
|
||||
// after "--" included.
|
||||
func TestParseLineCarriesWhatWasSetInParseableForm(t *testing.T) {
|
||||
fl := lineFlags()
|
||||
operands, err := ParseArgs(fl, []string{"-verbose", "-wait", "2s", "x", "--", "-1"})
|
||||
require.NoError(t, err)
|
||||
|
||||
req := ParseLine(fl, operands)
|
||||
assert.Equal(t, map[string]string{"verbose": "true", "wait": "2s"}, req.Params, "label was left alone and must be absent")
|
||||
assert.Equal(t, []string{"x", "-1"}, req.Args)
|
||||
assert.Equal(t, FormatUnset, req.Format)
|
||||
|
||||
// The round trip a client makes: what ParseLine produced is what Invoke applies.
|
||||
r, seen := paramRegistry(t)
|
||||
req.Command = r.Get("set")
|
||||
_, err = Invoke(req)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, *seen, 1)
|
||||
assert.Equal(t, paramsSeen{Verbose: true, Wait: 2 * time.Second}, (*seen)[0])
|
||||
}
|
||||
|
||||
// TestLineRunsTheFlagSetItParsed: the ssh path hands Run the FlagSet the line was parsed
|
||||
// into, with no trip through a Request. A flag.Func has no String worth re-parsing, so a
|
||||
// round trip would hand Run an empty value and no error; the line's value must arrive.
|
||||
func TestLineRunsTheFlagSetItParsed(t *testing.T) {
|
||||
var seen []string
|
||||
r := New()
|
||||
r.Register(&Command{
|
||||
Name: "mode",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := new(string)
|
||||
fl.Func("mode", "the mode", func(v string) error {
|
||||
*s = "set:" + v
|
||||
return nil
|
||||
})
|
||||
return fl, s
|
||||
},
|
||||
Run: func(fs any, a []string) (Result, error) {
|
||||
seen = append(seen, *fs.(*string))
|
||||
return Value("ok"), nil
|
||||
},
|
||||
})
|
||||
|
||||
var out, errw strings.Builder
|
||||
r.Dispatch("mode -json -mode fast", Output{Out: &out, Err: &errw})
|
||||
require.Equal(t, []string{"set:fast"}, seen)
|
||||
assert.Empty(t, errw.String())
|
||||
assert.Equal(t, "\"ok\"\n", out.String(), "-json was read from the same FlagSet")
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package commands
|
||||
|
||||
import "io"
|
||||
|
||||
// Output is where a command line surface's text goes.
|
||||
//
|
||||
// Out and Err are distinct so a command's primary output can stay machine readable on
|
||||
// a surface that separates the two. The ssh surface points both at the same channel and
|
||||
// sees a single merged stream. The local
|
||||
// control socket does not use one at all: it invokes by named parameter and carries the
|
||||
// returned value, so there is no stream for a command to write to.
|
||||
type Output struct {
|
||||
// Out receives what a command produces.
|
||||
Out io.Writer
|
||||
|
||||
// Err receives usage text, refusals and errors.
|
||||
Err io.Writer
|
||||
}
|
||||
|
||||
// MergedOutput sends output and errors to the same writer.
|
||||
func MergedOutput(w io.Writer) Output {
|
||||
return Output{Out: w, Err: w}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLogFormatRefusalIsShown: a format the logger does not know is a refusal the user
|
||||
// sees, rather than a bare error, which over ssh was silence.
|
||||
func TestLogFormatRefusalIsShown(t *testing.T) {
|
||||
l := logging.NewLogger(io.Discard)
|
||||
|
||||
res, err := runLogFormat(l, []string{"bogus"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, res.OK)
|
||||
assert.Equal(t, "Unable to set log format: unknown log format `bogus`. possible formats: [text json]", res.Reason)
|
||||
|
||||
res, err = runLogFormat(l, []string{"JSON"})
|
||||
require.NoError(t, err)
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, commands.Typed(textLogFormat)(res.Value, out))
|
||||
assert.Equal(t, "Log format is: json\n", out.String())
|
||||
}
|
||||
|
||||
// TestPrintRelaysReportsErrorsAsText: the Error field was an error value, which encodes
|
||||
// as {} and lost the message. It is the message now, and absent when there is none.
|
||||
func TestPrintRelaysReportsErrorsAsText(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
hm := newHostMap(l)
|
||||
relay := netip.MustParseAddr("10.0.0.1")
|
||||
peer := netip.MustParseAddr("10.0.0.2")
|
||||
|
||||
// A relay host that is in Relays but not in Hosts, so its hostinfo cannot be found.
|
||||
hm.Relays[1] = &HostInfo{vpnAddrs: []netip.Addr{relay}}
|
||||
ifce := &Interface{hostMap: hm}
|
||||
|
||||
marshal := func() string {
|
||||
b, err := json.Marshal(runPrintRelays(ifce))
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
assert.JSONEq(t, `{"Relays":[{"NebulaAddr":"10.0.0.1","RelayForAddrs":[{"Error":"could not find hostinfo","Type":"","State":"","PeerAddr":"","LocalIndex":0,"RemoteIndex":0,"RelayedThrough":null}]}]}`, marshal())
|
||||
|
||||
// The same relay host, found, relaying for a peer whose index matches: no Error key.
|
||||
hi := hm.Relays[1]
|
||||
r := &Relay{Type: ForwardingType, State: Established, PeerAddr: peer, LocalIndex: 1, RemoteIndex: 2}
|
||||
hi.relayState = RelayState{
|
||||
relayForByAddr: map[netip.Addr]*Relay{peer: r},
|
||||
relayForByIdx: map[uint32]*Relay{r.LocalIndex: r},
|
||||
}
|
||||
hm.Hosts[relay] = hi
|
||||
assert.JSONEq(t, `{"Relays":[{"NebulaAddr":"10.0.0.1","RelayForAddrs":[{"Type":"forwarding","State":"established","PeerAddr":"10.0.0.2","LocalIndex":1,"RemoteIndex":2,"RelayedThrough":null}]}]}`, marshal())
|
||||
|
||||
// And an index mismatch names it.
|
||||
hm.Relays[7] = hi
|
||||
delete(hm.Relays, 1)
|
||||
assert.Contains(t, marshal(), `"Error":"hostmap LocalIndex '7' does not match RelayState LocalIndex"`)
|
||||
}
|
||||
|
||||
// TestPrintCertOfATunnelWithoutACertificate: a tunnel still handshaking, or one being
|
||||
// torn down, has no certificate, and print-cert refuses rather than panicking.
|
||||
func TestPrintCertOfATunnelWithoutACertificate(t *testing.T) {
|
||||
f, _ := identityFixture(t)
|
||||
|
||||
r, err := runPrintCert(f, &printCertFlags{}, []string{"10.0.0.3"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.OK)
|
||||
assert.Equal(t, "Could not find tunnel for vpn addr: 10.0.0.3", r.Reason)
|
||||
|
||||
r, err = runPrintCert(f, &printCertFlags{}, []string{"10.0.0.2"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.OK, "a tunnel with a certificate is printed")
|
||||
}
|
||||
|
||||
// TestPrintCertByAddressFlag: -address is the info API's spelling of the operand, takes a
|
||||
// port and a 4in6 form the way identity does, answers our own address with our own
|
||||
// certificate, and is refused together with an operand.
|
||||
func TestPrintCertByAddressFlag(t *testing.T) {
|
||||
f, peerCert := identityFixture(t)
|
||||
|
||||
for _, addr := range []string{"10.0.0.2", "10.0.0.2:4242", "[::ffff:10.0.0.2]:4242"} {
|
||||
fl := &printCertFlags{}
|
||||
require.NoError(t, fl.setAddress(addr))
|
||||
r, err := runPrintCert(f, fl, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, r.OK, addr)
|
||||
assert.Equal(t, peerCert, r.Value, addr)
|
||||
}
|
||||
|
||||
fl := &printCertFlags{}
|
||||
require.NoError(t, fl.setAddress("10.0.0.1"))
|
||||
r, err := runPrintCert(f, fl, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, r.OK)
|
||||
assert.Equal(t, ownCertificate(f.pki.getCertState()), r.Value, "our own address is our own certificate")
|
||||
|
||||
fl = &printCertFlags{}
|
||||
require.NoError(t, fl.setAddress("10.0.0.3"))
|
||||
r, err = runPrintCert(f, fl, nil)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.OK)
|
||||
assert.True(t, r.NotFound)
|
||||
|
||||
fl = &printCertFlags{}
|
||||
require.NoError(t, fl.setAddress("not-an-address"))
|
||||
r, err = runPrintCert(f, fl, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "The provided vpn addr could not be parsed: not-an-address", r.Reason)
|
||||
|
||||
fl = &printCertFlags{}
|
||||
require.NoError(t, fl.setAddress("10.0.0.2"))
|
||||
r, err = runPrintCert(f, fl, []string{"10.0.0.2"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "print-cert takes one vpn addr, as -address or as an operand, not both", r.Reason)
|
||||
}
|
||||
|
||||
// TestPrintCertPrefersOwnV2: with no address print-cert reports the certificate whoami
|
||||
// does, the v2 when both versions are loaded, rather than the one handshakes start with.
|
||||
func TestPrintCertPrefersOwnV2(t *testing.T) {
|
||||
v4 := netip.MustParsePrefix("10.0.0.1/24")
|
||||
ca1, _, caKey1, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
v1, _, _, _ := cert_test.NewTestCert(cert.Version1, cert.Curve_CURVE25519, ca1, caKey1, "me", time.Time{}, time.Time{}, []netip.Prefix{v4}, nil, nil)
|
||||
ca2, _, caKey2, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
v2, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca2, caKey2, "me", time.Time{}, time.Time{}, []netip.Prefix{v4}, nil, nil)
|
||||
|
||||
f := &Interface{pki: &PKI{}, hostMap: newHostMap(test.NewLogger())}
|
||||
f.pki.cs.Store(&CertState{v1Cert: v1, v2Cert: v2, initiatingVersion: cert.Version1})
|
||||
|
||||
r, err := runPrintCert(f, &printCertFlags{}, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, r.OK)
|
||||
assert.Equal(t, v2, r.Value)
|
||||
}
|
||||
+23
-65
@@ -26,17 +26,9 @@ type C struct {
|
||||
files []string
|
||||
Settings map[string]any
|
||||
oldSettings map[string]any
|
||||
callbacks []func(*C, *Reload)
|
||||
callbacks []func(*C)
|
||||
l *slog.Logger
|
||||
reloadLock sync.Mutex
|
||||
|
||||
// Set by the first reload that needs a restart and never cleared. Guarded by reloadLock
|
||||
needsRestart bool
|
||||
|
||||
// callbackLock guards callbacks. Registration is not confined to startup: CatchHUP is
|
||||
// running from inside Main, and anything wired up after Main returns registers while
|
||||
// a HUP could already be reloading, so append and iteration have to be serialized.
|
||||
callbackLock sync.Mutex
|
||||
}
|
||||
|
||||
func NewC(l *slog.Logger) *C {
|
||||
@@ -80,45 +72,16 @@ func (c *C) LoadString(raw string) error {
|
||||
// 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
|
||||
// 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.
|
||||
// Use r to report anything that failed or needs a restart to apply.
|
||||
func (c *C) RegisterReloadCallback(f func(c *C, r *Reload)) {
|
||||
c.callbackLock.Lock()
|
||||
defer c.callbackLock.Unlock()
|
||||
// These functions should return quickly or spawn their own go routine if they will take a while
|
||||
func (c *C) RegisterReloadCallback(f func(*C)) {
|
||||
c.callbacks = append(c.callbacks, f)
|
||||
}
|
||||
|
||||
// reloadCallbacks returns a snapshot of the registered callbacks. Reloads iterate the
|
||||
// snapshot rather than the live slice, so a registration from another goroutine cannot
|
||||
// race the loop; a callback registered while a reload is in progress runs from the next
|
||||
// reload on. callbackLock is not held during the calls themselves, so a callback that
|
||||
// registers another callback does not deadlock.
|
||||
func (c *C) reloadCallbacks() []func(*C, *Reload) {
|
||||
c.callbackLock.Lock()
|
||||
defer c.callbackLock.Unlock()
|
||||
return append(make([]func(*C, *Reload), 0, len(c.callbacks)), c.callbacks...)
|
||||
}
|
||||
|
||||
// InitialLoad returns true if this is the first load of the config, and ReloadConfig has not been called yet.
|
||||
func (c *C) InitialLoad() bool {
|
||||
return c.oldSettings == nil
|
||||
}
|
||||
|
||||
// Render returns keys and their values as yaml, for a subsystem to remember what it applied. Empty means they couldn't
|
||||
// be rendered and should never match.
|
||||
func (c *C) Render(keys ...string) string {
|
||||
m := make(map[string]any, len(keys))
|
||||
for _, k := range keys {
|
||||
m[k] = c.Get(k)
|
||||
}
|
||||
b, err := yaml.Marshal(m)
|
||||
if err != nil {
|
||||
c.l.Debug("Failed to render config", "keys", keys, "error", err)
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
|
||||
// k in both the old and new settings will be serialized, the result of the string comparison is returned.
|
||||
// If k is an empty string the entire config is tested.
|
||||
@@ -181,55 +144,50 @@ func (c *C) CatchHUP(ctx context.Context) {
|
||||
return
|
||||
case <-ch:
|
||||
c.l.Info("Caught HUP, reloading config")
|
||||
c.ReloadConfig().Log(c.l)
|
||||
c.ReloadConfig()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// ReloadConfig reloads the config from the path provided to Load and runs every registered callback. A config that
|
||||
// fails to load is logged here, like any other failure, and the result carries the error for the summary.
|
||||
func (c *C) ReloadConfig() ReloadResult {
|
||||
func (c *C) ReloadConfig() {
|
||||
c.reloadLock.Lock()
|
||||
defer c.reloadLock.Unlock()
|
||||
|
||||
c.oldSettings = make(map[string]any)
|
||||
maps.Copy(c.oldSettings, c.Settings)
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
c.l.Error("Error occurred while reloading config",
|
||||
"config_path", c.path,
|
||||
"error", err,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
return c.runCallbacks()
|
||||
for _, v := range c.callbacks {
|
||||
v(c)
|
||||
}
|
||||
}
|
||||
|
||||
// ReloadConfigString is ReloadConfig for a config held in memory rather than on disk.
|
||||
func (c *C) ReloadConfigString(raw string) ReloadResult {
|
||||
func (c *C) ReloadConfigString(raw string) error {
|
||||
c.reloadLock.Lock()
|
||||
defer c.reloadLock.Unlock()
|
||||
|
||||
c.oldSettings = make(map[string]any)
|
||||
maps.Copy(c.oldSettings, c.Settings)
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.runCallbacks()
|
||||
}
|
||||
|
||||
func (c *C) runCallbacks() ReloadResult {
|
||||
r := &Reload{c: c}
|
||||
for _, v := range c.reloadCallbacks() {
|
||||
v(c, r)
|
||||
for _, v := range c.callbacks {
|
||||
v(c)
|
||||
}
|
||||
|
||||
if r.restart {
|
||||
c.needsRestart = true
|
||||
}
|
||||
return ReloadResult{Failed: r.failed, RestartRequired: c.needsRestart, RestartKeys: r.keys}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetString will get the string for k or return the default d if not found or invalid
|
||||
@@ -433,7 +391,7 @@ func (c *C) parse() error {
|
||||
var nm map[string]any
|
||||
err = yaml.Unmarshal(b, &nm)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", path, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// We need to use WithAppendSlice so that firewall rules in separate
|
||||
|
||||
+2
-41
@@ -3,7 +3,6 @@ package config
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -20,7 +19,7 @@ func TestConfig_Load(t *testing.T) {
|
||||
// invalid yaml
|
||||
c := NewC(l)
|
||||
os.WriteFile(filepath.Join(dir, "01.yaml"), []byte(" invalid yaml"), 0644)
|
||||
require.EqualError(t, c.Load(dir), filepath.Join(dir, "01.yaml")+": yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `invalid...` into map[string]interface {}")
|
||||
require.EqualError(t, c.Load(dir), "yaml: unmarshal errors:\n line 1: cannot unmarshal !!str `invalid...` into map[string]interface {}")
|
||||
|
||||
// simple multi config merge
|
||||
c = NewC(l)
|
||||
@@ -130,7 +129,7 @@ func TestConfig_ReloadConfig(t *testing.T) {
|
||||
|
||||
os.WriteFile(filepath.Join(dir, "01.yaml"), []byte("outer:\n inner: ho"), 0644)
|
||||
|
||||
c.RegisterReloadCallback(func(c *C, _ *Reload) {
|
||||
c.RegisterReloadCallback(func(c *C) {
|
||||
done <- true
|
||||
})
|
||||
|
||||
@@ -221,41 +220,3 @@ firewall:
|
||||
}
|
||||
assert.Equal(t, expected, m)
|
||||
}
|
||||
|
||||
// TestRegisterReloadCallbackDuringReload: registration is not confined to startup. The
|
||||
// HUP handler runs from inside nebula.Main, and anything wired after Main returns
|
||||
// registers while a reload may already be iterating the callbacks. Under -race this is
|
||||
// the data race on the slice; without it, it checks a callback registered mid-reload is
|
||||
// picked up by the next one.
|
||||
func TestRegisterReloadCallbackDuringReload(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
c := NewC(l)
|
||||
require.NoError(t, c.LoadString("a: 1"))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 200; i++ {
|
||||
c.RegisterReloadCallback(func(*C, *Reload) {})
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 200; i++ {
|
||||
assert.NoError(t, c.ReloadConfigString("a: 1").Err)
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
|
||||
// A callback that registers another callback must not deadlock, and the new one
|
||||
// runs from the following reload on.
|
||||
var ran int
|
||||
c.RegisterReloadCallback(func(c *C, _ *Reload) {
|
||||
c.RegisterReloadCallback(func(*C, *Reload) { ran++ })
|
||||
})
|
||||
require.NoError(t, c.ReloadConfigString("a: 1").Err)
|
||||
assert.Equal(t, 0, ran, "registered during this reload, so not run by it")
|
||||
require.NoError(t, c.ReloadConfigString("a: 1").Err)
|
||||
assert.Equal(t, 1, ran, "and run by the next")
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// ReloadResult describes how a reload went. Problems are logged where they happen, Log writes a one line summary.
|
||||
type ReloadResult struct {
|
||||
// Err is set when the new config could not be read or parsed, no callbacks ran
|
||||
Err error
|
||||
// Failed is true when a callback could not apply part of the new config
|
||||
Failed bool
|
||||
// RestartRequired is true once any reload has needed a restart, and stays true until the process restarts
|
||||
RestartRequired bool
|
||||
// RestartKeys are the keys this reload changed that only apply on a restart
|
||||
RestartKeys []string
|
||||
}
|
||||
|
||||
// Summary returns a one line summary of the reload and the level to log it at.
|
||||
func (r ReloadResult) Summary() (slog.Level, string) {
|
||||
switch {
|
||||
case r.Err != nil && r.RestartRequired:
|
||||
return slog.LevelError, "Config reload failed, the new config did not load and a restart is still required"
|
||||
case r.Err != nil:
|
||||
return slog.LevelError, "Config reload failed, the new config did not load"
|
||||
case r.Failed && r.RestartRequired:
|
||||
return slog.LevelError, "Config reload completed with errors and requires a restart to fully apply, review the logs"
|
||||
case r.Failed:
|
||||
return slog.LevelError, "Config reload completed with errors, review the logs"
|
||||
case r.RestartRequired:
|
||||
return slog.LevelWarn, "Config reload was completed but requires a restart to fully apply"
|
||||
default:
|
||||
return slog.LevelInfo, "Config reload complete"
|
||||
}
|
||||
}
|
||||
|
||||
// String is the summary with Err and RestartKeys included, for output other than the log.
|
||||
func (r ReloadResult) String() string {
|
||||
_, msg := r.Summary()
|
||||
if r.Err != nil {
|
||||
msg = fmt.Sprintf("%s: %v", msg, r.Err)
|
||||
}
|
||||
if len(r.RestartKeys) > 0 {
|
||||
msg = fmt.Sprintf("%s, keys %v", msg, r.RestartKeys)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
// Log writes Summary to l.
|
||||
func (r ReloadResult) Log(l *slog.Logger) {
|
||||
level, msg := r.Summary()
|
||||
if len(r.RestartKeys) > 0 {
|
||||
l.Log(context.Background(), level, msg, "keys", r.RestartKeys)
|
||||
return
|
||||
}
|
||||
l.Log(context.Background(), level, msg)
|
||||
}
|
||||
|
||||
// Reload is passed to each reload callback to report how applying the new config went.
|
||||
type Reload struct {
|
||||
c *C
|
||||
failed bool
|
||||
restart bool
|
||||
// Changed keys that only apply on a restart, from every callback
|
||||
keys []string
|
||||
}
|
||||
|
||||
// Failed marks the reload as failed, the caller logs why. Safe to call on a nil Reload, which is what the initial load
|
||||
// passes.
|
||||
func (r *Reload) Failed() {
|
||||
if r != nil {
|
||||
r.failed = true
|
||||
}
|
||||
}
|
||||
|
||||
// RestartRequired marks the reload as needing a restart, the caller logs why. Safe to call on a nil Reload.
|
||||
func (r *Reload) RestartRequired() {
|
||||
if r != nil {
|
||||
r.restart = true
|
||||
}
|
||||
}
|
||||
|
||||
// RestartRequiredIfChanged marks the reload as needing a restart if any of keys changed, and adds them to RestartKeys.
|
||||
// Use it for keys that are only read at startup. Safe to call on a nil Reload.
|
||||
func (r *Reload) RestartRequiredIfChanged(keys ...string) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
for _, k := range keys {
|
||||
if r.c.HasChanged(k) && !slices.Contains(r.keys, k) {
|
||||
r.keys = append(r.keys, k)
|
||||
r.restart = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestReloadConfigString(t *testing.T) {
|
||||
c := NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString("a: 1"))
|
||||
fail := false
|
||||
ran := 0
|
||||
c.RegisterReloadCallback(func(c *C, r *Reload) {
|
||||
ran++
|
||||
if fail {
|
||||
r.Failed()
|
||||
}
|
||||
})
|
||||
|
||||
assert.Equal(t, ReloadResult{}, c.ReloadConfigString("a: 2"))
|
||||
fail = true
|
||||
assert.Equal(t, ReloadResult{Failed: true}, c.ReloadConfigString("a: 3"))
|
||||
assert.Equal(t, 2, ran)
|
||||
|
||||
// A config that fails to load runs no callbacks and returns the error
|
||||
res := c.ReloadConfigString("a: [")
|
||||
require.Error(t, res.Err)
|
||||
assert.False(t, res.Failed)
|
||||
assert.Equal(t, 2, ran)
|
||||
assert.Equal(t, 3, c.GetInt("a", 0))
|
||||
}
|
||||
|
||||
func TestReloadRestartRequiredLatches(t *testing.T) {
|
||||
c := NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString("a: 1\nb: 1"))
|
||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequiredIfChanged("a", "b") })
|
||||
|
||||
// Nothing that needs a restart changed
|
||||
assert.Equal(t, ReloadResult{}, c.ReloadConfigString("a: 1\nb: 1\nc: 1"))
|
||||
assert.Equal(t, ReloadResult{RestartRequired: true, RestartKeys: []string{"a"}}, c.ReloadConfigString("a: 2\nb: 1\nc: 1"))
|
||||
|
||||
// The restart sticks through a reload with no changes, reverting the key and a config that fails to load. Only the
|
||||
// reload that changed the key lists it
|
||||
assert.Equal(t, ReloadResult{RestartRequired: true}, c.ReloadConfigString("a: 2\nb: 1\nc: 1"))
|
||||
assert.Equal(t, ReloadResult{RestartRequired: true, RestartKeys: []string{"a"}}, c.ReloadConfigString("a: 1\nb: 1\nc: 1"))
|
||||
|
||||
res := c.ReloadConfigString("a: [")
|
||||
require.Error(t, res.Err)
|
||||
assert.True(t, res.RestartRequired)
|
||||
}
|
||||
|
||||
// A key reported by more than one callback is listed once
|
||||
func TestReloadRestartKeysDeduped(t *testing.T) {
|
||||
c := NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString("a: 1\nb: 1"))
|
||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequiredIfChanged("a") })
|
||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequiredIfChanged("a", "b") })
|
||||
|
||||
assert.Equal(t, []string{"a", "b"}, c.ReloadConfigString("a: 2\nb: 2").RestartKeys)
|
||||
}
|
||||
|
||||
// A callback can require a restart without a key changing, a file the config points at may have
|
||||
func TestReloadRestartRequiredWithoutAChange(t *testing.T) {
|
||||
c := NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString("a: 1"))
|
||||
c.RegisterReloadCallback(func(c *C, r *Reload) { r.RestartRequired() })
|
||||
|
||||
assert.Equal(t, ReloadResult{RestartRequired: true}, c.ReloadConfigString("a: 1"))
|
||||
}
|
||||
|
||||
func TestReloadResultSummary(t *testing.T) {
|
||||
cases := []struct {
|
||||
res ReloadResult
|
||||
level slog.Level
|
||||
msg string
|
||||
}{
|
||||
{ReloadResult{}, slog.LevelInfo, "Config reload complete"},
|
||||
{ReloadResult{RestartRequired: true}, slog.LevelWarn, "Config reload was completed but requires a restart to fully apply"},
|
||||
{ReloadResult{Failed: true}, slog.LevelError, "Config reload completed with errors, review the logs"},
|
||||
{ReloadResult{Failed: true, RestartRequired: true}, slog.LevelError, "Config reload completed with errors and requires a restart to fully apply, review the logs"},
|
||||
{ReloadResult{Err: errors.New("bad yaml")}, slog.LevelError, "Config reload failed, the new config did not load"},
|
||||
{ReloadResult{Err: errors.New("bad yaml"), RestartRequired: true}, slog.LevelError, "Config reload failed, the new config did not load and a restart is still required"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
level, msg := tc.res.Summary()
|
||||
assert.Equal(t, tc.level, level, tc.msg)
|
||||
assert.Equal(t, tc.msg, msg)
|
||||
}
|
||||
|
||||
res := ReloadResult{RestartRequired: true, RestartKeys: []string{"a", "b"}}
|
||||
assert.Equal(t, "Config reload was completed but requires a restart to fully apply, keys [a b]", res.String())
|
||||
|
||||
// String includes the error
|
||||
assert.Equal(t, "Config reload failed, the new config did not load: bad yaml", ReloadResult{Err: errors.New("bad yaml")}.String())
|
||||
}
|
||||
|
||||
// The initial load passes a nil Reload
|
||||
func TestReloadNilIsSafe(t *testing.T) {
|
||||
var r *Reload
|
||||
r.Failed()
|
||||
r.RestartRequired()
|
||||
r.RestartRequiredIfChanged("a")
|
||||
}
|
||||
@@ -57,8 +57,7 @@ func newConnectionManagerFromConfig(l *slog.Logger, c *config.C, hm *HostMap, p
|
||||
}
|
||||
|
||||
cm.reload(c, true)
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
r.RestartRequiredIfChanged("timers.connection_alive_interval", "timers.pending_deletion_interval")
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
cm.reload(c, false)
|
||||
})
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/overlay"
|
||||
)
|
||||
@@ -48,7 +47,6 @@ type Control struct {
|
||||
|
||||
f *Interface
|
||||
l *slog.Logger
|
||||
commands *commands.Registry
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
sshStart func()
|
||||
@@ -374,13 +372,6 @@ func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
|
||||
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 {
|
||||
return c.f.inside
|
||||
}
|
||||
|
||||
@@ -151,9 +151,9 @@ func (c *fakeConn) WriteTo(_ []byte, _ netip.AddrPort) error { return nil }
|
||||
func (c *fakeConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
|
||||
return len(bufs), nil
|
||||
}
|
||||
func (c *fakeConn) ReloadConfig(_ *config.C, _ *config.Reload) {}
|
||||
func (c *fakeConn) SupportsMultipleReaders() bool { return true }
|
||||
func (c *fakeConn) Close() error { c.closed = true; return nil }
|
||||
func (c *fakeConn) ReloadConfig(_ *config.C) {}
|
||||
func (c *fakeConn) SupportsMultipleReaders() bool { return true }
|
||||
func (c *fakeConn) Close() error { c.closed = true; return nil }
|
||||
|
||||
type multiqueueDevice struct {
|
||||
*fakeDevice
|
||||
|
||||
+22
-13
@@ -12,7 +12,6 @@ import (
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/config"
|
||||
)
|
||||
|
||||
@@ -70,10 +69,9 @@ func newDnsServerFromConfig(ctx context.Context, l *slog.Logger, pki *PKI, hostM
|
||||
ds.mux = dns.NewServeMux()
|
||||
ds.mux.HandleFunc(".", ds.handleDnsRequest)
|
||||
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
if err := ds.reload(c, false); err != nil {
|
||||
ds.l.Error("Failed to reload DNS responder from config", "error", err)
|
||||
r.Failed()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -260,20 +258,31 @@ func (d *dnsServer) QueryCert(data string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Our own address answers with the certificate handshakes are initiated with, as the
|
||||
// TXT record always has; which of our certificates identity reports is its own choice.
|
||||
cs := d.certState()
|
||||
var crt cert.Certificate
|
||||
if ownsVpnAddr(cs, ip) {
|
||||
crt = cs.getCertificate(cs.initiatingVersion)
|
||||
} else {
|
||||
crt, _ = peerCertificateForVpnAddr(d.hostMap, ip)
|
||||
// The hostmap only ever contains peers we have handshaked with, so it never carries an entry for ourselves.
|
||||
// Answer self lookups straight from the local cert state.
|
||||
if cs := d.certState(); cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip) {
|
||||
c := cs.GetDefaultCertificate()
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
b, err := c.MarshalJSON()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
if crt == nil {
|
||||
|
||||
hostinfo := d.hostMap.QueryVpnAddr(ip)
|
||||
if hostinfo == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
b, err := crt.MarshalJSON()
|
||||
q := hostinfo.GetCert()
|
||||
if q == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
b, err := q.Certificate.MarshalJSON()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package nebula
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -403,32 +402,6 @@ func TestDnsServer_QueryCert_returnsOwnCert(t *testing.T) {
|
||||
assert.Empty(t, ds.QueryCert(other.String()+"."), "unknown peer IP should return nothing")
|
||||
}
|
||||
|
||||
// TestDnsServer_QueryCert_answersWithTheInitiatingCertificate: with both versions loaded
|
||||
// the TXT record carries the certificate handshakes start with, as it always has, where
|
||||
// identity and print-cert report the v2.
|
||||
func TestDnsServer_QueryCert_answersWithTheInitiatingCertificate(t *testing.T) {
|
||||
ds, _ := newTestDnsServer(t)
|
||||
me := netip.MustParseAddr("10.0.0.1")
|
||||
network := netip.PrefixFrom(me, 24)
|
||||
ca1, _, caKey1, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
v1, _, _, _ := cert_test.NewTestCert(cert.Version1, cert.Curve_CURVE25519, ca1, caKey1, "lighthouse", time.Time{}, time.Time{}, []netip.Prefix{network}, nil, nil)
|
||||
ca2, _, caKey2, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
v2, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca2, caKey2, "lighthouse", time.Time{}, time.Time{}, []netip.Prefix{network}, nil, nil)
|
||||
|
||||
addrsTable := new(bart.Lite)
|
||||
addrsTable.Insert(netip.PrefixFrom(me, me.BitLen()))
|
||||
cs := &CertState{v1Cert: v1, v2Cert: v2, initiatingVersion: cert.Version1, myVpnAddrs: []netip.Addr{me}, myVpnAddrsTable: addrsTable}
|
||||
ds.pki = &PKI{}
|
||||
ds.pki.cs.Store(cs)
|
||||
|
||||
var got struct {
|
||||
Version cert.Version `json:"version"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(ds.QueryCert(me.String()+".")), &got))
|
||||
assert.Equal(t, cert.Version1, got.Version)
|
||||
assert.Equal(t, v2, ownCertificate(cs), "identity reports the v2 from the same state")
|
||||
}
|
||||
|
||||
func TestDnsServer_reload_disable_stopsRunningServer(t *testing.T) {
|
||||
port := freeUDPPort(t)
|
||||
ds, c := newTestDnsServer(t)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# Post-quantum handshake transport compared with QUIC
|
||||
|
||||
Status: analysis, 2026-10-14. Compares the fragment transport in
|
||||
[pq-handshake.md](pq-handshake.md) with how QUIC makes its handshake reliable. TLS is out of
|
||||
scope; only the transport mechanics are compared.
|
||||
|
||||
## Summary
|
||||
|
||||
QUIC's handshake reliability is closed-loop: the receiver acknowledges, and the sender
|
||||
repairs exactly what is missing. Ours is open-loop: repair symbols are sent up front, and a
|
||||
timer sends fresh symbols. At handshake sizes (K <= 15) a QUIC-style acknowledgement
|
||||
shrinks to a 16-bit bitmap, and with an MDS code to a single count. So the real comparison
|
||||
is forward error correction versus acknowledgements, not QUIC versus us.
|
||||
|
||||
FEC is the right core. One piece of feedback is worth adding, initiator to responder and for
|
||||
msg2 only (see [Worth taking from QUIC](#worth-taking-from-quic)).
|
||||
|
||||
## What QUIC does
|
||||
|
||||
- **Messages as a stream.** Handshake bytes travel as `CRYPTO` frames (offset and length)
|
||||
and are reassembled in order. Initial and Handshake packets each have their own packet
|
||||
number space.
|
||||
- **Immediate acknowledgements.** Receivers must acknowledge Initial and Handshake packets
|
||||
without delay. ACK frames list ranges of received packet numbers.
|
||||
- **Loss detection** (RFC 9002). A packet is lost once 3 later packets are acknowledged, or
|
||||
after 9/8 of the round-trip time. Lost bytes are resent in new packets.
|
||||
- **Probe timeout (PTO).** If a whole flight vanishes, a probe timer fires. Before any RTT
|
||||
sample it starts at about 1 s (333 ms initial RTT plus 4x its variance) and doubles each
|
||||
time. Both endpoints run it.
|
||||
- **Amplification limit and anti-deadlock.** The server may send at most 3x what it
|
||||
received until the client's address is validated. The client must keep probing so a
|
||||
server stuck at that limit cannot deadlock.
|
||||
- **Retry.** A stateless round trip to validate the address. `NEW_TOKEN` lets later
|
||||
connections skip it.
|
||||
- **Congestion control from the first packet.** The initial window is 10 packets of 1200
|
||||
bytes.
|
||||
|
||||
## Side by side
|
||||
|
||||
| | QUIC | pq-handshake |
|
||||
|---|---|---|
|
||||
| Receiver feedback | ACK ranges, sent immediately | None; the next handshake message is the only acknowledgement |
|
||||
| Partial loss | +1 to 2 RTT (ACK, detect, resend) | 0 RTT while at most m symbols are lost |
|
||||
| Total loss | PTO: about 1 s, then doubling | Next PQ tick: 300 ms, then 1 s (alternating), or 100/300/600 ms (sticky) |
|
||||
| Spurious retransmit | Wasted bytes | Still useful: fresh repair indexes add to what the receiver holds |
|
||||
| Reassembly | Every byte offset, in order | Any K of up to 256 symbols |
|
||||
| Who retransmits | Both sides on their own timers | Initiator on a timer; the responder resends msg2 only when a repeat msg1 arrives (rate limited) |
|
||||
| State from the first packet | Server buffers and acknowledges partial flights | Capped pre-authentication table that never acknowledges |
|
||||
| Address validation | Retry, 1 RTT | Cookie under load, 1 RTT |
|
||||
|
||||
From the [simulation results](pq-handshake.md#simulation-results): phase 2 at 5% random
|
||||
loss with no FEC completes on the first attempt 39.8% of the time. Under
|
||||
acknowledgement-based recovery roughly 60% of handshakes would pay at least one extra round
|
||||
trip. With FEC, 0.4% wait for a retry. Spending bandwidth to save round trips is the stated
|
||||
design preference, and open-loop recovery delivers it.
|
||||
|
||||
## Where the designs already agree
|
||||
|
||||
- **1200-byte floor and the 3x amplification budget**, both taken directly from QUIC.
|
||||
- **Cookie and Retry.** Both cost one round trip and both can be forged by an on-path
|
||||
attacker. QUIC's Retry integrity tag uses a fixed, published key.
|
||||
- **On-path injection.** QUIC's Initial keys are derived from the client's connection ID,
|
||||
which an observer can read, so QUIC accepts the same handshake-blocking injection
|
||||
weakness documented for our symbols in
|
||||
[Injected symbols](pq-handshake.md#injected-symbols).
|
||||
- **Phase 2 msg3 confirmation.** Resending msg3 until any authenticated packet arrives,
|
||||
with a `Test` from the responder on completion, is QUIC's handshake confirmation and
|
||||
`HANDSHAKE_DONE`.
|
||||
|
||||
## Worth taking from QUIC
|
||||
|
||||
### 1. A msg2 progress probe from the initiator
|
||||
|
||||
This is the main gap. Today, recovering a partially lost msg2 means the initiator resends a
|
||||
full msg1 attempt; the responder decodes it, matches it in the answered-msg1 cache, and
|
||||
resends msg2. In phase 2 that is about 12 fragments (~13 KB) uploaded just to act as an
|
||||
acknowledgement, and recovery waits for the 300 ms or 1 s tick.
|
||||
|
||||
- The initiator already knows the responder's index: msg2 fragments carry it as `FragID`
|
||||
(`sendFragmentedResponse` passes `hostinfo.localIndexId`).
|
||||
- A one-packet probe, "msg2: have n of K", sent to that index would recover in about one
|
||||
round trip. The responder finds it the way phase 2 plans to find msg3.
|
||||
- Timing comes for free: msg1 send to first msg2 fragment is an RTT sample. Probe at
|
||||
roughly RTT/8 plus the repair delay after the first msg2 fragment if decoding has not
|
||||
completed.
|
||||
- Forging a probe needs the 32-bit responder index, so only an on-path attacker can, and
|
||||
the existing 3x budget bounds the reply.
|
||||
- If no msg2 fragment arrived at all, the initiator keeps today's msg1 resend. That is the
|
||||
same tail-loss case QUIC's PTO covers.
|
||||
|
||||
The reverse direction, the responder reporting progress on msg1, should not be added. It
|
||||
needs per-entry timers on the pre-authentication path, which is exactly the state QUIC
|
||||
servers carry and the reason QUIC needs Retry.
|
||||
|
||||
### 2. Buffer early data in phase 2
|
||||
|
||||
QUIC stacks hold a few packets they cannot decrypt yet. The phase 2 plan drops data that
|
||||
reaches the responder before msg3 decodes. Because repair fragments trail by
|
||||
`handshakes.pq.repair_delay` (10 ms), losing one msg3 data fragment drops about 10 ms of
|
||||
the initiator's first data while the repair is in flight. A small queue on the pending
|
||||
responder entry, replayed once msg3 verifies, avoids this.
|
||||
|
||||
### 3. Burst size across remotes
|
||||
|
||||
QUIC handshakes on a single path. `handleOutbound` sends the same `now` and `later` sets to
|
||||
every known remote and to relays (`StartRelays`).
|
||||
|
||||
- Phase 1 is fine.
|
||||
- In phase 2, four remotes means about 48 packets (~54 KB) leaving one uplink at once,
|
||||
every PQ tick, about 4x QUIC's initial window.
|
||||
- The Gilbert-Elliott simulation treats each path independently, so it does not capture
|
||||
this self-inflicted burst on a constrained uplink such as cellular.
|
||||
- Options: send the full FEC set only to the most likely remote and a reduced set to the
|
||||
others, or interleave packets across remotes.
|
||||
|
||||
## Not worth taking
|
||||
|
||||
- **Packet numbers, ACK ranges, an RTT estimator, loss thresholds, congestion control.**
|
||||
QUIC pays for this machinery because it also serves a data transport. Nebula carries
|
||||
packets and leaves reliability to the overlay's own transports. Building it only for
|
||||
handshakes of at most 15 fragments buys nothing a symbol count cannot.
|
||||
- **Offset-based reassembly.** It gives up the any-K-of-256 property and makes spurious
|
||||
retransmits wasteful again.
|
||||
- **An RTT-adaptive retry timer.** Low value. The fixed 100 ms linear schedule already fires
|
||||
sooner than QUIC's 1 s first PTO, and a spurious resend costs bandwidth, not correctness.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Keep FEC as the core and add the msg2 progress probe. That gets QUIC's roughly one round
|
||||
trip tail recovery without pre-authentication state, and cuts phase 2's retry cost on the
|
||||
uplink by about 10x. Items 2 and 3 are phase 2 concerns; item 1 also helps phase 1.
|
||||
@@ -0,0 +1,348 @@
|
||||
# Post-quantum handshakes
|
||||
|
||||
Status: draft. Decisions below were made on 2026-10-13; open items are listed at the end.
|
||||
Phase 1 is implemented (see [Implementation](#implementation-phase-1)).
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Confidentiality against harvest-now-decrypt-later.** Traffic recorded today must stay
|
||||
secret after a cryptographically relevant quantum computer exists. This needs a
|
||||
post-quantum key exchange now.
|
||||
2. **Post-quantum authentication, later.** Needs certificates whose CA signature and host
|
||||
keys are post-quantum. This requires reissuing certificates, so it ships second.
|
||||
3. **Never rely on IP fragmentation.** ML-KEM and ML-DSA do not fit in one packet, so the
|
||||
handshake must carry messages larger than the path MTU itself.
|
||||
|
||||
Non-goals: identity hiding beyond what IX offers today, and signatures at handshake time.
|
||||
The only signature in the system stays the CA signature inside the certificate.
|
||||
|
||||
## Primitives and sizes
|
||||
|
||||
| Primitive | Size |
|
||||
|---|---|
|
||||
| ML-KEM-1024 encapsulation key | 1568 B |
|
||||
| ML-KEM-1024 ciphertext | 1568 B |
|
||||
| ML-DSA-87 public key / signature | 2592 B / 4627 B |
|
||||
| Today's IX msg1 / msg2 (v2 cert, 151 B) | 252 B / 287 B |
|
||||
|
||||
`crypto/mlkem` is available in Go 1.26 (the current `go.mod`); `crypto/mldsa` arrives in
|
||||
Go 1.27 and is only needed for phase 2.
|
||||
|
||||
## Phase 1: ephemeral ML-KEM on today's certificates
|
||||
|
||||
A new handshake subtype, `ix_psk2_mlkem1024` (2), IX-shaped (2 messages; the responder
|
||||
completes on msg1 as today), using the flynn/noise `psk2` modifier. The Noise protocol name
|
||||
becomes `Noise_IXpsk2_...`, which separates it from the classical subtype.
|
||||
|
||||
- **msg1**: the initiator generates a fresh ML-KEM-1024 key pair and places the
|
||||
encapsulation key in `NebulaHandshakeDetails.KEMKey` (field 9). msg1's payload is mixed
|
||||
into the Noise transcript, so it cannot be stripped or replaced without msg2 failing.
|
||||
With the psk modifier Noise also mixes `e` into the cipher key, so msg1's static key and
|
||||
payload are encrypted, though only under a key derived from the public ephemeral.
|
||||
- **Responder**: after `ReadMessage(msg1)` it encapsulates to that key, obtaining
|
||||
`(ct, ss)`, and calls `HandshakeState.SetPresharedKey(psk)` before writing msg2, with
|
||||
`psk = HKDF-Extract(SHA-256, salt = "nebula ix_psk2_mlkem1024 v1", ikm = ss || ct)`.
|
||||
The ciphertext is bound in because, unlike the encapsulation key, it is not part of the
|
||||
Noise transcript.
|
||||
- **msg2** on the wire is `ct || noise_msg2`. The ciphertext travels outside the Noise
|
||||
message because the initiator needs `ss` before processing msg2's `psk` token. Any change
|
||||
to `ct` yields a different `ss` (ML-KEM implicit rejection) and the handshake fails.
|
||||
|
||||
Transport keys depend on both the X25519 DH outputs and the ML-KEM shared secret.
|
||||
Authentication is unchanged and classical. With a minimal v2 certificate msg1 and msg2 are
|
||||
about 1.84 KB each, so each travels as 2 data and 2 repair fragments of about 936 bytes.
|
||||
A KEM key on the classical subtype, or a missing or malformed one on this subtype, is a fatal
|
||||
protocol error; a forged ciphertext only fails that packet.
|
||||
|
||||
## Phase 2: pqIX hybrid with certificate v3
|
||||
|
||||
Certificate v3 is hybrid: the classical static key and CA signature plus a static
|
||||
ML-KEM-1024 key and an ML-DSA-87 CA signature. Host authentication is by KEM rather than by
|
||||
signature, following PQNoise's pqIX, while keeping the classical DH tokens:
|
||||
|
||||
- **msg1** (I to R): `e, s`, ephemeral ML-KEM key, initiator cert.
|
||||
- **msg2** (R to I): `e, s`, ciphertext to I's ephemeral KEM key, ciphertext to I's static
|
||||
KEM key, responder cert.
|
||||
- **msg3** (I to R): ciphertext to R's static KEM key, plus first data. R authenticates I
|
||||
when msg3 decrypts; I authenticates R implicitly when R's first reply decrypts.
|
||||
|
||||
msg3 is about 1.6 KB, 2 data and 2 repair fragments, and adds no new message types:
|
||||
|
||||
- **Responder.** After sending msg2 the responder keeps a pending Machine, found by its
|
||||
local index like the initiator's today; this is the multi-message responder support the
|
||||
manager lacks now. A repeat msg1 maps to it through the answered-msg1 cache and gets msg2
|
||||
resent with fresh symbols, exactly as in phase 1. Until msg3 verifies, data for that
|
||||
index is dropped silently: it must not draw a RecvError, which would tear down the
|
||||
initiator's new tunnel. On completing it sends an empty `Test`/`TestReply` under the
|
||||
new keys, so the initiator hears back even when there is no traffic.
|
||||
- **Initiator.** Writing msg3 yields the transport keys, so the hostinfo moves to the main
|
||||
hostmap and data flows at once, readable only by the real responder. The handshake entry
|
||||
stays behind in a confirming state: each retry tick resends msg3 with fresh symbols until
|
||||
any packet from the responder decrypts on the new tunnel, and if that never happens
|
||||
within the handshake timeout the tunnel is torn down. Losing msg3 costs the data sent
|
||||
behind it, which the overlay's own transport retransmits.
|
||||
- msg3's fragments use the responder's index as RemoteIndex and land on the responder's
|
||||
pending entry, so they never enter the pre-authentication table.
|
||||
|
||||
The initiator never caches the responder's certificate, so every handshake has three
|
||||
messages and carries both full certificates. With ML-DSA-87:
|
||||
|
||||
| Message | Size | Data fragments (k) |
|
||||
|---|---|---|
|
||||
| msg1 | ~8.2 KB | 8 |
|
||||
| msg2 | ~9.8 KB | 9 |
|
||||
| msg3 | ~1.6 KB | 2 |
|
||||
|
||||
flynn/noise cannot mix multiple KEM secrets into the chaining key, so phase 2 needs a
|
||||
KEM-aware Noise symmetric state written in this repository. Both subtypes coexist.
|
||||
|
||||
Cryptographic review of the hybrid composition will be done by in-house cryptographers.
|
||||
|
||||
## Fragment transport
|
||||
|
||||
### Requirements
|
||||
|
||||
- No IP fragmentation: every datagram's UDP payload is at most 1232 bytes **after** relay
|
||||
wrapping (16 B header + 16 B tag), the IPv6 minimum MTU budget also used by DNS Flag Day
|
||||
2020 and Solana's Turbine.
|
||||
- Every fragment of a handshake uses the same 5-tuple.
|
||||
- Bounded pre-authentication state, bounded amplification, selective loss recovery,
|
||||
tolerance of reordering and duplication, and a strictly validated, fuzzable parser.
|
||||
|
||||
### Wire format
|
||||
|
||||
Every packet of a fragmented handshake subtype is:
|
||||
|
||||
```
|
||||
Nebula header (16) Version | Type=Handshake | Subtype | Reserved=0 | RemoteIndex | Counter
|
||||
Fragment header (8) FragID u32 | MsgLen u16 | Index u8 | Flags u8
|
||||
Cookie (16) only when Flags has 0x01
|
||||
Symbol SymbolSize bytes
|
||||
```
|
||||
|
||||
- `Counter` is the Noise message number (1, 2, 3). `RemoteIndex` is 0 for msg1, as today.
|
||||
- `FragID` is the sender's local index (random, non-zero).
|
||||
- `MsgLen` is the length of the whole message. Both ends derive the layout from it:
|
||||
`K = ceil(MsgLen / 1160)`, `SymbolSize = ceil(MsgLen / K)`. Every symbol has the same
|
||||
size. Room for a cookie is always reserved, so a packet is at most
|
||||
16 + 8 + 16 + 1160 = 1200 bytes with or without one.
|
||||
- `Index < K` is a data symbol (a slice of the message, the last one zero padded);
|
||||
`Index >= K` is a repair symbol.
|
||||
- `Flags` bit 0x01 means a cookie follows the fragment header. Other bits must be zero.
|
||||
|
||||
A cookie reply, sent by a responder under load, is a bare 32 byte packet:
|
||||
|
||||
```
|
||||
Nebula header (16) Version | Type=Handshake | Subtype | Reserved=0 | RemoteIndex=FragID | Counter=0
|
||||
Cookie (16)
|
||||
```
|
||||
|
||||
It names the initiator's FragID, so the initiator finds its attempt the same way it finds
|
||||
msg2.
|
||||
|
||||
### Forward error correction
|
||||
|
||||
Messages are protected with a systematic Reed-Solomon code over GF(2^8), implemented in
|
||||
`handshake/fec`:
|
||||
|
||||
- The repair rows form a Cauchy matrix, `coefficient(row, col) = 1 / (row XOR col)` with
|
||||
`row >= K > col`, so every square submatrix is invertible and **any K distinct symbols
|
||||
reconstruct the message**. Naive identity-over-Vandermonde constructions are not MDS
|
||||
(the PAR1 flaw and the 1997 Plank tutorial erratum).
|
||||
- A repair row depends only on its index, so repair symbols are generated on demand and
|
||||
their indexes never need to be agreed in advance. Up to 256 symbols exist per message.
|
||||
- Known-answer vectors in `fec_test.go` pin the encoding and were cross-checked against an
|
||||
independent implementation; changing them is a wire format change.
|
||||
- Cost for a 9.8 KB message (k=9): about 13 µs for three repair symbols, about 19 µs to
|
||||
decode with three data symbols missing.
|
||||
|
||||
**The sender chooses m**, the number of repair symbols per attempt. The receiver only needs
|
||||
any K symbols, so this is policy and can change without a protocol change. The starting
|
||||
rule is `m = max(2, ceil(K/3))`.
|
||||
|
||||
**Retries send fresh symbols.** Attempt 0 sends indexes `0 .. K+m-1`; each retry sends
|
||||
the next `K+m` unused indexes. The receiver merges all distinct symbols across attempts,
|
||||
so no received fragment is wasted. Indexes are a deterministic function of the message,
|
||||
so retransmits stay idempotent: the responder caches msg2 itself and regenerates any
|
||||
symbol.
|
||||
|
||||
**Repair symbols trail the data.** Data symbols go out back to back; repair symbols follow
|
||||
after a short delay, so a queue tail-drop at the end of the data run does not also take the
|
||||
repair. In simulation this lifts small messages substantially (k=2 at 10% loss, burst 8:
|
||||
91.4% to 98.2% first-attempt success). Pacing every fragment was also evaluated; it gains
|
||||
about 5 more points for k=7..9 on bursty paths, which is not worth the extra machinery,
|
||||
and the retry with fresh symbols covers the remainder.
|
||||
|
||||
### Receiver rules
|
||||
|
||||
Implemented in `handshake/fragment` (`Sender`, `Assembly`, and the capped `Table`).
|
||||
|
||||
- Fragments are stored individually as they arrive and charged against a memory cap.
|
||||
Nothing is allocated from a claimed size alone (FragmentSmack, game-engine "fragment
|
||||
bombs").
|
||||
- `MsgLen` must be identical for every fragment of a `FragID`; a mismatch drops the whole
|
||||
entry. msg1 is capped at `MsgLen <= 16384` (K <= 15).
|
||||
- The decoder keeps at most K distinct symbols, so an entry never exceeds about MsgLen bytes
|
||||
however many repair symbols arrive.
|
||||
- When K symbols are present the message is decoded and handed to the handshake `Machine`
|
||||
as a synthetic `[header | message]`. The Machine never sees fragments.
|
||||
- A completed entry is forgotten immediately. A late duplicate fragment starts a new entry
|
||||
and, once enough arrive, reconstructs the same message again; the handshake layer's
|
||||
duplicate detection recognises it.
|
||||
- If Noise rejects a decoded message, the entry is discarded and the next attempt
|
||||
supplies fresh symbols. (Possible refinement: keep a few spare symbols so an injected
|
||||
bad symbol can be identified by re-encoding instead of waiting for a retry.)
|
||||
- Pre-authentication msg1 entries live in a table keyed by (source address or relay index,
|
||||
FragID) with a total memory cap, per-source quotas (/32 for IPv4, /64 for IPv6), a
|
||||
sliding TTL of about 2 s refreshed by progress, and random eviction under pressure.
|
||||
msg2 and msg3 reassembly attaches to the existing pending handshake found by RemoteIndex.
|
||||
|
||||
### Retransmission and amplification
|
||||
|
||||
- Only timers cause transmission. Reactive resends (the responder resending its cached
|
||||
msg2 when a duplicate msg1 completes) are rate limited to one per handshake per retry
|
||||
interval, to avoid TFTP's Sorcerer's Apprentice amplification.
|
||||
- Duplicate msg1 detection compares the decoded message to the cached one **before**
|
||||
running Noise or certificate verification.
|
||||
- Before an address is validated, a responder sends at most 3x the bytes it received from
|
||||
it (QUIC's rule). Normal handshakes sit near 1.1-1.2x.
|
||||
- In phase 2 the initiator retransmits msg3 until any authenticated packet arrives from
|
||||
the responder; the responder sends a small confirmation on completion and holds tunnel
|
||||
traffic until msg3 verifies.
|
||||
|
||||
### Denial of service
|
||||
|
||||
The responder can no longer complete statelessly on msg1, since msg1 arrives in pieces.
|
||||
Defenses are the capped table above plus a **cookie under load**, in the style of
|
||||
WireGuard's mac2, QUIC Retry and the SCTP state cookie:
|
||||
|
||||
- Once the msg1 table is at least half full (by bytes or by entries), every msg1 fragment
|
||||
must carry a valid cookie. One without is answered with a cookie reply and leaves no
|
||||
state. Fragments that already belong to an entry need one too, so an attacker cannot
|
||||
hold old entries open.
|
||||
- A cookie is `HMAC-SHA256(secret, source address and port, relay channel, FragID)`
|
||||
truncated to 16 bytes. The secret rotates every 2 minutes and the previous one is still
|
||||
accepted, so a cookie is good for 2 to 4 minutes.
|
||||
- Replies are never larger than the packet that prompted them (no amplification) and are
|
||||
rate limited as a whole (a burst of 256, then 1000 per second), so spoofed floods cannot
|
||||
turn the responder into a reflector.
|
||||
- The initiator attaches the cookie to its PQ attempt, so every later packet carries it,
|
||||
and immediately resends fresh symbols to the address the reply came from, at most once
|
||||
per retry interval. Under load a PQ handshake costs one extra round trip, which in
|
||||
practice still beats the classical attempt on the next retry tick.
|
||||
- An attacker on the path can forge a cookie reply; the bogus cookie is simply rejected
|
||||
and answered with a real one.
|
||||
|
||||
A CA-keyed pre-filter MAC was considered and rejected: networks commonly trust many CAs.
|
||||
|
||||
#### Injected symbols
|
||||
|
||||
The decoder keeps the first K distinct symbols it sees, so one forged symbol in those K
|
||||
spoils that attempt's decode; Noise rejects the result and the next attempt brings fresh
|
||||
symbols. Forging one needs the attempt's FragID or index, which are random 32 bit values,
|
||||
and for msg1 the initiator's exact address and port too, so in practice only an attacker
|
||||
who sees the traffic can do it. An attacker who can also drop packets gains nothing new.
|
||||
One who can only inject, and races a forged symbol into every attempt, can stop a PQ
|
||||
handshake where it could not stop a classical one, since classical msg2s are tried one
|
||||
packet at a time. Keeping spare symbols to find a consistent subset only raises the number
|
||||
of forgeries needed per attempt, and authenticating symbols is impossible for msg1, which
|
||||
travels before any key exists. So the decoder deliberately does neither. A non-sticky
|
||||
initiator still gets a classical tunnel from its next attempt; a sticky one, by design,
|
||||
does not downgrade.
|
||||
|
||||
## Rollout
|
||||
|
||||
- Separate settings for initiating and accepting PQ handshakes, both off by default:
|
||||
`handshakes.pq.initiate`, `handshakes.pq.accept`. `handshakes.pq.repair_delay` (default
|
||||
10ms) sets how long repair fragments trail the data fragments.
|
||||
- `handshakes.pq.require` makes every handshake PQ: it implies `initiate` and `accept`,
|
||||
never offers a classical attempt, and drops classical msg1s.
|
||||
- Old nodes silently drop unknown subtypes, so discovery is speculative: an initiator with
|
||||
`initiate` enabled alternates PQ and classical attempts on successive timer retries,
|
||||
keeping both pending, and the first to complete wins. A path nothing has been sent over
|
||||
yet gets the PQ attempt first: an early resend triggered by a lighthouse reply is PQ, and
|
||||
a relay that comes up pushes the PQ attempt through at once, counting as the PQ turn.
|
||||
Without that, relays set up during the first attempt handed every relayed handshake to
|
||||
the classical retry (seen on real hosts: 11 of 11). Once a msg2 fragment or cookie reply
|
||||
arrives for the PQ attempt the peer evidently speaks PQ, and classical stops getting
|
||||
turns.
|
||||
- All `handshakes.pq` settings reload without a restart. Handshakes in flight carry on;
|
||||
the new settings apply to the next attempt and the next packet.
|
||||
- `handshakes.pq.sticky` (default off): once a peer has completed a PQ handshake, never fall
|
||||
back to classical for it again during this process lifetime. This resists active
|
||||
downgrade after first contact.
|
||||
- No lighthouse capability advertisement.
|
||||
|
||||
## Simulation results
|
||||
|
||||
Gilbert-Elliott channel (bad state drops everything), losses expressed as average rate and
|
||||
mean burst length in packets. First-attempt success for the whole handshake with
|
||||
`m = max(2, ceil(K/3))` and repair delayed 16 packet slots, compared with no FEC:
|
||||
|
||||
| Handshake | Loss | Burst 1 | Burst 2 | Burst 4 | Burst 8 |
|
||||
|---|---|---|---|---|---|
|
||||
| phase 1 (2, 2) no FEC | 5% | 81.4% | 85.6% | 87.9% | 89.0% |
|
||||
| phase 1 (2, 2) FEC | 5% | 99.9% | 99.4% | 99.3% | 98.6% |
|
||||
| phase 1 (2, 2) FEC | 10% | 99.3% | 97.5% | 97.4% | 96.3% |
|
||||
| phase 2 (8, 9, 2) no FEC | 5% | 37.8% | 56.0% | 69.3% | 77.1% |
|
||||
| phase 2 (8, 9, 2) FEC | 5% | 99.6% | 93.7% | 89.9% | 88.4% |
|
||||
| phase 2 (8, 9, 2) FEC | 10% | 95.3% | 83.5% | 77.9% | 76.7% |
|
||||
|
||||
With fresh repair symbols, phase 2 completes within two attempts at least 99.1% of the time
|
||||
in every scenario above, and within three at least 99.98%.
|
||||
|
||||
The simulators and their outputs are in [pq-handshake-sim](pq-handshake-sim/README.md),
|
||||
including a comparison with classical handshakes and a model of time to a working tunnel
|
||||
under Nebula's retry schedule.
|
||||
|
||||
## Prior art
|
||||
|
||||
- **WireGuard / Rosenpass**: fit every message in one packet; cookies and biscuits for
|
||||
statelessness. Not possible at our sizes.
|
||||
- **IKEv2**: RFC 7383 fragments only after keys exist, with each fragment authenticated;
|
||||
RFC 9242/9370 move PQ key exchange into intermediate exchanges for that reason.
|
||||
- **QUIC / DTLS 1.3**: offset-based reassembly with ACKs; QUIC's 3x amplification limit and
|
||||
1200-byte floor.
|
||||
- **Solana Turbine**: Reed-Solomon over 1232-byte UDP packets through untrusted relays;
|
||||
moved to Merkle-authenticated shreds after unauthenticated repair symbols enabled
|
||||
poisoning.
|
||||
- **kcp-go, UDPspeeder, CM256**: RS FEC over UDP; parity must scale up for small groups.
|
||||
- **gQUIC FEC (removed)**: FEC does not pay for bulk transfer under bursty loss; it does
|
||||
for short, latency-critical transfers such as handshakes.
|
||||
- **TFTP, NFS duplicate request cache, memcached UDP, IP reassembly bugs**: retransmit
|
||||
storms, ID-wrap misassembly, reflection amplification, and allocation from claimed sizes.
|
||||
|
||||
## Implementation (phase 1)
|
||||
|
||||
- `handshake`: the `ix_psk2_mlkem1024` subtype (`patterns.go`, `kem.go`), the `KEMKey`
|
||||
payload field, and the psk2 plumbing in `Machine`.
|
||||
- `handshake/fec`, `handshake/fragment`: the code and the fragment transport.
|
||||
- `handshake_manager_pq.go` and the manager:
|
||||
- **Initiator.** Attempts alternate PQ and classical, starting with PQ (sticky peers get
|
||||
only PQ). The PQ attempt has its own local index registered alongside the classical
|
||||
one; whichever response completes first wins, and the other index is released
|
||||
(`settleIndex`). A timed out or deleted pending handshake releases both.
|
||||
- **Responder.** msg1 fragments go into the capped pre-authentication table. A decoded
|
||||
msg1 is looked up by hash among recently answered ones before any Noise, KEM or
|
||||
certificate work: the trailing repair fragments of an attempt rebuild a msg1 its data
|
||||
fragments already completed, and a retrying initiator offers fresh symbols for the
|
||||
same msg1. A repeat goes straight to the cached-response resend, which offers fresh
|
||||
msg2 symbols, is rate limited to one per retry interval and is held to the 3x
|
||||
amplification budget.
|
||||
- **Relays** carry fragments unchanged; repair fragments trail via a timer.
|
||||
- The pre-authentication table is capped at 4 MiB, 1024 entries, 4 per source (IPv4 /32,
|
||||
IPv6 /64, or relay channel), 16 KiB messages and a 3 s idle timeout. Cookies are
|
||||
demanded from half full.
|
||||
- Tests: Noise-level KEM tests, codec and fragment tests and fuzzers, manager unit tests
|
||||
for the response budget and rate limit, and e2e tests for a clean handshake, loss of
|
||||
data fragments in both directions, fallback to a peer that does not accept PQ, a lost
|
||||
msg2 recovered by fresh symbols, sticky mode under an attacker dropping PQ packets,
|
||||
relays, index cleanup on completion, fallback and timeout, and a responder flooded from
|
||||
spoofed sources demanding and accepting a cookie. Unit tests cover cookie binding and
|
||||
rotation, the never-amplify rule, the initiator's rate limited resend, and reload. ML-KEM and HKDF also
|
||||
pass under `GOEXPERIMENT=boringcrypto` and `GODEBUG=fips140=on`.
|
||||
|
||||
## Open items
|
||||
|
||||
None for phase 1. Phase 2 needs certificate v3, the KEM-aware Noise symmetric state, and
|
||||
the msg3 design above.
|
||||
@@ -1,181 +0,0 @@
|
||||
//go:build e2e_testing
|
||||
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/sshd"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// volatile lists everything in command output that legitimately differs between runs.
|
||||
// Each run mints fresh certificates and indexes, so these are replaced with a marker
|
||||
// before comparison. Keep the list short: anything added here is something the golden
|
||||
// stops guarding.
|
||||
var volatile = []struct {
|
||||
re *regexp.Regexp
|
||||
with string
|
||||
}{
|
||||
{regexp.MustCompile(`[0-9a-f]{40,}`), "<hex>"}, // fingerprints, keys, signatures
|
||||
{regexp.MustCompile(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})`), "<time>"}, // RFC 3339
|
||||
{regexp.MustCompile(`\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4} \w+`), "<time>"}, // time.Time.String()
|
||||
{regexp.MustCompile(`(?s)(-----BEGIN [A-Z ]+-----\n).*?(\n-----END [A-Z ]+-----)`), "${1}<pem>${2}"}, // print-cert -raw
|
||||
{regexp.MustCompile(`(-----BEGIN [A-Z ]+-----\\n).*?(\\n-----END [A-Z ]+-----)`), "${1}<pem>${2}"}, // the same, inside a JSON string
|
||||
{regexp.MustCompile(`"(localIndex|remoteIndex|messageCounter)":\d+`), `"$1":<n>`},
|
||||
{regexp.MustCompile(`(?m)^(\s*"?(?:LocalIndex|RemoteIndex|localIndex|remoteIndex|messageCounter)"?:?\s*)\d+`), "${1}<n>"}, // and the -pretty form
|
||||
}
|
||||
|
||||
func normalise(s string) string {
|
||||
for _, v := range volatile {
|
||||
s = v.re.ReplaceAllString(s, v.with)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// outputCase is one command line to run through the ssh dispatch path.
|
||||
type outputCase struct {
|
||||
name string
|
||||
args []string
|
||||
}
|
||||
|
||||
// TestCommandOutput pins the bytes every command produces, in every format, through the
|
||||
// ssh dispatch path. It is the safety net for moving rendering out of the commands: a
|
||||
// change here is a change someone at an ssh prompt would see. Regenerate with:
|
||||
//
|
||||
// go test -tags e2e_testing ./e2e -run TestCommandOutput -update
|
||||
func TestCommandOutput(t *testing.T) {
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(
|
||||
cert.Version1, cert.Curve_CURVE25519,
|
||||
time.Now(), time.Now().Add(10*time.Minute),
|
||||
nil, nil, []string{},
|
||||
)
|
||||
|
||||
control, _, _, _ := newSimpleServer(cert.Version1, ca, caKey, "output-golden", "10.222.0.1/24", nil)
|
||||
control.Start()
|
||||
t.Cleanup(func() { control.Stop() })
|
||||
|
||||
// As an ssh session does: a clone of the daemon's registry with logout added, which
|
||||
// help on the clone lists and describes. There is no session to end here.
|
||||
reg := control.Commands().Clone()
|
||||
reg.Register(sshd.LogoutCommand(func() {}))
|
||||
// Dispatch with ssh's default-format policy, so the no-flag column records what an
|
||||
// operator at an ssh prompt sees.
|
||||
reg.DefaultFormat = sshd.DefaultFormat
|
||||
|
||||
// run dispatches as the ssh exec path does and returns the output and the error, which
|
||||
// over ssh is exit status 1.
|
||||
run := func(args ...string) (string, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
err := reg.DispatchArgs(args, commands.MergedOutput(buf))
|
||||
return buf.String(), err
|
||||
}
|
||||
|
||||
// Seed a pending tunnel so the listing and per-address commands have something to show.
|
||||
seed, err := run("create-tunnel", "10.222.0.9")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Created\n", seed, "seeding a tunnel should succeed before anything else is recorded")
|
||||
|
||||
cases := []outputCase{
|
||||
{"version", nil},
|
||||
{"device-info", nil},
|
||||
{"list-hostmap", nil},
|
||||
{"list-hostmap", []string{"-by-index"}},
|
||||
{"list-pending-hostmap", nil},
|
||||
{"list-pending-hostmap", []string{"-by-index"}},
|
||||
{"list-lighthouse-addrmap", nil},
|
||||
{"print-cert", nil},
|
||||
{"print-cert", []string{"-raw"}},
|
||||
{"print-cert", []string{"10.222.0.9"}},
|
||||
// A flag after the operand is still a flag, on both surfaces.
|
||||
{"print-cert", []string{"10.222.0.9", "-json"}},
|
||||
{"print-cert", []string{"10.222.0.250"}},
|
||||
{"print-cert", []string{"not-an-address"}},
|
||||
{"whoami", nil},
|
||||
{"whoami", []string{"x"}},
|
||||
// No address is a refusal that names whoami, never this node's identity.
|
||||
{"identity", nil},
|
||||
// Our own address, which the hostmap never holds, answers from our certificate.
|
||||
{"identity", []string{"-address", "10.222.0.1"}},
|
||||
{"identity", []string{"-address", "10.222.0.1:4242"}},
|
||||
// A pending tunnel has no certificate yet.
|
||||
{"identity", []string{"-address", "10.222.0.9"}},
|
||||
{"identity", []string{"-address", "not-an-address"}},
|
||||
{"identity", []string{"-address", ""}},
|
||||
{"identity", []string{"10.222.0.9"}},
|
||||
{"print-tunnel", nil},
|
||||
{"print-tunnel", []string{"10.222.0.9"}},
|
||||
{"print-tunnel", []string{"10.222.0.250"}},
|
||||
{"print-relays", nil},
|
||||
{"query-lighthouse", nil},
|
||||
{"query-lighthouse", []string{"10.222.0.9"}},
|
||||
{"query-lighthouse", []string{"not-an-address"}},
|
||||
// The test logger cannot change level or format, so these cases record the
|
||||
// refusal each command prints on it, not a successful change.
|
||||
{"log-level", nil},
|
||||
{"log-level", []string{"debug"}},
|
||||
{"log-level", []string{"bogus"}},
|
||||
{"log-level", []string{"info"}},
|
||||
{"log-format", nil},
|
||||
{"log-format", []string{"json"}},
|
||||
{"log-format", []string{"text"}},
|
||||
{"change-remote", nil},
|
||||
{"change-remote", []string{"10.222.0.9"}},
|
||||
{"change-remote", []string{"-address", "10.94.0.10:4242", "10.222.0.9"}},
|
||||
{"change-remote", []string{"-address", "10.94.0.10:4242", "10.222.0.250"}},
|
||||
{"create-tunnel", nil},
|
||||
{"create-tunnel", []string{"10.222.0.9"}},
|
||||
// A fresh address, so this exercises the handshake start with a remote attached
|
||||
// rather than the "already handshaking" path above.
|
||||
{"create-tunnel", []string{"-address", "10.94.0.10:4242", "10.222.0.10"}},
|
||||
{"create-tunnel", []string{"not-an-address"}},
|
||||
{"close-tunnel", nil},
|
||||
{"close-tunnel", []string{"10.222.0.250"}},
|
||||
{"close-tunnel", []string{"not-an-address"}},
|
||||
{"help", nil},
|
||||
{"help", []string{"print-cert"}},
|
||||
{"help", []string{"logout"}},
|
||||
{"logout", []string{"-h"}},
|
||||
{"not-a-command", []string{"10.222.0.9"}},
|
||||
// reload is last so that whatever a reload does to the daemon cannot leak into an
|
||||
// earlier case. In this harness it fails: the config was loaded from a string and
|
||||
// has no path to re-read, which is what the recorded result says.
|
||||
{"reload", nil},
|
||||
}
|
||||
|
||||
got := &strings.Builder{}
|
||||
for _, c := range cases {
|
||||
for _, fmtFlags := range [][]string{nil, {"-json"}, {"-pretty"}} {
|
||||
args := append([]string{c.name}, fmtFlags...)
|
||||
args = append(args, c.args...)
|
||||
|
||||
fmt.Fprintf(got, "$ %s\n", strings.Join(args, " "))
|
||||
out, err := run(args...)
|
||||
out = normalise(out)
|
||||
got.WriteString(out)
|
||||
// Output that does not end in a newline is recorded as such, the way diff marks
|
||||
// it, so the golden sees that byte too and the next prompt still starts a line.
|
||||
if out != "" && !strings.HasSuffix(out, "\n") {
|
||||
got.WriteString("\\ No newline at end of output\n")
|
||||
}
|
||||
// A failed command is recorded as the exit status an ssh caller sees, so the
|
||||
// golden pins which outcomes count as failures.
|
||||
if err != nil {
|
||||
got.WriteString("exit status 1\n")
|
||||
}
|
||||
got.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
test.Golden(t, filepath.Join("testdata", "commands_output.golden"), got.String())
|
||||
}
|
||||
@@ -1513,7 +1513,7 @@ func TestLighthouseUpdateOnReload(t *testing.T) {
|
||||
// Reload the config. The lighthouse.hosts change triggers TriggerUpdate,
|
||||
// which wakes the update worker. It calls SendUpdate, initiating a
|
||||
// handshake to the new lighthouse and caching the HostUpdateNotification.
|
||||
require.NoError(t, myConfig.ReloadConfigString(string(newCfg)).Err)
|
||||
require.NoError(t, myConfig.ReloadConfigString(string(newCfg)))
|
||||
|
||||
// Route until the lighthouse receives the HostUpdateNotification.
|
||||
// This covers: handshake stage 1, stage 2, then the cached update.
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
//go:build e2e_testing
|
||||
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/e2e/router"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestIdentityOverTheInfoAPI is the info API's reason to exist, end to end: a program on
|
||||
// this host has a connection arriving over the overlay and asks who is behind its
|
||||
// source address, and the answer is the identity in the certificate the tunnel was
|
||||
// established with.
|
||||
func TestIdentityOverTheInfoAPI(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the test's HTTP helpers dial unix sockets; on windows the info API is a named pipe")
|
||||
}
|
||||
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.1/24", nil)
|
||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.2/24", nil)
|
||||
|
||||
myControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||
|
||||
r := router.NewR(t, myControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
|
||||
myControl.Start()
|
||||
theirControl.Start()
|
||||
t.Cleanup(func() {
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
|
||||
// Before the tunnel is up their address is unknown to us.
|
||||
path := infoSocket(t)
|
||||
info := localapi.NewInfoServer(NewTestLogger(), myControl.Commands())
|
||||
require.NoError(t, info.Rebind(context.Background(), path, localapi.Access{Mode: 0600}))
|
||||
t.Cleanup(info.Stop)
|
||||
|
||||
status, body := test.HTTPGet(t, path, "/v1/identity?address="+theirVpnIpNet[0].Addr().String())
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
assert.JSONEq(t, `{"error":"No active tunnel for vpn addr: 10.128.0.2"}`, body)
|
||||
|
||||
// Only we know how to reach them, so the first packet has to be ours; once the tunnel
|
||||
// is up both directions work and assertTunnel can check it.
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("Hi from me")))
|
||||
p := r.RouteForAllUntilTxTun(theirControl)
|
||||
assertUdpPacket(t, []byte("Hi from me"), p, myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), 80, 80)
|
||||
assertTunnel(t, myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
type identity struct {
|
||||
Name string `json:"name"`
|
||||
VpnAddrs []netip.Addr `json:"vpnAddrs"`
|
||||
Networks []netip.Prefix `json:"networks"`
|
||||
Groups []string `json:"groups"`
|
||||
Issuer string `json:"issuer"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
}
|
||||
|
||||
// A connection's RemoteAddr, port and all, resolves to the peer.
|
||||
status, body = test.HTTPGet(t, path, "/v1/identity?address="+netip.AddrPortFrom(theirVpnIpNet[0].Addr(), 51234).String())
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
var them identity
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &them))
|
||||
assert.Equal(t, "them", them.Name)
|
||||
assert.Equal(t, []netip.Addr{theirVpnIpNet[0].Addr()}, them.VpnAddrs)
|
||||
assert.Equal(t, theirVpnIpNet, them.Networks)
|
||||
assert.Equal(t, []string{}, them.Groups)
|
||||
caFP, err := ca.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, caFP, them.Issuer)
|
||||
|
||||
// No address is a caller that forgot the parameter, and is refused rather than handed
|
||||
// this node's identity to authorize against; whoami is the command for that.
|
||||
status, body = test.HTTPGet(t, path, "/v1/identity")
|
||||
assert.Equal(t, http.StatusBadRequest, status, body)
|
||||
assert.Contains(t, body, "whoami")
|
||||
|
||||
status, body = test.HTTPGet(t, path, "/v1/whoami")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
var me identity
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &me))
|
||||
assert.Equal(t, "me", me.Name)
|
||||
assert.Equal(t, []netip.Addr{myVpnIpNet[0].Addr()}, me.VpnAddrs)
|
||||
|
||||
// An empty address is a caller's bug, and is told so rather than handed our identity.
|
||||
status, body = test.HTTPGet(t, path, "/v1/identity?address=")
|
||||
assert.Equal(t, http.StatusBadRequest, status)
|
||||
assert.JSONEq(t, `{"error":"The provided vpn addr could not be parsed: "}`, body)
|
||||
|
||||
// The certificate itself, for a program that verifies it against its own CAs: the one
|
||||
// nebula verified when the tunnel came up, as PEM, by the address a connection carries.
|
||||
status, body = test.HTTPGet(t, path, "/v1/print-cert?address="+netip.AddrPortFrom(theirVpnIpNet[0].Addr(), 51234).String()+"&raw=true")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
var raw struct {
|
||||
PEM string `json:"pem"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &raw))
|
||||
theirs, _, err := cert.UnmarshalCertificateFromPEM([]byte(raw.PEM))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "them", theirs.Name())
|
||||
fp, err := theirs.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, them.Fingerprint, fp, "the same certificate identity reports")
|
||||
|
||||
// Without raw it is the certificate's fields; without an address, our own.
|
||||
status, body = test.HTTPGet(t, path, "/v1/print-cert")
|
||||
require.Equal(t, http.StatusOK, status, body)
|
||||
assert.Contains(t, body, `"name":"me"`)
|
||||
|
||||
status, body = test.HTTPGet(t, path, "/v1/print-cert?address=10.128.0.9")
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
assert.JSONEq(t, `{"error":"Could not find tunnel for vpn addr: 10.128.0.9"}`, body)
|
||||
|
||||
// Nothing else nebula serves is reachable here.
|
||||
status, body = test.HTTPGet(t, path, "/v1/list-hostmap")
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
assert.Contains(t, body, "identity lookups only")
|
||||
|
||||
r.RenderHostmaps("Final hostmaps", myControl, theirControl)
|
||||
}
|
||||
|
||||
// infoSocket returns a short socket path in a private directory, one level below it
|
||||
// so that listen has a directory of its own to create.
|
||||
func infoSocket(t *testing.T) string {
|
||||
t.Helper()
|
||||
return filepath.Join(test.ShortTempDir(t), "n", "info.sock")
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
//go:build e2e_testing
|
||||
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sync"
|
||||
"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/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func pqRequire() m {
|
||||
return m{"handshakes": m{"pq": m{"require": true, "repair_delay": "0s"}}}
|
||||
}
|
||||
|
||||
func pqConfig(initiate, accept, sticky bool) m {
|
||||
return m{"handshakes": m{"pq": m{
|
||||
"initiate": initiate,
|
||||
"accept": accept,
|
||||
"sticky": sticky,
|
||||
"repair_delay": "0s",
|
||||
}}}
|
||||
}
|
||||
|
||||
// handshakeOf returns the handshake header p carries, looking inside relay
|
||||
// wrapping, plus the fragment header when the handshake is fragmented.
|
||||
func handshakeOf(p *udp.Packet) (*header.H, *fragment.Header) {
|
||||
b := p.Data
|
||||
h := &header.H{}
|
||||
if h.Parse(b) != nil {
|
||||
return nil, nil
|
||||
}
|
||||
if h.Type == header.Message && h.Subtype == header.MessageRelay {
|
||||
// Relays authenticate but do not encrypt the inner packet.
|
||||
b = b[header.Len:]
|
||||
if h.Parse(b) != nil {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
if h.Type != header.Handshake {
|
||||
return nil, nil
|
||||
}
|
||||
if !header.IsFragmented(h.Subtype) {
|
||||
return h, nil
|
||||
}
|
||||
// A relayed packet still has the relay's AEAD tag on the end.
|
||||
for _, tag := range []int{0, 16} {
|
||||
if len(b) < header.Len+tag {
|
||||
break
|
||||
}
|
||||
if fh, _, err := fragment.Parse(b[header.Len : len(b)-tag]); err == nil {
|
||||
return h, &fh
|
||||
}
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// handshakeTally counts handshake packets by style as the router moves them.
|
||||
type handshakeTally struct {
|
||||
sync.Mutex
|
||||
pq, classical int
|
||||
maxPQLen int
|
||||
}
|
||||
|
||||
func (ht *handshakeTally) observe(p *udp.Packet) {
|
||||
h, _ := handshakeOf(p)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
ht.Lock()
|
||||
defer ht.Unlock()
|
||||
if h.Subtype == header.HandshakeIXPSK2MLKEM1024 {
|
||||
ht.pq++
|
||||
ht.maxPQLen = max(ht.maxPQLen, len(p.Data))
|
||||
} else {
|
||||
ht.classical++
|
||||
}
|
||||
}
|
||||
|
||||
// isTunnelData reports whether p is ordinary tunnel traffic headed for to,
|
||||
// directly or as the last hop of a relay.
|
||||
func isTunnelData(p *udp.Packet, receiver, to *nebula.Control) bool {
|
||||
h := &header.H{}
|
||||
if receiver != to || h.Parse(p.Data) != nil || h.Type != header.Message {
|
||||
return false
|
||||
}
|
||||
if h.Subtype == header.MessageRelay {
|
||||
if h.Parse(p.Data[header.Len:]) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return h.Type == header.Message && h.Subtype == header.MessageNone
|
||||
}
|
||||
|
||||
func newPQPair(t *testing.T, mine, theirs m) (myControl, theirControl *nebula.Control, myVpn, theirVpn []netip.Prefix, myUdp, theirUdp netip.AddrPort, r *router.R) {
|
||||
t.Helper()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
myControl, myVpn, myUdp, _ = newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.1/24", mine)
|
||||
theirControl, theirVpn, theirUdp, _ = newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.2/24", theirs)
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
r = router.NewR(t, myControl, theirControl)
|
||||
myControl.Start()
|
||||
theirControl.Start()
|
||||
return
|
||||
}
|
||||
|
||||
func TestPQHandshake(t *testing.T) {
|
||||
t.Parallel()
|
||||
// They only accept, which is all a PQ initiator needs.
|
||||
myControl, theirControl, myVpn, theirVpn, myUdp, theirUdp, r := newPQPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Zero(t, tally.classical, "no classical handshake should be needed")
|
||||
assert.GreaterOrEqual(t, tally.pq, 4, "both messages travel as several fragments")
|
||||
assert.LessOrEqual(t, tally.maxPQLen, fragment.MaxPacketLen)
|
||||
|
||||
assertHostInfoPair(t, myUdp, theirUdp, myVpn, theirVpn, myControl, theirControl)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true), "no pending index may outlive the handshake")
|
||||
assert.Empty(t, theirControl.ListHostmapIndexes(true))
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQHandshakeLoss drops data fragments of both messages; the repair
|
||||
// fragments must carry the handshake without a retry.
|
||||
func TestPQHandshakeLoss(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
dropped := 0
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if h, fh := handshakeOf(p); fh != nil {
|
||||
// Every data fragment of msg1, and the first of msg2.
|
||||
if (h.MessageCounter == 1 && int(fh.Index) < 2) || (h.MessageCounter == 2 && fh.Index == 0) {
|
||||
dropped++
|
||||
return router.Drop
|
||||
}
|
||||
}
|
||||
tally.observe(p)
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Equal(t, 3, dropped)
|
||||
assert.Zero(t, tally.classical, "the first attempt should succeed from repair fragments")
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQFallback has a peer that does not accept PQ handshakes. The initiator's
|
||||
// next attempt is classical and the tunnel comes up anyway.
|
||||
func TestPQFallback(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, myUdp, theirUdp, r := newPQPair(t, pqConfig(true, true, false), nil)
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Positive(t, tally.pq, "a PQ attempt comes first")
|
||||
assert.Positive(t, tally.classical, "then a classical one")
|
||||
|
||||
assertHostInfoPair(t, myUdp, theirUdp, myVpn, theirVpn, myControl, theirControl)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true), "the losing PQ attempt's index must be released")
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQResendFreshSymbols loses the responder's whole first msg2. The
|
||||
// initiator's next PQ attempt offers fresh msg1 symbols, the responder
|
||||
// recognises the repeat and resends msg2 with symbols it has not sent before.
|
||||
func TestPQResendFreshSymbols(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var firstMsg2, freshMsg2, freshMsg1 int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(10*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
h, fh := handshakeOf(p)
|
||||
switch {
|
||||
case h != nil && fh == nil:
|
||||
// Keep the classical fallback out of the way.
|
||||
return router.Drop
|
||||
case fh != nil && h.MessageCounter == 2 && fh.Index < 4:
|
||||
firstMsg2++
|
||||
return router.Drop
|
||||
case fh != nil && h.MessageCounter == 2:
|
||||
freshMsg2++
|
||||
case fh != nil && h.MessageCounter == 1 && fh.Index >= 4:
|
||||
freshMsg1++
|
||||
}
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Equal(t, 4, firstMsg2, "the first msg2 is 2 data and 2 repair fragments")
|
||||
assert.Positive(t, freshMsg1, "the retry offers fresh msg1 symbols")
|
||||
assert.Positive(t, freshMsg2, "the resend offers fresh msg2 symbols")
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQSticky checks a sticky initiator never offers a classical handshake to a
|
||||
// peer it has already completed a PQ handshake with.
|
||||
func TestPQSticky(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, pqConfig(true, true, true), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
theirControl.GetFromTun(true)
|
||||
|
||||
t.Log("Rehandshake while an attacker drops every PQ packet")
|
||||
var tally handshakeTally
|
||||
myControl.ReHandshake(theirVpn[0].Addr())
|
||||
r.RouteForAllExitFuncOrTimeout(time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if h, _ := handshakeOf(p); h != nil && h.Subtype == header.HandshakeIXPSK2MLKEM1024 {
|
||||
return router.Drop
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
assert.Positive(t, tally.pq, "PQ attempts keep being made")
|
||||
assert.Zero(t, tally.classical, "sticky must never fall back")
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
func TestPQRelays(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
useRelays := pqConfig(true, true, false)
|
||||
useRelays["relay"] = m{"use_relays": true}
|
||||
amRelay := pqConfig(true, true, false)
|
||||
amRelay["relay"] = m{"am_relay": true}
|
||||
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version1, ca, caKey, "me ", "10.128.0.1/24", useRelays)
|
||||
relayControl, relayVpnIpNet, relayUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "relay ", "10.128.0.128/24", amRelay)
|
||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "them ", "10.128.0.2/24", useRelays)
|
||||
|
||||
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()
|
||||
|
||||
var tally handshakeTally
|
||||
var relayedPQ, relayedClassical int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(10*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
outer := &header.H{}
|
||||
if outer.Parse(p.Data) == nil && outer.Type == header.Message && outer.Subtype == header.MessageRelay {
|
||||
if h, fh := handshakeOf(p); h != nil && fh != nil {
|
||||
relayedPQ++
|
||||
assert.LessOrEqual(t, len(p.Data), fragment.MaxPacketLen+32, "a relayed fragment fits the IPv6 minimum MTU")
|
||||
} else if h != nil {
|
||||
relayedClassical++
|
||||
}
|
||||
}
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), 80, 80)
|
||||
assert.Positive(t, relayedPQ, "the end to end handshake is PQ through the relay")
|
||||
assert.Zero(t, relayedClassical, "the relay coming up carries the PQ attempt, not the classical retry")
|
||||
r.RenderHostmaps("Final hostmaps", myControl, relayControl, theirControl)
|
||||
|
||||
myControl.Stop()
|
||||
relayControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQTimeoutReleasesIndexes lets a handshake with both a PQ and a classical
|
||||
// attempt pending time out, and checks neither index is left behind.
|
||||
func TestPQTimeoutReleasesIndexes(t *testing.T) {
|
||||
t.Parallel()
|
||||
mine := pqConfig(true, true, false)
|
||||
mine["handshakes"].(m)["retries"] = 2
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, mine, pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
r.RouteForAllExitFuncOrTimeout(1500*time.Millisecond, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
return router.Drop
|
||||
})
|
||||
|
||||
assert.Positive(t, tally.pq)
|
||||
assert.Positive(t, tally.classical)
|
||||
assert.Nil(t, myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), true), "the handshake should have timed out")
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true))
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQCookieUnderLoad floods the responder with msg1 fragments from spoofed
|
||||
// sources until it demands cookies, then checks a real initiator picks up the
|
||||
// cookie and still completes a PQ handshake.
|
||||
func TestPQCookieUnderLoad(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, _, theirUdp, r := newPQPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
// Half of the 1024 entry table is the cookie threshold. Stopping exactly there
|
||||
// keeps them from answering the spoofed sources, which the router cannot reach.
|
||||
t.Log("Flood them with the first fragment of msg1s nobody will finish")
|
||||
for i := range 512 {
|
||||
from := netip.AddrPortFrom(netip.AddrFrom4([4]byte{198, 18, byte(i >> 8), byte(i)}), 4242)
|
||||
s, err := fragment.NewSender(make([]byte, 2000), header.HandshakeIXPSK2MLKEM1024, 0, 1, uint32(i+1))
|
||||
require.NoError(t, err)
|
||||
pkts, _, err := s.Attempt(0)
|
||||
require.NoError(t, err)
|
||||
theirControl.InjectUDPPacket(&udp.Packet{From: from, To: theirUdp, Data: pkts[0]})
|
||||
}
|
||||
|
||||
var tally handshakeTally
|
||||
var cookieReplies, msg2, withCookie int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if h, fh := handshakeOf(p); h != nil && h.Subtype == header.HandshakeIXPSK2MLKEM1024 {
|
||||
switch {
|
||||
case h.MessageCounter == 0:
|
||||
cookieReplies++
|
||||
case h.MessageCounter == 2:
|
||||
msg2++
|
||||
case fh != nil && fh.HasCookie():
|
||||
withCookie++
|
||||
}
|
||||
}
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Positive(t, cookieReplies, "a loaded responder asks for a cookie")
|
||||
assert.Positive(t, withCookie, "the initiator resends with it")
|
||||
assert.Positive(t, msg2, "and the handshake completes post-quantum")
|
||||
assert.Zero(t, tally.classical, "the cookie round trip beats the classical fallback")
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQRequire checks require mode never handshakes classically, in either
|
||||
// direction.
|
||||
func TestPQRequire(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("initiator", func(t *testing.T) {
|
||||
// They neither speak PQ nor require it; we never fall back.
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, pqRequire(), nil)
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
r.RouteForAllExitFuncOrTimeout(time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
return router.KeepRouting
|
||||
})
|
||||
assert.Positive(t, tally.pq)
|
||||
assert.Zero(t, tally.classical)
|
||||
assert.Nil(t, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false), "no tunnel without PQ")
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
|
||||
t.Run("responder", func(t *testing.T) {
|
||||
// We only speak classical; they refuse it.
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, nil, pqRequire())
|
||||
defer r.RenderFlow()
|
||||
|
||||
var answers int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
r.RouteForAllExitFuncOrTimeout(time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if h, _ := handshakeOf(p); h != nil && h.MessageCounter == 2 {
|
||||
answers++
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
assert.Zero(t, answers, "a classical msg1 gets no answer")
|
||||
assert.Nil(t, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false))
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
|
||||
t.Run("both", func(t *testing.T) {
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newPQPair(t, pqRequire(), pqRequire())
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Zero(t, tally.classical)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
}
|
||||
Vendored
-1362
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -129,7 +129,7 @@ func TestCertUpgrade(t *testing.T) {
|
||||
}
|
||||
|
||||
r.Logf("reload new v2-only config")
|
||||
err = myC.ReloadConfigString(string(cb)).Err
|
||||
err = myC.ReloadConfigString(string(cb))
|
||||
assert.NoError(t, err)
|
||||
r.Log("yay, spin until their sees it")
|
||||
waitStart := time.Now()
|
||||
@@ -222,7 +222,7 @@ func TestCertDowngrade(t *testing.T) {
|
||||
}
|
||||
|
||||
r.Logf("reload new v1-only config")
|
||||
err = myC.ReloadConfigString(string(cb)).Err
|
||||
err = myC.ReloadConfigString(string(cb))
|
||||
assert.NoError(t, err)
|
||||
r.Log("yay, spin until their sees it")
|
||||
waitStart := time.Now()
|
||||
|
||||
+32
-74
@@ -8,7 +8,6 @@ pki:
|
||||
cert: /etc/nebula/host.crt
|
||||
key: /etc/nebula/host.key
|
||||
# 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:
|
||||
# - c99d4e650533b92061b09918e838a5a0a6aaee21eed1d12fd937682865936c72
|
||||
# disconnect_invalid is a toggle to force a client to be disconnected if the certificate is expired or invalid.
|
||||
@@ -44,7 +43,7 @@ static_host_map:
|
||||
|
||||
lighthouse:
|
||||
# am_lighthouse is used to enable lighthouse functionality for a node. This should ONLY be true on nodes
|
||||
# you have configured to be lighthouses in your network. Not reloadable.
|
||||
# you have configured to be lighthouses in your network
|
||||
am_lighthouse: false
|
||||
# serve_dns optionally starts a dns listener that responds to various queries and can even be
|
||||
# delegated to for resolution
|
||||
@@ -127,9 +126,8 @@ lighthouse:
|
||||
# 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.
|
||||
listen:
|
||||
# To listen on only ipv4, use "0.0.0.0". Not reloadable.
|
||||
# To listen on only ipv4, use "0.0.0.0"
|
||||
host: "::"
|
||||
# Not reloadable.
|
||||
port: 4242
|
||||
# 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
|
||||
@@ -137,8 +135,7 @@ listen:
|
||||
# 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
|
||||
# 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
|
||||
# Linux only. 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)
|
||||
# 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
|
||||
@@ -182,7 +179,7 @@ listen:
|
||||
# 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
|
||||
# device and SO_REUSEPORT on the UDP socket to allow multiple queues.
|
||||
# This option is only supported on Linux. Not reloadable.
|
||||
# This option is only supported on Linux.
|
||||
#routines: 1
|
||||
|
||||
punchy:
|
||||
@@ -206,7 +203,6 @@ punchy:
|
||||
|
||||
# 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!
|
||||
# Not reloadable.
|
||||
#cipher: aes
|
||||
|
||||
# Preferred ranges is used to define a hint about the local network ranges, which speeds up discovering the fastest
|
||||
@@ -233,57 +229,12 @@ punchy:
|
||||
# Trusted SSH CA public keys. These are the public keys of the CAs that are allowed to sign SSH keys for access.
|
||||
#trusted_cas:
|
||||
#- "ssh public key string"
|
||||
|
||||
# Local APIs allow accessing running nebula state.
|
||||
#local_api:
|
||||
# There are two types of sockets available: a control socket intended for use on the
|
||||
# local machine, primarily for debugging, and an info socket intended to make
|
||||
# nebula's internal state available to other consumers.
|
||||
#
|
||||
# The control socket is made available by default, and can be accessed via
|
||||
# `nebula ctl <command>`. It defaults to /var/run/nebula/ctl.sock on Linux, macOS and
|
||||
# the BSDs; on Windows it is a named pipe under \\.\pipe\ProtectedPrefix\Administrators.
|
||||
#control:
|
||||
# Set to false to turn the control socket off. Reloadable.
|
||||
#enabled: true
|
||||
# The absolute path where the control socket should live, or a full pipe name on
|
||||
# Windows. The last directory is created if missing, and must be owned by root or by
|
||||
# the user running nebula. It must not be writable by anyone else.
|
||||
#socket: /var/run/nebula/ctl.sock
|
||||
# A group (or account/group/SID on Windows) that should be allowed to access the
|
||||
# socket.
|
||||
#group: nebula
|
||||
|
||||
# The info socket is not made available by default. If you enable it, it makes some
|
||||
# internal state available over HTTP.
|
||||
#
|
||||
# The currently supported HTTP requests are:
|
||||
# GET /v1/identity?address=<vpn addr>[:port] the host owning the address; the port
|
||||
# is ignored. 404 when no tunnel is
|
||||
# up, 400 when no address is given.
|
||||
# GET /v1/whoami this node's identity
|
||||
# GET /v1/print-cert?address=<vpn addr>[:port]&raw=true
|
||||
# the certificate for the specified
|
||||
# address, as {"pem": ...}.
|
||||
# GET /v1 describes what is served
|
||||
#
|
||||
# NB: unless a connection arrived on the nebula interface, there's no guarantee
|
||||
# that the identity returned belongs to the sender.
|
||||
#
|
||||
#info:
|
||||
#enabled: false
|
||||
# The absolute path to listen on, or a full pipe name on Windows. Name a pipe under
|
||||
# \\.\pipe\ProtectedPrefix\Administrators\.
|
||||
#socket: /var/run/nebula/info.sock
|
||||
# A group (or account/group/SID on Windows) that should be allowed to access the
|
||||
# socket. On Windows the group may read and write the pipe but not create an
|
||||
# instance of it, so a client in the group must open the pipe asking for read and
|
||||
# write data rather than generic read and write.
|
||||
#group: nebula-info
|
||||
# Octal mode for the socket, as a quoted string. Defaults to "0600" unless a
|
||||
# group is set, in which case it defaults to "0660". On Windows a pipe has no
|
||||
# mode and this is ignored; the group alone decides who may connect.
|
||||
#socket_mode: "0660"
|
||||
# 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.
|
||||
relay:
|
||||
@@ -302,25 +253,19 @@ relay:
|
||||
# Configure the private interface. Note: addr is baked into the nebula certificate
|
||||
tun:
|
||||
# When tun is disabled, a lighthouse can be started without a local tun interface (and therefore without root)
|
||||
# Not reloadable.
|
||||
disabled: false
|
||||
# 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 OpenBSD and NetBSD: if set, must be in the form `tun[0-9]+`, otherwise the first free one is used.
|
||||
# Not reloadable.
|
||||
# For NetBSD: Required to be set, must be in the form `tun[0-9]+`
|
||||
dev: nebula1
|
||||
# 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
|
||||
# Toggles forwarding of multicast packets. Not reloadable.
|
||||
# Toggles forwarding of multicast packets
|
||||
drop_multicast: false
|
||||
# Sets the transmit queue length, if you notice lots of transmit drops on the tun it may help to raise this number. Default is 5000
|
||||
# Not reloadable.
|
||||
tx_queue: 5000
|
||||
# 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
|
||||
|
||||
# the use_offloads setting controls if Nebula will attempt to enable GSO and GRO for the tun device. Linux only, not reloadable.
|
||||
@@ -382,9 +327,6 @@ tun:
|
||||
# `mtu`: will default to tun mtu if this option is not specified
|
||||
# `metric`: will default to 0 if this option is not specified
|
||||
# `install`: will default to true, controls whether this route is installed in the systems routing table.
|
||||
# On macOS, a route whose destination another interface already routes, like the local network, is installed once
|
||||
# that route is removed. One deleted by hand stays deleted until nebula reloads or restarts, or until another
|
||||
# interface routes its destination and lets it go.
|
||||
# This setting is reloadable.
|
||||
unsafe_routes:
|
||||
#- route: 172.16.1.0/24
|
||||
@@ -416,7 +358,7 @@ tun:
|
||||
#use_system_route_table: false
|
||||
# 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.
|
||||
# SO_RCVBUFFORCE is used to avoid having to raise the system wide max. Not reloadable.
|
||||
# SO_RCVBUFFORCE is used to avoid having to raise the system wide max
|
||||
#use_system_route_table_buffer_size: 0
|
||||
|
||||
# Configure logging level
|
||||
@@ -466,18 +408,34 @@ logging:
|
||||
# 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
|
||||
# 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
|
||||
#retries: 20
|
||||
|
||||
# query_buffer is the size of the buffer channel for querying lighthouses, drops are recorded in the lighthouse.query.dropped metric.
|
||||
# Not reloadable.
|
||||
#query_buffer: 1024
|
||||
|
||||
# trigger_buffer is the size of the buffer channel for quickly sending handshakes
|
||||
# after receiving the response for lighthouse queries. Not reloadable.
|
||||
# after receiving the response for lighthouse queries
|
||||
#trigger_buffer: 64
|
||||
|
||||
# pq enables handshakes that mix an ephemeral ML-KEM-1024 key exchange into the session keys, protecting
|
||||
# recorded traffic against a future quantum computer. Authentication is unchanged. These handshakes are too
|
||||
# large for one packet and travel as fragments with forward error correction.
|
||||
#pq:
|
||||
# initiate starts post-quantum handshakes. Attempts alternate between post-quantum and classical until one is
|
||||
# answered, so peers that do not support them still connect.
|
||||
#initiate: false
|
||||
# accept answers post-quantum handshakes from peers.
|
||||
#accept: false
|
||||
# require makes every handshake post-quantum: it implies initiate and accept, never offers a classical handshake
|
||||
# and refuses classical handshakes from peers. Only enable it once every host can speak post-quantum handshakes.
|
||||
#require: false
|
||||
# sticky never falls back to a classical handshake with a peer that has completed a post-quantum one since
|
||||
# nebula started, which defeats an attacker who drops post-quantum handshakes to force a downgrade.
|
||||
#sticky: false
|
||||
# repair_delay is how long the forward error correction fragments trail the rest of a handshake message.
|
||||
#repair_delay: 10ms
|
||||
|
||||
# Tunnel manager settings
|
||||
#tunnels:
|
||||
# drop_inactive controls whether inactive tunnels are maintained or dropped after the inactive_timeout period has
|
||||
|
||||
+4
-38
@@ -60,18 +60,12 @@ type Firewall struct {
|
||||
|
||||
// assignedNetworks is a list of vpn networks assigned to us in the certificate.
|
||||
assignedNetworks []netip.Prefix
|
||||
// vpnNetworks holds assignedNetworks for lookup: a source address inside one of them
|
||||
// belongs to a node of the overlay, and only that node may send as it.
|
||||
vpnNetworks *bart.Lite
|
||||
// unsafeNetworks is the list of unsafe networks issued to us in the certificate
|
||||
unsafeNetworks []netip.Prefix
|
||||
|
||||
rules string
|
||||
rulesVersion uint16
|
||||
|
||||
// source is the rendered firewall config this firewall was built from, the cert networks are kept above
|
||||
source string
|
||||
|
||||
defaultLocalCIDRAny bool
|
||||
incomingMetrics firewallMetrics
|
||||
outgoingMetrics firewallMetrics
|
||||
@@ -159,12 +153,10 @@ func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Dur
|
||||
}
|
||||
|
||||
routableNetworks := new(bart.Lite)
|
||||
vpnNetworks := new(bart.Lite)
|
||||
var assignedNetworks []netip.Prefix
|
||||
for _, network := range c.Networks() {
|
||||
nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
|
||||
routableNetworks.Insert(nprefix)
|
||||
vpnNetworks.Insert(network)
|
||||
assignedNetworks = append(assignedNetworks, network)
|
||||
}
|
||||
|
||||
@@ -185,7 +177,6 @@ func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Dur
|
||||
DefaultTimeout: defaultTimeout,
|
||||
routableNetworks: routableNetworks,
|
||||
assignedNetworks: assignedNetworks,
|
||||
vpnNetworks: vpnNetworks,
|
||||
unsafeNetworks: unsafeNetworks,
|
||||
l: l,
|
||||
|
||||
@@ -212,25 +203,11 @@ func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewal
|
||||
panic("No certificate available to reconfigure the firewall")
|
||||
}
|
||||
|
||||
tcpTimeout := c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12)
|
||||
udpTimeout := c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3)
|
||||
defaultTimeout := c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10)
|
||||
|
||||
if tcpTimeout <= 0 {
|
||||
return nil, fmt.Errorf("firewall.conntrack.tcp_timeout must be greater than 0, got: %s", tcpTimeout)
|
||||
}
|
||||
if udpTimeout <= 0 {
|
||||
return nil, fmt.Errorf("firewall.conntrack.udp_timeout must be greater than 0, got: %s", udpTimeout)
|
||||
}
|
||||
if defaultTimeout <= 0 {
|
||||
return nil, fmt.Errorf("firewall.conntrack.default_timeout must be greater than 0, got: %s", defaultTimeout)
|
||||
}
|
||||
|
||||
fw := NewFirewall(
|
||||
l,
|
||||
tcpTimeout,
|
||||
udpTimeout,
|
||||
defaultTimeout,
|
||||
c.GetDuration("firewall.conntrack.tcp_timeout", time.Minute*12),
|
||||
c.GetDuration("firewall.conntrack.udp_timeout", time.Minute*3),
|
||||
c.GetDuration("firewall.conntrack.default_timeout", time.Minute*10),
|
||||
certificate,
|
||||
//TODO: max_connections
|
||||
)
|
||||
@@ -269,7 +246,6 @@ func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewal
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fw.source = c.Render("firewall")
|
||||
return fw, nil
|
||||
}
|
||||
|
||||
@@ -468,17 +444,7 @@ func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *
|
||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||
return ErrPeerRejected // reject for now, one day this may have different FW rules
|
||||
case NetworkTypeUnsafe:
|
||||
// An unsafe network says what a peer routes for, never who it is. One that
|
||||
// overlaps our own networks would let the peer send as any node of the overlay,
|
||||
// and whatever trusts the source address, the firewall's own rules and the
|
||||
// identity a program looks up for it, would be told the wrong node. A source
|
||||
// inside our networks is a node's own address, which only that node sends
|
||||
// from, as NetworkTypeVPN, matched first; through an unsafe network it is
|
||||
// refused. Outbound the address is a destination and claims nothing.
|
||||
if incoming && f.vpnNetworks.Contains(fp.RemoteAddr) {
|
||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||
return ErrInvalidRemoteIP
|
||||
}
|
||||
break // nothing special, one day this may have different FW rules
|
||||
default:
|
||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||
return ErrUnknownNetworkType //should never happen
|
||||
|
||||
@@ -58,31 +58,6 @@ func TestNewFirewall(t *testing.T) {
|
||||
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||
}
|
||||
|
||||
func TestNewFirewall_ZeroOrNegativeTimeout(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
c := &dummyCert{}
|
||||
cs := &CertState{v2Cert: c, initiatingVersion: cert.Version2}
|
||||
|
||||
cases := map[string]string{
|
||||
"tcp_timeout zero": "firewall:\n conntrack:\n tcp_timeout: 0s\n",
|
||||
"tcp_timeout negative": "firewall:\n conntrack:\n tcp_timeout: -5s\n",
|
||||
"udp_timeout zero": "firewall:\n conntrack:\n udp_timeout: 0s\n",
|
||||
"udp_timeout negative": "firewall:\n conntrack:\n udp_timeout: -5s\n",
|
||||
"default_timeout zero": "firewall:\n conntrack:\n default_timeout: 0s\n",
|
||||
"default_timeout negative": "firewall:\n conntrack:\n default_timeout: -5s\n",
|
||||
}
|
||||
|
||||
for name, cfgStr := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
cfg := config.NewC(l)
|
||||
require.NoError(t, cfg.LoadString(cfgStr))
|
||||
_, err := NewFirewallFromConfig(l, cs, cfg)
|
||||
require.Error(t, err, "expected error for non-positive timeout duration")
|
||||
assert.ErrorContains(t, err, "must be greater than 0")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirewall_AddRule(t *testing.T) {
|
||||
ob := &bytes.Buffer{}
|
||||
l := test.NewLoggerWithOutput(ob)
|
||||
@@ -277,58 +252,6 @@ func TestFirewall_Drop(t *testing.T) {
|
||||
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||
}
|
||||
|
||||
// TestFirewall_DropOverlaySourceThroughUnsafeNetwork: a peer whose unsafe network
|
||||
// overlaps our overlay may not send as another node of it. Its own address and sources
|
||||
// outside the overlay still pass through the unsafe network, and outbound to such an
|
||||
// address, where the address is a destination, is not the firewall's to refuse here.
|
||||
func TestFirewall_DropOverlaySourceThroughUnsafeNetwork(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
myVpnNetworksTable := new(bart.Lite)
|
||||
myVpnNetworksTable.Insert(netip.MustParsePrefix("1.2.3.0/24"))
|
||||
|
||||
me := dummyCert{name: "me", networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")}}
|
||||
// A router for 1.2.0.0/16, which contains the whole overlay.
|
||||
peer := dummyCert{
|
||||
name: "router",
|
||||
networks: []netip.Prefix{netip.MustParsePrefix("1.2.3.9/24")},
|
||||
unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("1.2.0.0/16")},
|
||||
groups: []string{"default-group"},
|
||||
}
|
||||
h := HostInfo{
|
||||
ConnectionState: &ConnectionState{
|
||||
peerCert: &cert.CachedCertificate{Certificate: &peer, InvertedGroups: map[string]struct{}{"default-group": {}}},
|
||||
},
|
||||
vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.9")},
|
||||
}
|
||||
h.buildNetworks(myVpnNetworksTable, &peer)
|
||||
|
||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, &me)
|
||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||
cp := cert.NewCAPool()
|
||||
packet := func(remote string) firewall.Packet {
|
||||
return firewall.Packet{
|
||||
LocalAddr: netip.MustParseAddr("1.2.3.4"),
|
||||
RemoteAddr: netip.MustParseAddr(remote),
|
||||
LocalPort: 10,
|
||||
RemotePort: 90,
|
||||
Protocol: iputil.IPProtocolUDP,
|
||||
}
|
||||
}
|
||||
|
||||
// Another node's overlay address, through the unsafe network: refused.
|
||||
assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(packet("1.2.3.10"), true, &h, cp, nil))
|
||||
assert.Equal(t, int64(1), fw.incomingMetrics.droppedRemoteAddr.Count())
|
||||
|
||||
// The peer's own address, and an address outside the overlay it routes for: served.
|
||||
require.NoError(t, fw.Drop(packet("1.2.3.9"), true, &h, cp, nil))
|
||||
require.NoError(t, fw.Drop(packet("1.2.5.5"), true, &h, cp, nil))
|
||||
|
||||
// Outbound to the overlay address via the router is not refused here; it meets the
|
||||
// outbound rules as before.
|
||||
resetConntrack(fw)
|
||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(packet("1.2.3.10"), false, &h, cp, nil))
|
||||
}
|
||||
|
||||
func TestFirewall_DropV6(t *testing.T) {
|
||||
ob := &bytes.Buffer{}
|
||||
l := test.NewLoggerWithOutput(ob)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
module github.com/slackhq/nebula
|
||||
|
||||
go 1.27.2
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.2
|
||||
filippo.io/bigmod v0.1.0
|
||||
github.com/DefinedNet/netlink v1.3.2-dn.1
|
||||
github.com/Microsoft/go-winio v0.6.2
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
|
||||
github.com/armon/go-radix v1.0.0
|
||||
github.com/flynn/noise v1.1.0
|
||||
github.com/gaissmai/bart v0.29.0
|
||||
github.com/gogo/protobuf v1.3.2
|
||||
@@ -33,7 +33,7 @@ require (
|
||||
golang.zx2c4.com/wireguard/windows v1.0.1
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980
|
||||
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -45,6 +45,5 @@ require (
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/time v0.5.0 // indirect
|
||||
)
|
||||
@@ -5,8 +5,6 @@ filippo.io/bigmod v0.1.0 h1:UNzDk7y9ADKST+axd9skUpBQeW7fG2KrTZyOE4uGQy8=
|
||||
filippo.io/bigmod v0.1.0/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
|
||||
github.com/DefinedNet/netlink v1.3.2-dn.1 h1:Md2PsUE1Xuy1Zxs/Bm6356n1kt5bq2HspXlPJ6pEspg=
|
||||
github.com/DefinedNet/netlink v1.3.2-dn.1/go.mod h1:o4YSn8Jw7zoDcYXDmV77TRd4eS5sSLuE+vu2zAN67C8=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
@@ -14,6 +12,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/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/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 v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -157,8 +157,6 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc h1:TS73t7x3KarrNd5qAipmspBDS1rkMcgVG/fS1aRb4Rc=
|
||||
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/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
@@ -205,8 +203,8 @@ 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.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
@@ -245,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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980 h1:ribyrTYQ/QYeUIs8x8bVLYwGyepa7RnHLqJzegT5YYk=
|
||||
gvisor.dev/gvisor v0.0.0-20261014193016-04d31b385980/go.mod h1:pK/dapF5Bf3KGW7/kd5CI5IC4lYh9FMFY1qETAIGLXk=
|
||||
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe h1:fre4i6mv4iBuz5lCMOzHD1rH1ljqHWSICFmZRbbgp3g=
|
||||
gvisor.dev/gvisor v0.0.0-20240423190808-9d7a357edefe/go.mod h1:sxc3Uvk/vHcd3tj7/DHVBoR5wvWT/MmRq2pj7HRJnwU=
|
||||
@@ -35,7 +35,9 @@ func NewCredential(
|
||||
}
|
||||
|
||||
// buildHandshakeState creates a noise.HandshakeState from this credential.
|
||||
func (hc *Credential) buildHandshakeState(initiator bool, pattern noise.HandshakePattern) (*noise.HandshakeState, error) {
|
||||
// pskPlacement selects the noise psk modifier; 0 means none. A psk for
|
||||
// placements 2 and up is supplied later with SetPresharedKey.
|
||||
func (hc *Credential) buildHandshakeState(initiator bool, pattern noise.HandshakePattern, pskPlacement int) (*noise.HandshakeState, error) {
|
||||
return noise.NewHandshakeState(noise.Config{
|
||||
CipherSuite: hc.cipherSuite,
|
||||
Random: rand.Reader,
|
||||
@@ -43,7 +45,7 @@ func (hc *Credential) buildHandshakeState(initiator bool, pattern noise.Handshak
|
||||
Initiator: initiator,
|
||||
StaticKeypair: noise.DHKey{Private: hc.privateKey, Public: hc.Cert.PublicKey()},
|
||||
PresharedKey: []byte{},
|
||||
PresharedKeyPlacement: 0,
|
||||
PresharedKeyPlacement: pskPlacement,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
// Package fec implements the systematic Reed-Solomon erasure code used to carry
|
||||
// handshake messages that do not fit in a single UDP packet.
|
||||
//
|
||||
// A message is split into K equally sized data symbols (the last one zero
|
||||
// padded). Symbol indexes 0..K-1 are the data symbols themselves; indexes
|
||||
// K..MaxSymbols-1 are repair symbols. Any K distinct symbols reconstruct the
|
||||
// message. Repair symbols are generated on demand, so a sender can emit fresh
|
||||
// ones on every retransmit and a receiver can merge everything it has seen.
|
||||
package fec
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// MaxSymbols is the number of distinct symbols, data and repair together, one
|
||||
// message can be encoded into. It is bounded by the size of GF(2^8).
|
||||
const MaxSymbols = 256
|
||||
|
||||
var (
|
||||
ErrInvalidLayout = errors.New("invalid fec layout")
|
||||
ErrIndexRange = errors.New("symbol index out of range")
|
||||
ErrSymbolSize = errors.New("symbol has the wrong size")
|
||||
ErrNotEnough = errors.New("not enough symbols to decode")
|
||||
ErrCorrupt = errors.New("decoded message has non-zero padding")
|
||||
)
|
||||
|
||||
// Layout describes how a message is split into symbols. Both ends derive it
|
||||
// from the message length alone, so it never has to be sent.
|
||||
type Layout struct {
|
||||
MsgLen int // length of the message in bytes
|
||||
K int // number of data symbols
|
||||
SymbolSize int // size of every symbol, data and repair
|
||||
}
|
||||
|
||||
// NewLayout returns the layout for a message of msgLen bytes carried in symbols
|
||||
// of at most maxSymbolSize bytes. Symbols are balanced, so padding is always
|
||||
// less than K bytes.
|
||||
func NewLayout(msgLen, maxSymbolSize int) (Layout, error) {
|
||||
if msgLen <= 0 || maxSymbolSize <= 0 {
|
||||
return Layout{}, ErrInvalidLayout
|
||||
}
|
||||
k := (msgLen + maxSymbolSize - 1) / maxSymbolSize
|
||||
if k >= MaxSymbols {
|
||||
return Layout{}, fmt.Errorf("%w: %d data symbols", ErrInvalidLayout, k)
|
||||
}
|
||||
return Layout{
|
||||
MsgLen: msgLen,
|
||||
K: k,
|
||||
SymbolSize: (msgLen + k - 1) / k,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Encoder produces symbols for one message.
|
||||
type Encoder struct {
|
||||
layout Layout
|
||||
data [][]byte
|
||||
}
|
||||
|
||||
// NewEncoder copies msg into padded data symbols.
|
||||
func NewEncoder(msg []byte, maxSymbolSize int) (*Encoder, error) {
|
||||
l, err := NewLayout(len(msg), maxSymbolSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf := make([]byte, l.K*l.SymbolSize)
|
||||
copy(buf, msg)
|
||||
data := make([][]byte, l.K)
|
||||
for i := range data {
|
||||
data[i] = buf[i*l.SymbolSize : (i+1)*l.SymbolSize]
|
||||
}
|
||||
return &Encoder{layout: l, data: data}, nil
|
||||
}
|
||||
|
||||
func (e *Encoder) Layout() Layout {
|
||||
return e.layout
|
||||
}
|
||||
|
||||
// Symbol appends the symbol with the given index to dst and returns the result.
|
||||
func (e *Encoder) Symbol(dst []byte, index int) ([]byte, error) {
|
||||
if index < 0 || index >= MaxSymbols {
|
||||
return nil, ErrIndexRange
|
||||
}
|
||||
if index < e.layout.K {
|
||||
return append(dst, e.data[index]...), nil
|
||||
}
|
||||
|
||||
start := len(dst)
|
||||
dst = append(dst, make([]byte, e.layout.SymbolSize)...)
|
||||
out := dst[start:]
|
||||
for col, d := range e.data {
|
||||
mulAdd(out, d, coefficient(index, col))
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
// Decoder collects symbols for one message until it can reconstruct it.
|
||||
// It stores at most K symbols, so its memory is bounded by the layout no matter
|
||||
// how many symbols arrive.
|
||||
type Decoder struct {
|
||||
layout Layout
|
||||
have [MaxSymbols]bool
|
||||
syms map[int][]byte
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder for a message of msgLen bytes that was encoded
|
||||
// with the same maxSymbolSize.
|
||||
func NewDecoder(msgLen, maxSymbolSize int) (*Decoder, error) {
|
||||
l, err := NewLayout(msgLen, maxSymbolSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Decoder{layout: l, syms: make(map[int][]byte, l.K)}, nil
|
||||
}
|
||||
|
||||
func (d *Decoder) Layout() Layout {
|
||||
return d.layout
|
||||
}
|
||||
|
||||
// Stored returns the number of symbols held.
|
||||
func (d *Decoder) Stored() int {
|
||||
return len(d.syms)
|
||||
}
|
||||
|
||||
// Has reports whether the symbol with the given index is held.
|
||||
func (d *Decoder) Has(index int) bool {
|
||||
return index >= 0 && index < MaxSymbols && d.have[index]
|
||||
}
|
||||
|
||||
// Ready reports whether enough symbols have arrived to decode.
|
||||
func (d *Decoder) Ready() bool {
|
||||
return len(d.syms) >= d.layout.K
|
||||
}
|
||||
|
||||
// Add stores a copy of the symbol. Duplicates, and anything beyond the first K
|
||||
// distinct symbols, are ignored. It returns whether the decoder is ready.
|
||||
func (d *Decoder) Add(index int, sym []byte) (bool, error) {
|
||||
if index < 0 || index >= MaxSymbols {
|
||||
return d.Ready(), ErrIndexRange
|
||||
}
|
||||
if len(sym) != d.layout.SymbolSize {
|
||||
return d.Ready(), ErrSymbolSize
|
||||
}
|
||||
if d.have[index] || d.Ready() {
|
||||
return d.Ready(), nil
|
||||
}
|
||||
d.have[index] = true
|
||||
d.syms[index] = append([]byte(nil), sym...)
|
||||
return d.Ready(), nil
|
||||
}
|
||||
|
||||
// Decode reconstructs the message from the stored symbols.
|
||||
func (d *Decoder) Decode() ([]byte, error) {
|
||||
if !d.Ready() {
|
||||
return nil, ErrNotEnough
|
||||
}
|
||||
l := d.layout
|
||||
|
||||
out := make([]byte, l.K*l.SymbolSize)
|
||||
var missing, repair []int
|
||||
for i := range l.K {
|
||||
if s, ok := d.syms[i]; ok {
|
||||
copy(out[i*l.SymbolSize:], s)
|
||||
} else {
|
||||
missing = append(missing, i)
|
||||
}
|
||||
}
|
||||
|
||||
if len(missing) > 0 {
|
||||
for i := l.K; i < MaxSymbols && len(repair) < len(missing); i++ {
|
||||
if d.have[i] {
|
||||
repair = append(repair, i)
|
||||
}
|
||||
}
|
||||
if len(repair) < len(missing) {
|
||||
return nil, ErrNotEnough
|
||||
}
|
||||
|
||||
// Each repair symbol r satisfies r = sum_col coefficient(r, col) * data[col].
|
||||
// Move the known data columns to the left hand side, leaving a square
|
||||
// Cauchy system in the missing columns.
|
||||
rhs := make([][]byte, len(repair))
|
||||
m := make([][]byte, len(repair))
|
||||
for ri, row := range repair {
|
||||
rhs[ri] = append([]byte(nil), d.syms[row]...)
|
||||
m[ri] = make([]byte, len(missing))
|
||||
mi := 0
|
||||
for col := range l.K {
|
||||
if mi < len(missing) && missing[mi] == col {
|
||||
m[ri][mi] = coefficient(row, col)
|
||||
mi++
|
||||
continue
|
||||
}
|
||||
mulAdd(rhs[ri], out[col*l.SymbolSize:(col+1)*l.SymbolSize], coefficient(row, col))
|
||||
}
|
||||
}
|
||||
if !invert(m) {
|
||||
// Unreachable for a Cauchy matrix; kept so a broken invariant fails loudly.
|
||||
return nil, errors.New("fec: singular decode matrix")
|
||||
}
|
||||
for mi, col := range missing {
|
||||
dst := out[col*l.SymbolSize : (col+1)*l.SymbolSize]
|
||||
for ri := range repair {
|
||||
mulAdd(dst, rhs[ri], m[mi][ri])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, b := range out[l.MsgLen:] {
|
||||
if b != 0 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
}
|
||||
return out[:l.MsgLen], nil
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package fec
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"math/rand/v2"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// slowMul is carry-less multiplication reduced by gfPoly, used to check the tables.
|
||||
func slowMul(a, b byte) byte {
|
||||
var p int
|
||||
x, y := int(a), int(b)
|
||||
for y > 0 {
|
||||
if y&1 != 0 {
|
||||
p ^= x
|
||||
}
|
||||
x <<= 1
|
||||
if x&0x100 != 0 {
|
||||
x ^= gfPoly
|
||||
}
|
||||
y >>= 1
|
||||
}
|
||||
return byte(p)
|
||||
}
|
||||
|
||||
func TestGF(t *testing.T) {
|
||||
for a := range 256 {
|
||||
for b := range 256 {
|
||||
require.Equal(t, slowMul(byte(a), byte(b)), gfMul(byte(a), byte(b)), "%d*%d", a, b)
|
||||
}
|
||||
if a != 0 {
|
||||
require.Equal(t, byte(1), gfMul(byte(a), gfInv(byte(a))), "inv(%d)", a)
|
||||
}
|
||||
}
|
||||
|
||||
src := make([]byte, 256)
|
||||
for i := range src {
|
||||
src[i] = byte(i)
|
||||
}
|
||||
for c := range 256 {
|
||||
dst := make([]byte, 256)
|
||||
mulAdd(dst, src, byte(c))
|
||||
for i := range src {
|
||||
require.Equal(t, gfMul(byte(c), src[i]), dst[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLayout(t *testing.T) {
|
||||
for msgLen := 1; msgLen <= 20000; msgLen++ {
|
||||
l, err := NewLayout(msgLen, 1176)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, (msgLen+1175)/1176, l.K)
|
||||
require.LessOrEqual(t, l.SymbolSize, 1176)
|
||||
require.GreaterOrEqual(t, l.K*l.SymbolSize, msgLen)
|
||||
require.Less(t, l.K*l.SymbolSize-msgLen, l.K, "padding must be less than one byte per symbol")
|
||||
}
|
||||
|
||||
l, err := NewLayout(65535, 1176)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 56, l.K)
|
||||
|
||||
_, err = NewLayout(0, 1176)
|
||||
require.ErrorIs(t, err, ErrInvalidLayout)
|
||||
_, err = NewLayout(100, 0)
|
||||
require.ErrorIs(t, err, ErrInvalidLayout)
|
||||
_, err = NewLayout(256, 1)
|
||||
require.ErrorIs(t, err, ErrInvalidLayout)
|
||||
_, err = NewLayout(255, 1)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func randMsg(r *rand.Rand, n int) []byte {
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = byte(r.Uint32())
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func decodeWith(t *testing.T, enc *Encoder, msgLen, maxSym int, indexes []int) []byte {
|
||||
t.Helper()
|
||||
dec, err := NewDecoder(msgLen, maxSym)
|
||||
require.NoError(t, err)
|
||||
for _, idx := range indexes {
|
||||
sym, err := enc.Symbol(nil, idx)
|
||||
require.NoError(t, err)
|
||||
_, err = dec.Add(idx, sym)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.True(t, dec.Ready())
|
||||
out, err := dec.Decode()
|
||||
require.NoError(t, err)
|
||||
return out
|
||||
}
|
||||
|
||||
// TestExhaustiveSubsets decodes every k-subset of the first k+m symbols for
|
||||
// small codes, which checks the MDS property directly.
|
||||
func TestExhaustiveSubsets(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(1, 2))
|
||||
const maxSym = 16
|
||||
for k := 1; k <= 10; k++ {
|
||||
for m := 1; m <= 5; m++ {
|
||||
msgLen := (k-1)*maxSym + 1 + r.IntN(maxSym)
|
||||
msg := randMsg(r, msgLen)
|
||||
enc, err := NewEncoder(msg, maxSym)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, k, enc.Layout().K)
|
||||
|
||||
n := k + m
|
||||
for mask := 0; mask < 1<<n; mask++ {
|
||||
var idx []int
|
||||
for i := range n {
|
||||
if mask&(1<<i) != 0 {
|
||||
idx = append(idx, i)
|
||||
}
|
||||
}
|
||||
if len(idx) != k {
|
||||
continue
|
||||
}
|
||||
require.Equal(t, msg, decodeWith(t, enc, msgLen, maxSym, idx), "k=%d m=%d idx=%v", k, m, idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRandomHighIndexes draws symbols from the whole index space, the shape
|
||||
// retransmits produce once fresh repair symbols are in play.
|
||||
func TestRandomHighIndexes(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(3, 4))
|
||||
for range 2000 {
|
||||
msgLen := 1 + r.IntN(65535)
|
||||
msg := randMsg(r, msgLen)
|
||||
enc, err := NewEncoder(msg, 1176)
|
||||
require.NoError(t, err)
|
||||
k := enc.Layout().K
|
||||
|
||||
idx := r.Perm(MaxSymbols)[:k]
|
||||
require.Equal(t, msg, decodeWith(t, enc, msgLen, 1176, idx), "k=%d idx=%v", k, idx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecoderBounds(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(5, 6))
|
||||
msg := randMsg(r, 3000)
|
||||
enc, err := NewEncoder(msg, 1176)
|
||||
require.NoError(t, err)
|
||||
l := enc.Layout()
|
||||
require.Equal(t, 3, l.K)
|
||||
require.Equal(t, 1000, l.SymbolSize)
|
||||
|
||||
dec, err := NewDecoder(3000, 1176)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = dec.Decode()
|
||||
require.ErrorIs(t, err, ErrNotEnough)
|
||||
|
||||
_, err = dec.Add(-1, make([]byte, 1000))
|
||||
require.ErrorIs(t, err, ErrIndexRange)
|
||||
_, err = dec.Add(MaxSymbols, make([]byte, 1000))
|
||||
require.ErrorIs(t, err, ErrIndexRange)
|
||||
_, err = dec.Add(0, make([]byte, 999))
|
||||
require.ErrorIs(t, err, ErrSymbolSize)
|
||||
|
||||
s5, _ := enc.Symbol(nil, 5)
|
||||
ready, err := dec.Add(5, s5)
|
||||
require.NoError(t, err)
|
||||
require.False(t, ready)
|
||||
|
||||
// A duplicate index is ignored, even with different contents.
|
||||
ready, err = dec.Add(5, make([]byte, 1000))
|
||||
require.NoError(t, err)
|
||||
require.False(t, ready)
|
||||
|
||||
s0, _ := enc.Symbol(nil, 0)
|
||||
s9, _ := enc.Symbol(nil, 9)
|
||||
_, err = dec.Add(0, s0)
|
||||
require.NoError(t, err)
|
||||
ready, err = dec.Add(9, s9)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ready)
|
||||
|
||||
// Symbols beyond K are not stored.
|
||||
ready, err = dec.Add(1, make([]byte, 1000))
|
||||
require.NoError(t, err)
|
||||
require.True(t, ready)
|
||||
require.Len(t, dec.syms, 3)
|
||||
|
||||
out, err := dec.Decode()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, msg, out)
|
||||
}
|
||||
|
||||
func TestCorruptPadding(t *testing.T) {
|
||||
// 3001 bytes in 3 symbols of 1001 leaves 2 bytes of padding in the last one.
|
||||
dec, err := NewDecoder(3001, 1176)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1001, dec.Layout().SymbolSize)
|
||||
|
||||
last := make([]byte, 1001)
|
||||
last[1000] = 1
|
||||
for i, s := range [][]byte{make([]byte, 1001), make([]byte, 1001), last} {
|
||||
_, err = dec.Add(i, s)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
_, err = dec.Decode()
|
||||
require.ErrorIs(t, err, ErrCorrupt)
|
||||
}
|
||||
|
||||
// TestKnownAnswer pins the encoding. Both ends of a handshake must produce
|
||||
// identical repair symbols, so any change here is a wire format change.
|
||||
func TestKnownAnswer(t *testing.T) {
|
||||
msg := make([]byte, 3000)
|
||||
for i := range msg {
|
||||
msg[i] = byte(i*7 + 3)
|
||||
}
|
||||
enc, err := NewEncoder(msg, 1176)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Cross-checked against an independent bit-serial GF(2^8) implementation.
|
||||
want := map[int]string{
|
||||
3: "52124f58276ec6338d3b3f4eed273bc7cabfe4f0f467928962b046ad1b348f50",
|
||||
4: "a50928b04738981985a7d4a17ffaf8d7e30014ca64fc53c99800ffb61aec4aa7",
|
||||
5: "ada4c95a7facbc542aaef584e6f0d081b7b0d0eed69ded03b57d0753a119cfc9",
|
||||
255: "839066cdf94f963b223fb1c1c1360f698c14f6349b25653ff5b521791a4021b1",
|
||||
}
|
||||
for idx, h := range want {
|
||||
sym, err := enc.Symbol(nil, idx)
|
||||
require.NoError(t, err)
|
||||
sum := sha256.Sum256(sym)
|
||||
assert.Equal(t, h, hex.EncodeToString(sum[:]), "symbol %d", idx)
|
||||
}
|
||||
}
|
||||
|
||||
func FuzzRoundTrip(f *testing.F) {
|
||||
f.Add([]byte("hello"), uint16(2), uint64(0))
|
||||
f.Add(make([]byte, 9000), uint16(1176), uint64(7))
|
||||
f.Fuzz(func(t *testing.T, msg []byte, maxSym uint16, seed uint64) {
|
||||
if len(msg) == 0 || maxSym == 0 {
|
||||
return
|
||||
}
|
||||
enc, err := NewEncoder(msg, int(maxSym))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
r := rand.New(rand.NewPCG(seed, seed))
|
||||
idx := r.Perm(MaxSymbols)[:enc.Layout().K]
|
||||
require.Equal(t, msg, decodeWith(t, enc, len(msg), int(maxSym), idx))
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzDecoder feeds arbitrary symbols to a decoder; it must never panic and
|
||||
// must either fail or return a message of the declared length.
|
||||
func FuzzDecoder(f *testing.F) {
|
||||
f.Add(uint16(3000), []byte{0, 5, 9, 200}, []byte("some symbol bytes"))
|
||||
f.Fuzz(func(t *testing.T, msgLen uint16, indexes []byte, fill []byte) {
|
||||
dec, err := NewDecoder(int(msgLen), 1176)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
size := dec.Layout().SymbolSize
|
||||
for i, idx := range indexes {
|
||||
sym := make([]byte, size)
|
||||
for j := range sym {
|
||||
if len(fill) > 0 {
|
||||
sym[j] = fill[(i+j)%len(fill)]
|
||||
}
|
||||
}
|
||||
if _, err := dec.Add(int(idx), sym); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
out, err := dec.Decode()
|
||||
if err == nil {
|
||||
require.Len(t, out, int(msgLen))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// BenchmarkRepair and BenchmarkDecode use a v3-sized msg2 (~9.8KB, k=9) with
|
||||
// three repair symbols, decoding with three data symbols missing.
|
||||
func BenchmarkRepair(b *testing.B) {
|
||||
msg := randMsg(rand.New(rand.NewPCG(7, 8)), 9800)
|
||||
enc, err := NewEncoder(msg, 1176)
|
||||
require.NoError(b, err)
|
||||
buf := make([]byte, 0, 1176)
|
||||
b.SetBytes(int64(len(msg)))
|
||||
for b.Loop() {
|
||||
for idx := 9; idx < 12; idx++ {
|
||||
buf, _ = enc.Symbol(buf[:0], idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDecode(b *testing.B) {
|
||||
msg := randMsg(rand.New(rand.NewPCG(7, 8)), 9800)
|
||||
enc, err := NewEncoder(msg, 1176)
|
||||
require.NoError(b, err)
|
||||
idx := []int{0, 1, 2, 3, 5, 6, 9, 10, 11}
|
||||
syms := make([][]byte, len(idx))
|
||||
for i, x := range idx {
|
||||
syms[i], _ = enc.Symbol(nil, x)
|
||||
}
|
||||
b.SetBytes(int64(len(msg)))
|
||||
for b.Loop() {
|
||||
dec, _ := NewDecoder(len(msg), 1176)
|
||||
for i, x := range idx {
|
||||
_, _ = dec.Add(x, syms[i])
|
||||
}
|
||||
if _, err := dec.Decode(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package fec
|
||||
|
||||
// Arithmetic over GF(2^8) with the reducing polynomial x^8+x^4+x^3+x^2+1 (0x11d).
|
||||
// Addition is XOR. Multiplication uses log/exp tables; the exp table is doubled so
|
||||
// the sum of two logs never needs reducing mod 255.
|
||||
|
||||
const gfPoly = 0x11d
|
||||
|
||||
var (
|
||||
gfExp [510]byte
|
||||
gfLog [256]byte
|
||||
)
|
||||
|
||||
func init() {
|
||||
x := 1
|
||||
for i := range 255 {
|
||||
gfExp[i] = byte(x)
|
||||
gfExp[i+255] = byte(x)
|
||||
gfLog[x] = byte(i)
|
||||
x <<= 1
|
||||
if x&0x100 != 0 {
|
||||
x ^= gfPoly
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func gfMul(a, b byte) byte {
|
||||
if a == 0 || b == 0 {
|
||||
return 0
|
||||
}
|
||||
return gfExp[int(gfLog[a])+int(gfLog[b])]
|
||||
}
|
||||
|
||||
// gfInv returns the multiplicative inverse of a. a must be non-zero.
|
||||
func gfInv(a byte) byte {
|
||||
return gfExp[255-int(gfLog[a])]
|
||||
}
|
||||
|
||||
// mulAdd computes dst ^= c*src element-wise. dst must be at least as long as src.
|
||||
func mulAdd(dst, src []byte, c byte) {
|
||||
switch c {
|
||||
case 0:
|
||||
return
|
||||
case 1:
|
||||
for i, s := range src {
|
||||
dst[i] ^= s
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var t [256]byte
|
||||
lc := int(gfLog[c])
|
||||
for s := 1; s < 256; s++ {
|
||||
t[s] = gfExp[int(gfLog[s])+lc]
|
||||
}
|
||||
for i, s := range src {
|
||||
dst[i] ^= t[s]
|
||||
}
|
||||
}
|
||||
|
||||
// coefficient returns the generator matrix entry for repair symbol index row and
|
||||
// data symbol index col. Repair rows are a Cauchy matrix 1/(x_row + y_col) with
|
||||
// x_row = row and y_col = col: rows are always >= k and columns < k so the two
|
||||
// sets are disjoint, which makes every square submatrix invertible and the
|
||||
// systematic code [I; C] MDS. A row depends only on its index, never on how many
|
||||
// repair symbols exist, so new repair symbols can be generated at any time.
|
||||
func coefficient(row, col int) byte {
|
||||
return gfInv(byte(row) ^ byte(col))
|
||||
}
|
||||
|
||||
// invert inverts the n x n matrix m in place with Gauss-Jordan elimination.
|
||||
// It returns false if m is singular.
|
||||
func invert(m [][]byte) bool {
|
||||
n := len(m)
|
||||
inv := make([][]byte, n)
|
||||
for i := range inv {
|
||||
inv[i] = make([]byte, n)
|
||||
inv[i][i] = 1
|
||||
}
|
||||
|
||||
for col := range n {
|
||||
pivot := -1
|
||||
for r := col; r < n; r++ {
|
||||
if m[r][col] != 0 {
|
||||
pivot = r
|
||||
break
|
||||
}
|
||||
}
|
||||
if pivot < 0 {
|
||||
return false
|
||||
}
|
||||
m[col], m[pivot] = m[pivot], m[col]
|
||||
inv[col], inv[pivot] = inv[pivot], inv[col]
|
||||
|
||||
scale := gfInv(m[col][col])
|
||||
for c := range n {
|
||||
m[col][c] = gfMul(m[col][c], scale)
|
||||
inv[col][c] = gfMul(inv[col][c], scale)
|
||||
}
|
||||
|
||||
for r := 0; r < n; r++ {
|
||||
if r == col || m[r][col] == 0 {
|
||||
continue
|
||||
}
|
||||
f := m[r][col]
|
||||
for c := range n {
|
||||
m[r][c] ^= gfMul(f, m[col][c])
|
||||
inv[r][c] ^= gfMul(f, inv[col][c])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
copy(m, inv)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package fragment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/slackhq/nebula/handshake/fec"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
// ErrMismatch is returned when a fragment disagrees with the message it claims to
|
||||
// belong to. The caller should discard the whole assembly.
|
||||
var ErrMismatch = errors.New("fragment does not match its message")
|
||||
|
||||
// Assembly collects the fragments of one incoming message. Its memory is bounded
|
||||
// by the message length: at most K symbols are kept however many arrive.
|
||||
//
|
||||
// An Assembly is not safe for concurrent use.
|
||||
type Assembly struct {
|
||||
fragID uint32
|
||||
msgLen uint16
|
||||
dec *fec.Decoder
|
||||
received int
|
||||
}
|
||||
|
||||
// NewAssembly starts an assembly for the message described by h. The fragment
|
||||
// itself still has to be passed to Add.
|
||||
func NewAssembly(h Header) (*Assembly, error) {
|
||||
dec, err := fec.NewDecoder(int(h.MsgLen), MaxSymbolSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Assembly{fragID: h.FragID, msgLen: h.MsgLen, dec: dec}, nil
|
||||
}
|
||||
|
||||
// Add records a fragment parsed by Parse. It returns true once enough symbols
|
||||
// are held to call Decode.
|
||||
func (a *Assembly) Add(h Header, sym []byte) (bool, error) {
|
||||
if h.FragID != a.fragID || h.MsgLen != a.msgLen {
|
||||
return a.dec.Ready(), ErrMismatch
|
||||
}
|
||||
a.received += header.Len + HeaderLen + len(sym)
|
||||
return a.dec.Add(int(h.Index), sym)
|
||||
}
|
||||
|
||||
// wouldStore returns how many bytes Add would retain for this fragment.
|
||||
func (a *Assembly) wouldStore(h Header, sym []byte) int {
|
||||
if h.FragID != a.fragID || h.MsgLen != a.msgLen || a.dec.Ready() || a.dec.Has(int(h.Index)) {
|
||||
return 0
|
||||
}
|
||||
return len(sym)
|
||||
}
|
||||
|
||||
// Decode reconstructs the message. It requires Add to have reported ready.
|
||||
func (a *Assembly) Decode() ([]byte, error) {
|
||||
return a.dec.Decode()
|
||||
}
|
||||
|
||||
// Stored returns the number of symbol bytes held.
|
||||
func (a *Assembly) Stored() int {
|
||||
return a.dec.Stored() * a.dec.Layout().SymbolSize
|
||||
}
|
||||
|
||||
// Received returns the number of packet bytes received for this message,
|
||||
// duplicates included. It is the basis for the amplification budget.
|
||||
func (a *Assembly) Received() int {
|
||||
return a.received
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
package fragment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const testSubtype = header.MessageSubType(9)
|
||||
|
||||
type testKey struct {
|
||||
src string
|
||||
fragID uint32
|
||||
}
|
||||
|
||||
func randMsg(r *rand.Rand, n int) []byte {
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = byte(r.Uint32())
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func testConfig() TableConfig {
|
||||
return TableConfig{
|
||||
MaxBytes: 1 << 20,
|
||||
MaxEntries: 64,
|
||||
MaxPerSource: 4,
|
||||
MaxMsgLen: 16384,
|
||||
TTL: 2 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// checkInvariants verifies the table's bookkeeping against its contents.
|
||||
func checkInvariants[K, S comparable](t *testing.T, tb *Table[K, S]) {
|
||||
t.Helper()
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
|
||||
require.Len(t, tb.order, len(tb.entries))
|
||||
require.LessOrEqual(t, len(tb.entries), tb.cfg.MaxEntries)
|
||||
bytes := 0
|
||||
perSource := map[S]int{}
|
||||
for i, key := range tb.order {
|
||||
e, ok := tb.entries[key]
|
||||
require.True(t, ok)
|
||||
require.Equal(t, i, e.pos)
|
||||
bytes += e.a.Stored()
|
||||
perSource[e.source]++
|
||||
}
|
||||
require.Equal(t, bytes, tb.bytes)
|
||||
require.LessOrEqual(t, tb.bytes, tb.cfg.MaxBytes)
|
||||
require.Equal(t, perSource, tb.perSource)
|
||||
for _, n := range perSource {
|
||||
require.LessOrEqual(t, n, tb.cfg.MaxPerSource)
|
||||
}
|
||||
}
|
||||
|
||||
func parse(t *testing.T, p []byte) (header.H, Header, []byte) {
|
||||
t.Helper()
|
||||
var nh header.H
|
||||
require.NoError(t, nh.Parse(p))
|
||||
h, sym, err := Parse(p[header.Len:])
|
||||
require.NoError(t, err)
|
||||
return nh, h, sym
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
h := Header{FragID: 0xdeadbeef, MsgLen: 3000, Index: 7}
|
||||
b := h.Encode(nil)
|
||||
require.Len(t, b, HeaderLen)
|
||||
b = append(b, make([]byte, 1000)...)
|
||||
|
||||
got, sym, err := Parse(b)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, h, got)
|
||||
assert.Len(t, sym, 1000)
|
||||
|
||||
_, _, err = Parse(b[:HeaderLen-1])
|
||||
require.ErrorIs(t, err, ErrShortFragment)
|
||||
_, _, err = Parse(b[:len(b)-1])
|
||||
require.ErrorIs(t, err, ErrSymbolSize)
|
||||
_, _, err = Parse(append(b, 0))
|
||||
require.ErrorIs(t, err, ErrSymbolSize)
|
||||
|
||||
bad := Header{FragID: 0, MsgLen: 3000}.Encode(nil)
|
||||
_, _, err = Parse(append(bad, make([]byte, 1000)...))
|
||||
require.ErrorIs(t, err, ErrFragID)
|
||||
|
||||
bad = Header{FragID: 1, MsgLen: 0}.Encode(nil)
|
||||
_, _, err = Parse(bad)
|
||||
require.ErrorIs(t, err, ErrMsgLen)
|
||||
|
||||
bad = Header{FragID: 1, MsgLen: 3000, Flags: 0x02}.Encode(nil)
|
||||
_, _, err = Parse(append(bad, make([]byte, 1000)...))
|
||||
require.ErrorIs(t, err, ErrFlags)
|
||||
|
||||
t.Run("cookie", func(t *testing.T) {
|
||||
h := Header{FragID: 7, MsgLen: 3000, Index: 4, Flags: FlagCookie}
|
||||
for i := range h.Cookie {
|
||||
h.Cookie[i] = byte(i + 1)
|
||||
}
|
||||
b := h.Encode(nil)
|
||||
require.Len(t, b, HeaderLen+CookieLen)
|
||||
b = append(b, make([]byte, 1000)...)
|
||||
|
||||
got, sym, err := Parse(b)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, h, got)
|
||||
assert.True(t, got.HasCookie())
|
||||
assert.Len(t, sym, 1000)
|
||||
|
||||
_, _, err = Parse(b[:HeaderLen+CookieLen-1])
|
||||
require.ErrorIs(t, err, ErrNoCookie)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDefaultRepair(t *testing.T) {
|
||||
for k, want := range map[int]int{1: 2, 2: 2, 6: 2, 7: 3, 9: 3, 10: 4, 14: 5} {
|
||||
assert.Equal(t, want, DefaultRepair(k), "k=%d", k)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSender(t *testing.T) {
|
||||
_, err := NewSender(nil, testSubtype, 0, 1, 1)
|
||||
require.ErrorIs(t, err, ErrMsgLen)
|
||||
_, err = NewSender(make([]byte, 65536), testSubtype, 0, 1, 1)
|
||||
require.ErrorIs(t, err, ErrMsgLen)
|
||||
_, err = NewSender(make([]byte, 10), testSubtype, 0, 1, 0)
|
||||
require.ErrorIs(t, err, ErrFragID)
|
||||
|
||||
msg := randMsg(rand.New(rand.NewPCG(1, 1)), 9800)
|
||||
s, err := NewSender(msg, testSubtype, 77, 2, 1234)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 9, s.Layout().K)
|
||||
|
||||
indexes := func(ps [][]byte) []int {
|
||||
var out []int
|
||||
for _, p := range ps {
|
||||
require.LessOrEqual(t, len(p), MaxPacketLen)
|
||||
nh, h, _ := parse(t, p)
|
||||
assert.Equal(t, header.Handshake, nh.Type)
|
||||
assert.Equal(t, testSubtype, nh.Subtype)
|
||||
assert.Equal(t, uint32(77), nh.RemoteIndex)
|
||||
assert.Equal(t, uint64(2), nh.MessageCounter)
|
||||
assert.Equal(t, uint32(1234), h.FragID)
|
||||
assert.Equal(t, uint16(9800), h.MsgLen)
|
||||
out = append(out, int(h.Index))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
now, later, err := s.Attempt(3)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}, indexes(now))
|
||||
assert.Equal(t, []int{9, 10, 11}, indexes(later))
|
||||
|
||||
// A retry offers only indexes the receiver has not seen.
|
||||
now, later, err = s.Attempt(3)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []int{12, 13, 14, 15, 16, 17, 18, 19, 20}, indexes(now))
|
||||
assert.Equal(t, []int{21, 22, 23}, indexes(later))
|
||||
|
||||
// A sender rebuilt from the same message resumes where it was told to.
|
||||
s2, err := NewSender(msg, testSubtype, 77, 2, 1234)
|
||||
require.NoError(t, err)
|
||||
s2.SetNext(s.Next())
|
||||
now2, _, err := s2.Attempt(0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []int{24, 25, 26, 27, 28, 29, 30, 31, 32}, indexes(now2))
|
||||
s2.SetNext(-1)
|
||||
assert.Equal(t, 255, s2.Next())
|
||||
|
||||
// A cookie rides on every later packet, which still fits MaxPacketLen even
|
||||
// with a full size symbol.
|
||||
full, err := NewSender(make([]byte, 2*MaxSymbolSize), testSubtype, 0, 1, 9)
|
||||
require.NoError(t, err)
|
||||
full.SetCookie(Cookie{1, 2, 3})
|
||||
pkts, _, err := full.Attempt(1)
|
||||
require.NoError(t, err)
|
||||
for _, p := range pkts {
|
||||
assert.Len(t, p, MaxPacketLen)
|
||||
_, h, _ := parse(t, p)
|
||||
assert.True(t, h.HasCookie())
|
||||
assert.Equal(t, Cookie{1, 2, 3}, h.Cookie)
|
||||
}
|
||||
|
||||
// Indexes wrap once the space is used up.
|
||||
for range 19 {
|
||||
_, _, err = s.Attempt(3)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
now, _, err = s.Attempt(3)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []int{252, 253, 254, 255, 0, 1, 2, 3, 4}, indexes(now))
|
||||
}
|
||||
|
||||
// TestLossy runs whole messages through heavy loss, reordering and duplication,
|
||||
// merging across attempts, and checks the table ends empty.
|
||||
func TestLossy(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(2, 2))
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
now := time.Unix(1000, 0)
|
||||
|
||||
for i := range 300 {
|
||||
msg := randMsg(r, 1+r.IntN(16384))
|
||||
fragID := uint32(i + 1)
|
||||
s, err := NewSender(msg, testSubtype, 0, 1, fragID)
|
||||
require.NoError(t, err)
|
||||
|
||||
var got *Result
|
||||
for attempt := 0; got == nil; attempt++ {
|
||||
require.Less(t, attempt, 20, "message never completed")
|
||||
a, b, err := s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
var pkts [][]byte
|
||||
for _, p := range append(a, b...) {
|
||||
if r.Float64() < 0.3 {
|
||||
continue
|
||||
}
|
||||
pkts = append(pkts, p)
|
||||
if r.Float64() < 0.2 {
|
||||
pkts = append(pkts, p)
|
||||
}
|
||||
}
|
||||
r.Shuffle(len(pkts), func(i, j int) { pkts[i], pkts[j] = pkts[j], pkts[i] })
|
||||
|
||||
for _, p := range pkts {
|
||||
_, h, sym := parse(t, p)
|
||||
res, err := tb.Add(testKey{"a", h.FragID}, "a", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
if res != nil {
|
||||
// The table keeps no memory of completed messages, so a late
|
||||
// duplicate can complete one again; the handshake layer
|
||||
// recognises the repeat.
|
||||
require.True(t, bytes.Equal(msg, res.Msg))
|
||||
got = res
|
||||
}
|
||||
checkInvariants(t, tb)
|
||||
}
|
||||
now = now.Add(100 * time.Millisecond)
|
||||
}
|
||||
require.Positive(t, got.Received)
|
||||
// Late fragments of a completed message start a fresh entry; drop it.
|
||||
tb.Expire(now.Add(time.Hour))
|
||||
}
|
||||
assert.Zero(t, tb.Len())
|
||||
assert.Zero(t, tb.Bytes())
|
||||
}
|
||||
|
||||
// TestConcurrent spreads each message's fragments across goroutines, as
|
||||
// multiple UDP reader routines would.
|
||||
func TestConcurrent(t *testing.T) {
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
now := time.Unix(1000, 0)
|
||||
r := rand.New(rand.NewPCG(3, 3))
|
||||
|
||||
const msgs = 50
|
||||
want := make(map[uint32][]byte, msgs)
|
||||
var pkts [][]byte
|
||||
for id := uint32(1); id <= msgs; id++ {
|
||||
msg := randMsg(r, 1+r.IntN(16384))
|
||||
want[id] = msg
|
||||
s, err := NewSender(msg, testSubtype, 0, 1, id)
|
||||
require.NoError(t, err)
|
||||
a, b, err := s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
pkts = append(pkts, a...)
|
||||
pkts = append(pkts, b...)
|
||||
}
|
||||
r.Shuffle(len(pkts), func(i, j int) { pkts[i], pkts[j] = pkts[j], pkts[i] })
|
||||
|
||||
var mu sync.Mutex
|
||||
done := map[uint32]bool{}
|
||||
var wg sync.WaitGroup
|
||||
for w := range 8 {
|
||||
wg.Go(func() {
|
||||
for i := w; i < len(pkts); i += 8 {
|
||||
h, sym, err := Parse(pkts[i][16:])
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
src := string(rune('a' + h.FragID))
|
||||
res, err := tb.Add(testKey{src, h.FragID}, src, now, h, sym)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if res != nil {
|
||||
if !bytes.Equal(want[h.FragID], res.Msg) {
|
||||
t.Errorf("message %d decoded wrong", h.FragID)
|
||||
}
|
||||
mu.Lock()
|
||||
done[h.FragID] = true
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
assert.Len(t, done, msgs)
|
||||
checkInvariants(t, tb)
|
||||
}
|
||||
|
||||
func firstFragment(t *testing.T, msgLen int, fragID uint32) (Header, []byte) {
|
||||
t.Helper()
|
||||
s, err := NewSender(make([]byte, msgLen), testSubtype, 0, 1, fragID)
|
||||
require.NoError(t, err)
|
||||
now, _, err := s.Attempt(0)
|
||||
require.NoError(t, err)
|
||||
_, h, sym := parse(t, now[0])
|
||||
return h, sym
|
||||
}
|
||||
|
||||
func TestTableLimits(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
|
||||
t.Run("max message length", func(t *testing.T) {
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
h, sym := firstFragment(t, 16385, 1)
|
||||
_, err := tb.Add(testKey{"a", 1}, "a", now, h, sym)
|
||||
require.ErrorIs(t, err, ErrTooLarge)
|
||||
assert.Zero(t, tb.Len())
|
||||
})
|
||||
|
||||
t.Run("per source quota", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.MaxPerSource = 2
|
||||
tb := NewTable[testKey, string](cfg)
|
||||
for id := uint32(1); id <= 3; id++ {
|
||||
h, sym := firstFragment(t, 5000, id)
|
||||
_, err := tb.Add(testKey{"a", id}, "a", now, h, sym)
|
||||
if id <= 2 {
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
require.ErrorIs(t, err, ErrSourceQuota)
|
||||
}
|
||||
}
|
||||
h, sym := firstFragment(t, 5000, 4)
|
||||
_, err := tb.Add(testKey{"b", 4}, "b", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 3, tb.Len())
|
||||
checkInvariants(t, tb)
|
||||
})
|
||||
|
||||
t.Run("max entries evicts", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.MaxEntries = 4
|
||||
tb := NewTable[testKey, string](cfg)
|
||||
for id := uint32(1); id <= 10; id++ {
|
||||
h, sym := firstFragment(t, 5000, id)
|
||||
src := string(rune('a' + id))
|
||||
_, err := tb.Add(testKey{src, id}, src, now, h, sym)
|
||||
require.NoError(t, err)
|
||||
checkInvariants(t, tb)
|
||||
}
|
||||
assert.Equal(t, 4, tb.Len())
|
||||
})
|
||||
|
||||
t.Run("max bytes evicts others", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.MaxBytes = 3 * 1000
|
||||
tb := NewTable[testKey, string](cfg)
|
||||
for id := uint32(1); id <= 10; id++ {
|
||||
h, sym := firstFragment(t, 5000, id) // 5 symbols of 1000
|
||||
src := string(rune('a' + id))
|
||||
_, err := tb.Add(testKey{src, id}, src, now, h, sym)
|
||||
require.NoError(t, err)
|
||||
checkInvariants(t, tb)
|
||||
}
|
||||
assert.Equal(t, 3000, tb.Bytes())
|
||||
})
|
||||
|
||||
t.Run("no room removes new entry", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.MaxBytes = 500
|
||||
tb := NewTable[testKey, string](cfg)
|
||||
h, sym := firstFragment(t, 5000, 1)
|
||||
_, err := tb.Add(testKey{"a", 1}, "a", now, h, sym)
|
||||
require.ErrorIs(t, err, ErrNoRoom)
|
||||
assert.Zero(t, tb.Len())
|
||||
checkInvariants(t, tb)
|
||||
})
|
||||
|
||||
t.Run("duplicates are not charged", func(t *testing.T) {
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
h, sym := firstFragment(t, 5000, 1)
|
||||
for range 5 {
|
||||
_, err := tb.Add(testKey{"a", 1}, "a", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
assert.Equal(t, 1000, tb.Bytes())
|
||||
})
|
||||
|
||||
t.Run("mismatch drops the entry", func(t *testing.T) {
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
h, sym := firstFragment(t, 5000, 1)
|
||||
_, err := tb.Add(testKey{"a", 1}, "a", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
|
||||
h2, sym2 := firstFragment(t, 6000, 1)
|
||||
_, err = tb.Add(testKey{"a", 1}, "a", now, h2, sym2)
|
||||
require.ErrorIs(t, err, ErrMismatch)
|
||||
assert.Zero(t, tb.Len())
|
||||
assert.Zero(t, tb.Bytes())
|
||||
checkInvariants(t, tb)
|
||||
})
|
||||
|
||||
t.Run("load", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.MaxEntries = 4
|
||||
cfg.MaxBytes = 10000
|
||||
tb := NewTable[testKey, string](cfg)
|
||||
assert.Zero(t, tb.Load())
|
||||
h, sym := firstFragment(t, 5000, 1)
|
||||
_, err := tb.Add(testKey{"a", 1}, "a", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
assert.InDelta(t, 0.25, tb.Load(), 0.001, "one of four entries")
|
||||
h, sym = firstFragment(t, 5000, 2)
|
||||
_, err = tb.Add(testKey{"b", 2}, "b", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
assert.InDelta(t, 0.5, tb.Load(), 0.001)
|
||||
})
|
||||
|
||||
t.Run("ttl", func(t *testing.T) {
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
s, err := NewSender(make([]byte, 5000), testSubtype, 0, 1, 1)
|
||||
require.NoError(t, err)
|
||||
pkts, _, err := s.Attempt(0)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, h, sym := parse(t, pkts[0])
|
||||
_, err = tb.Add(testKey{"a", 1}, "a", now, h, sym)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Activity within the TTL keeps the entry and slides its deadline.
|
||||
_, h, sym = parse(t, pkts[1])
|
||||
_, err = tb.Add(testKey{"a", 1}, "a", now.Add(1500*time.Millisecond), h, sym)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2000, tb.Bytes())
|
||||
|
||||
tb.Expire(now.Add(3 * time.Second))
|
||||
assert.Equal(t, 1, tb.Len())
|
||||
|
||||
// A stale entry is restarted rather than merged.
|
||||
_, h, sym = parse(t, pkts[2])
|
||||
_, err = tb.Add(testKey{"a", 1}, "a", now.Add(10*time.Second), h, sym)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1000, tb.Bytes())
|
||||
|
||||
tb.Expire(now.Add(time.Minute))
|
||||
assert.Zero(t, tb.Len())
|
||||
checkInvariants(t, tb)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParse(f *testing.F) {
|
||||
f.Add(append(Header{FragID: 1, MsgLen: 3000}.Encode(nil), make([]byte, 1000)...))
|
||||
f.Add([]byte{0, 0, 0, 1, 0, 1, 0, 0, 7})
|
||||
f.Fuzz(func(t *testing.T, b []byte) {
|
||||
h, sym, err := Parse(b)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
require.Equal(t, b, append(h.Encode(nil), sym...))
|
||||
l, err := h.Layout()
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, l.SymbolSize, MaxSymbolSize)
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzTable drives a small table with arbitrary fragments and checks its
|
||||
// bookkeeping after every step.
|
||||
func FuzzTable(f *testing.F) {
|
||||
f.Add([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})
|
||||
f.Fuzz(func(t *testing.T, ops []byte) {
|
||||
tb := NewTable[testKey, string](TableConfig{
|
||||
MaxBytes: 4000,
|
||||
MaxEntries: 3,
|
||||
MaxPerSource: 2,
|
||||
MaxMsgLen: 6000,
|
||||
TTL: time.Second,
|
||||
})
|
||||
now := time.Unix(0, 0)
|
||||
for len(ops) >= 4 {
|
||||
src := string(rune('a' + ops[0]%4))
|
||||
fragID := uint32(ops[1]%5) + 1
|
||||
msgLen := uint16(ops[2])*32 + 1
|
||||
index := ops[3]
|
||||
ops = ops[4:]
|
||||
|
||||
h := Header{FragID: fragID, MsgLen: msgLen, Index: index}
|
||||
l, err := h.Layout()
|
||||
require.NoError(t, err)
|
||||
sym := make([]byte, l.SymbolSize)
|
||||
if index%7 == 0 {
|
||||
now = now.Add(600 * time.Millisecond)
|
||||
tb.Expire(now)
|
||||
}
|
||||
res, err := tb.Add(testKey{src, fragID}, src, now, h, sym)
|
||||
if res != nil {
|
||||
require.NoError(t, err)
|
||||
require.Len(t, res.Msg, int(msgLen))
|
||||
}
|
||||
checkInvariants(t, tb)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package fragment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
|
||||
"github.com/slackhq/nebula/handshake/fec"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
// DefaultRepair is the starting number of repair symbols per attempt for a
|
||||
// message of k data symbols. Small messages get proportionally more repair.
|
||||
func DefaultRepair(k int) int {
|
||||
return max(2, (k+2)/3)
|
||||
}
|
||||
|
||||
// Sender produces the fragment packets of one outgoing handshake message.
|
||||
//
|
||||
// The first attempt sends the K data symbols followed by repair symbols. Every
|
||||
// later attempt sends symbols with indexes the receiver has not been offered yet,
|
||||
// so whatever it already holds still counts toward K. Symbols are a deterministic
|
||||
// function of the message, which keeps retransmits idempotent. Once all
|
||||
// fec.MaxSymbols indexes are used the sequence wraps and repeats.
|
||||
//
|
||||
// A Sender is not safe for concurrent use.
|
||||
type Sender struct {
|
||||
enc *fec.Encoder
|
||||
subtype header.MessageSubType
|
||||
remoteIndex uint32
|
||||
counter uint64
|
||||
fragID uint32
|
||||
next int
|
||||
cookie *Cookie
|
||||
}
|
||||
|
||||
// NewSender prepares msg for sending. subtype, remoteIndex and counter fill the
|
||||
// Nebula header of every fragment; fragID is the sender's local index.
|
||||
func NewSender(msg []byte, subtype header.MessageSubType, remoteIndex uint32, counter uint64, fragID uint32) (*Sender, error) {
|
||||
if len(msg) == 0 || len(msg) > math.MaxUint16 {
|
||||
return nil, ErrMsgLen
|
||||
}
|
||||
if fragID == 0 {
|
||||
return nil, ErrFragID
|
||||
}
|
||||
enc, err := fec.NewEncoder(msg, MaxSymbolSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Sender{
|
||||
enc: enc,
|
||||
subtype: subtype,
|
||||
remoteIndex: remoteIndex,
|
||||
counter: counter,
|
||||
fragID: fragID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Sender) Layout() fec.Layout {
|
||||
return s.enc.Layout()
|
||||
}
|
||||
|
||||
// SetNext sets the index the next attempt starts from, so a sender rebuilt from
|
||||
// a cached message can carry on offering fresh symbols.
|
||||
func (s *Sender) SetNext(index int) {
|
||||
s.next = ((index % fec.MaxSymbols) + fec.MaxSymbols) % fec.MaxSymbols
|
||||
}
|
||||
|
||||
// SetCookie attaches a cookie from a responder under load to every later packet.
|
||||
func (s *Sender) SetCookie(c Cookie) {
|
||||
s.cookie = &c
|
||||
}
|
||||
|
||||
// Next returns the index the next attempt starts from.
|
||||
func (s *Sender) Next() int {
|
||||
return s.next
|
||||
}
|
||||
|
||||
// Attempt returns the packets for one transmission attempt carrying K+repair
|
||||
// symbols. now should be sent immediately and later after the repair delay, so
|
||||
// a tail drop at the end of the first burst does not also take the repair.
|
||||
func (s *Sender) Attempt(repair int) (now, later [][]byte, err error) {
|
||||
if repair < 0 {
|
||||
return nil, nil, errors.New("negative repair count")
|
||||
}
|
||||
k := s.enc.Layout().K
|
||||
now = make([][]byte, 0, k)
|
||||
later = make([][]byte, 0, repair)
|
||||
for i := range k + repair {
|
||||
p, err := s.packet(s.next)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
s.next = (s.next + 1) % fec.MaxSymbols
|
||||
if i < k {
|
||||
now = append(now, p)
|
||||
} else {
|
||||
later = append(later, p)
|
||||
}
|
||||
}
|
||||
return now, later, nil
|
||||
}
|
||||
|
||||
func (s *Sender) packet(index int) ([]byte, error) {
|
||||
l := s.enc.Layout()
|
||||
p := make([]byte, header.Len, header.Len+HeaderLen+CookieLen+l.SymbolSize)
|
||||
header.Encode(p, header.Version, header.Handshake, s.subtype, s.remoteIndex, s.counter)
|
||||
h := Header{
|
||||
FragID: s.fragID,
|
||||
MsgLen: uint16(l.MsgLen),
|
||||
Index: uint8(index),
|
||||
}
|
||||
if s.cookie != nil {
|
||||
h.Flags |= FlagCookie
|
||||
h.Cookie = *s.cookie
|
||||
}
|
||||
p = h.Encode(p)
|
||||
return s.enc.Symbol(p, index)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package fragment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrTooLarge = errors.New("fragmented message exceeds the size limit")
|
||||
ErrSourceQuota = errors.New("source has too many messages in progress")
|
||||
ErrNoRoom = errors.New("no room for fragment")
|
||||
)
|
||||
|
||||
// TableConfig bounds a Table.
|
||||
type TableConfig struct {
|
||||
MaxBytes int // symbol bytes held across all entries
|
||||
MaxEntries int // messages in progress across all sources
|
||||
MaxPerSource int // messages in progress per source
|
||||
MaxMsgLen int // largest message accepted
|
||||
TTL time.Duration // an entry idle this long is dropped
|
||||
}
|
||||
|
||||
// Table reassembles messages from senders that have not authenticated yet, the
|
||||
// responder's view of msg1. Every resource is capped. When a cap is hit a
|
||||
// random entry is evicted; random eviction is harder to aim than LRU, which a
|
||||
// flood can use to flush specific entries.
|
||||
//
|
||||
// K identifies one message, typically the source plus FragID. S identifies the
|
||||
// source for quotas, typically the address masked to /32 or /64.
|
||||
//
|
||||
// A Table is safe for concurrent use.
|
||||
type Table[K, S comparable] struct {
|
||||
mu sync.Mutex
|
||||
cfg TableConfig
|
||||
entries map[K]*tableEntry[K, S]
|
||||
order []K
|
||||
perSource map[S]int
|
||||
bytes int
|
||||
}
|
||||
|
||||
type tableEntry[K, S comparable] struct {
|
||||
a *Assembly
|
||||
source S
|
||||
lastSeen time.Time
|
||||
pos int
|
||||
}
|
||||
|
||||
func NewTable[K, S comparable](cfg TableConfig) *Table[K, S] {
|
||||
return &Table[K, S]{
|
||||
cfg: cfg,
|
||||
entries: make(map[K]*tableEntry[K, S]),
|
||||
perSource: make(map[S]int),
|
||||
}
|
||||
}
|
||||
|
||||
// Result describes a completed message.
|
||||
type Result struct {
|
||||
Msg []byte // the decoded message
|
||||
Received int // packet bytes received for it, for the amplification budget
|
||||
}
|
||||
|
||||
// Add records a fragment parsed by Parse. When the message is complete its entry
|
||||
// is removed and the result returned; otherwise the result is nil. A decode
|
||||
// error means the message is lost and must be retransmitted.
|
||||
func (t *Table[K, S]) Add(key K, source S, now time.Time, h Header, sym []byte) (*Result, error) {
|
||||
if int(h.MsgLen) > t.cfg.MaxMsgLen {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
e, ok := t.entries[key]
|
||||
if ok && now.Sub(e.lastSeen) > t.cfg.TTL {
|
||||
t.remove(key, e)
|
||||
ok = false
|
||||
}
|
||||
if !ok {
|
||||
var err error
|
||||
e, err = t.insert(key, source, h)
|
||||
if err != nil {
|
||||
t.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
e.lastSeen = now
|
||||
|
||||
if !t.makeRoom(key, e.a.wouldStore(h, sym)) {
|
||||
if e.a.Stored() == 0 {
|
||||
t.remove(key, e)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
return nil, ErrNoRoom
|
||||
}
|
||||
|
||||
before := e.a.Stored()
|
||||
ready, err := e.a.Add(h, sym)
|
||||
t.bytes += e.a.Stored() - before
|
||||
if err != nil || !ready {
|
||||
if errors.Is(err, ErrMismatch) || (err != nil && e.a.Stored() == 0) {
|
||||
t.remove(key, e)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
t.remove(key, e)
|
||||
t.mu.Unlock()
|
||||
|
||||
msg, err := e.a.Decode()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Result{Msg: msg, Received: e.a.Received()}, nil
|
||||
}
|
||||
|
||||
// Expire drops every entry idle for longer than the TTL.
|
||||
func (t *Table[K, S]) Expire(now time.Time) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
for i := 0; i < len(t.order); {
|
||||
key := t.order[i]
|
||||
e := t.entries[key]
|
||||
if now.Sub(e.lastSeen) > t.cfg.TTL {
|
||||
// remove swaps the last entry into position i, so look at i again.
|
||||
t.remove(key, e)
|
||||
continue
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of messages in progress.
|
||||
func (t *Table[K, S]) Len() int {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return len(t.entries)
|
||||
}
|
||||
|
||||
// Load returns how full the table is, from 0 to 1, by whichever of its byte and
|
||||
// entry limits is closer.
|
||||
func (t *Table[K, S]) Load() float64 {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return max(float64(t.bytes)/float64(t.cfg.MaxBytes), float64(len(t.entries))/float64(t.cfg.MaxEntries))
|
||||
}
|
||||
|
||||
// Bytes returns the number of symbol bytes held.
|
||||
func (t *Table[K, S]) Bytes() int {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.bytes
|
||||
}
|
||||
|
||||
func (t *Table[K, S]) insert(key K, source S, h Header) (*tableEntry[K, S], error) {
|
||||
if t.perSource[source] >= t.cfg.MaxPerSource {
|
||||
return nil, ErrSourceQuota
|
||||
}
|
||||
a, err := NewAssembly(h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for len(t.entries) >= t.cfg.MaxEntries {
|
||||
if !t.evictRandom(nil) {
|
||||
return nil, ErrNoRoom
|
||||
}
|
||||
}
|
||||
|
||||
e := &tableEntry[K, S]{a: a, source: source, pos: len(t.order)}
|
||||
t.entries[key] = e
|
||||
t.order = append(t.order, key)
|
||||
t.perSource[source]++
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// makeRoom evicts random entries other than keep until n more bytes fit.
|
||||
func (t *Table[K, S]) makeRoom(keep K, n int) bool {
|
||||
for t.bytes+n > t.cfg.MaxBytes {
|
||||
if !t.evictRandom(&keep) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *Table[K, S]) evictRandom(keep *K) bool {
|
||||
candidates := len(t.order)
|
||||
if keep != nil {
|
||||
if _, ok := t.entries[*keep]; ok {
|
||||
candidates--
|
||||
}
|
||||
}
|
||||
if candidates <= 0 {
|
||||
return false
|
||||
}
|
||||
for {
|
||||
key := t.order[rand.IntN(len(t.order))]
|
||||
if keep != nil && key == *keep {
|
||||
continue
|
||||
}
|
||||
t.remove(key, t.entries[key])
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Table[K, S]) remove(key K, e *tableEntry[K, S]) {
|
||||
last := len(t.order) - 1
|
||||
moved := t.order[last]
|
||||
t.order[e.pos] = moved
|
||||
t.entries[moved].pos = e.pos
|
||||
t.order = t.order[:last]
|
||||
delete(t.entries, key)
|
||||
|
||||
t.bytes -= e.a.Stored()
|
||||
if t.perSource[e.source] <= 1 {
|
||||
delete(t.perSource, e.source)
|
||||
} else {
|
||||
t.perSource[e.source]--
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Package fragment carries handshake messages that do not fit in one UDP
|
||||
// packet. A message is Reed-Solomon coded into equally sized symbols (see
|
||||
// handshake/fec) and each symbol travels in its own packet:
|
||||
//
|
||||
// Nebula header (16) | Fragment header (8) | [cookie (16)] | symbol
|
||||
//
|
||||
// The fragment header is FragID u32 | MsgLen u16 | Index u8 | Flags u8, all big
|
||||
// endian. Both ends derive the symbol layout from MsgLen, so any MsgLen-derived
|
||||
// value never has to be sent. FlagCookie marks a cookie a responder under load
|
||||
// asked for; room for it is always reserved, so a fragment never outgrows
|
||||
// MaxPacketLen.
|
||||
package fragment
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
|
||||
"github.com/slackhq/nebula/handshake/fec"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
const (
|
||||
// HeaderLen is the size of the fragment header that follows the Nebula header.
|
||||
HeaderLen = 8
|
||||
|
||||
// CookieLen is the size of the cookie a fragment carries when FlagCookie is set.
|
||||
CookieLen = 16
|
||||
|
||||
// FlagCookie marks a fragment that carries a cookie after its header.
|
||||
FlagCookie uint8 = 0x01
|
||||
|
||||
// MaxPacketLen bounds every fragment packet, Nebula header included. A relayed
|
||||
// fragment gains a 16 byte header and a 16 byte tag, which lands exactly on
|
||||
// the 1232 byte UDP payload available on an IPv6 minimum MTU path.
|
||||
MaxPacketLen = 1200
|
||||
|
||||
// MaxSymbolSize is the largest symbol that fits in MaxPacketLen alongside a cookie.
|
||||
MaxSymbolSize = MaxPacketLen - header.Len - HeaderLen - CookieLen
|
||||
)
|
||||
|
||||
var (
|
||||
ErrShortFragment = errors.New("fragment is too short")
|
||||
ErrFragID = errors.New("fragment has a zero FragID")
|
||||
ErrMsgLen = errors.New("fragment has a zero MsgLen")
|
||||
ErrFlags = errors.New("fragment has reserved flags set")
|
||||
ErrNoCookie = errors.New("fragment is too short for its cookie")
|
||||
ErrSymbolSize = errors.New("fragment symbol size does not match its MsgLen")
|
||||
)
|
||||
|
||||
// Cookie proves a sender received a responder's reply at its address.
|
||||
type Cookie [CookieLen]byte
|
||||
|
||||
// Header is the fragment header.
|
||||
type Header struct {
|
||||
FragID uint32 // the sender's local index for this handshake, never zero
|
||||
MsgLen uint16 // length of the whole message
|
||||
Index uint8 // symbol index, data below K and repair from K
|
||||
Flags uint8 // FlagCookie, other bits reserved and zero
|
||||
Cookie Cookie // valid when Flags has FlagCookie
|
||||
}
|
||||
|
||||
func (h Header) HasCookie() bool {
|
||||
return h.Flags&FlagCookie != 0
|
||||
}
|
||||
|
||||
// Encode appends the header, and its cookie if it has one, to b.
|
||||
func (h Header) Encode(b []byte) []byte {
|
||||
b = binary.BigEndian.AppendUint32(b, h.FragID)
|
||||
b = binary.BigEndian.AppendUint16(b, h.MsgLen)
|
||||
b = append(b, h.Index, h.Flags)
|
||||
if h.HasCookie() {
|
||||
b = append(b, h.Cookie[:]...)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Layout returns the symbol layout the header's MsgLen implies.
|
||||
func (h Header) Layout() (fec.Layout, error) {
|
||||
return fec.NewLayout(int(h.MsgLen), MaxSymbolSize)
|
||||
}
|
||||
|
||||
// Parse validates the bytes following the Nebula header and splits them into
|
||||
// the fragment header and the symbol. The symbol aliases b.
|
||||
func Parse(b []byte) (Header, []byte, error) {
|
||||
if len(b) < HeaderLen {
|
||||
return Header{}, nil, ErrShortFragment
|
||||
}
|
||||
h := Header{
|
||||
FragID: binary.BigEndian.Uint32(b[0:4]),
|
||||
MsgLen: binary.BigEndian.Uint16(b[4:6]),
|
||||
Index: b[6],
|
||||
Flags: b[7],
|
||||
}
|
||||
if h.FragID == 0 {
|
||||
return Header{}, nil, ErrFragID
|
||||
}
|
||||
if h.MsgLen == 0 {
|
||||
return Header{}, nil, ErrMsgLen
|
||||
}
|
||||
if h.Flags&^FlagCookie != 0 {
|
||||
return Header{}, nil, ErrFlags
|
||||
}
|
||||
b = b[HeaderLen:]
|
||||
if h.HasCookie() {
|
||||
if len(b) < CookieLen {
|
||||
return Header{}, nil, ErrNoCookie
|
||||
}
|
||||
copy(h.Cookie[:], b)
|
||||
b = b[CookieLen:]
|
||||
}
|
||||
|
||||
l, err := h.Layout()
|
||||
if err != nil {
|
||||
return Header{}, nil, err
|
||||
}
|
||||
sym := b
|
||||
if len(sym) != l.SymbolSize {
|
||||
return Header{}, nil, ErrSymbolSize
|
||||
}
|
||||
return h, sym, nil
|
||||
}
|
||||
@@ -24,6 +24,9 @@ message NebulaHandshakeDetails {
|
||||
uint64 Cookie = 4 [deprecated = true];
|
||||
uint64 Time = 5;
|
||||
uint32 CertVersion = 8;
|
||||
// KEMKey is the initiator's ephemeral ML-KEM-1024 encapsulation key. It is
|
||||
// only present in msg1 of the ix_psk2_mlkem1024 subtype.
|
||||
bytes KEMKey = 9;
|
||||
// reserved for WIP multiport
|
||||
reserved 6, 7;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"crypto/hkdf"
|
||||
"crypto/mlkem"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// kemPSKSalt separates the psk derivation from any other use of the secret.
|
||||
const kemPSKSalt = "nebula ix_psk2_mlkem1024 v1"
|
||||
|
||||
var ErrInvalidKEMKey = errors.New("peer sent an invalid ML-KEM encapsulation key")
|
||||
|
||||
// kemPSK derives the noise psk from an ML-KEM shared secret. The ciphertext is
|
||||
// bound in because, unlike the encapsulation key, it travels outside the noise
|
||||
// transcript.
|
||||
func kemPSK(sharedKey, ciphertext []byte) ([]byte, error) {
|
||||
secret := make([]byte, 0, len(sharedKey)+len(ciphertext))
|
||||
secret = append(secret, sharedKey...)
|
||||
secret = append(secret, ciphertext...)
|
||||
return hkdf.Extract(sha256.New, secret, []byte(kemPSKSalt))
|
||||
}
|
||||
|
||||
// kemEncapsulate is the responder half: encapsulate to the initiator's key,
|
||||
// install the psk, and remember the ciphertext to prefix the response with.
|
||||
func (m *Machine) kemEncapsulate(encapsulationKey []byte) error {
|
||||
ek, err := mlkem.NewEncapsulationKey1024(encapsulationKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrInvalidKEMKey, err)
|
||||
}
|
||||
sharedKey, ct := ek.Encapsulate()
|
||||
psk, err := kemPSK(sharedKey, ct)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.hs.SetPresharedKey(psk); err != nil {
|
||||
return err
|
||||
}
|
||||
m.kemCiphertext = ct
|
||||
return nil
|
||||
}
|
||||
|
||||
// kemDecapsulate is the initiator half: recover the shared secret from the
|
||||
// ciphertext prefixing the response and install the psk. It returns the rest of
|
||||
// the message, which is the noise message.
|
||||
func (m *Machine) kemDecapsulate(msg []byte) ([]byte, error) {
|
||||
if len(msg) < mlkem.CiphertextSize1024 {
|
||||
return nil, ErrPacketTooShort
|
||||
}
|
||||
if m.kemKey == nil {
|
||||
return nil, errors.New("no ML-KEM decapsulation key for this handshake")
|
||||
}
|
||||
ct := msg[:mlkem.CiphertextSize1024]
|
||||
sharedKey, err := m.kemKey.Decapsulate(ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
psk, err := kemPSK(sharedKey, ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := m.hs.SetPresharedKey(psk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg[mlkem.CiphertextSize1024:], nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/mlkem"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newKEMMachine(t *testing.T, cs *testCertState, v CertVerifier, initiator bool, index uint32) *Machine {
|
||||
t.Helper()
|
||||
m, err := NewMachine(
|
||||
cs.version, cs.getCredential, v,
|
||||
func() (uint32, error) { return index, nil },
|
||||
initiator, header.HandshakeIXPSK2MLKEM1024,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return m
|
||||
}
|
||||
|
||||
type kemFixture struct {
|
||||
initCS, respCS *testCertState
|
||||
v CertVerifier
|
||||
}
|
||||
|
||||
func newKEMFixture(t *testing.T, cipher noise.CipherFunc) kemFixture {
|
||||
ca, _, caKey, _ := ct.NewTestCaCert(
|
||||
cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil,
|
||||
)
|
||||
return kemFixture{
|
||||
initCS: newTestCertStateWithCipher(t, ca, caKey, "initiator", []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}, cipher),
|
||||
respCS: newTestCertStateWithCipher(t, ca, caKey, "responder", []netip.Prefix{netip.MustParsePrefix("10.0.0.2/24")}, cipher),
|
||||
v: testVerifier(ct.NewTestCAPool(ca)),
|
||||
}
|
||||
}
|
||||
|
||||
func requireKeysMatch(t *testing.T, a, b *Result) {
|
||||
t.Helper()
|
||||
c, err := a.EKey.Encrypt(nil, nil, []byte("hello"))
|
||||
require.NoError(t, err)
|
||||
p, err := b.DKey.Decrypt(nil, nil, c)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("hello"), p)
|
||||
|
||||
c, err = b.EKey.Encrypt(nil, nil, []byte("world"))
|
||||
require.NoError(t, err)
|
||||
p, err = a.DKey.Decrypt(nil, nil, c)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("world"), p)
|
||||
}
|
||||
|
||||
func TestKEMHandshake(t *testing.T) {
|
||||
for _, cipher := range []noise.CipherFunc{noise.CipherChaChaPoly, noise.CipherAESGCM} {
|
||||
t.Run(cipher.CipherName(), func(t *testing.T) {
|
||||
f := newKEMFixture(t, cipher)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, header.HandshakeIXPSK2MLKEM1024, header.MessageSubType(msg1[1]))
|
||||
assert.Greater(t, len(msg1), header.Len+mlkem.EncapsulationKeySize1024)
|
||||
|
||||
msg2, respR, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, respR)
|
||||
assert.Greater(t, len(msg2), header.Len+mlkem.CiphertextSize1024)
|
||||
|
||||
_, initR, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, initR)
|
||||
|
||||
assert.Equal(t, "responder", initR.RemoteCert.Certificate.Name())
|
||||
assert.Equal(t, "initiator", respR.RemoteCert.Certificate.Name())
|
||||
assert.Equal(t, uint32(2000), initR.RemoteIndex)
|
||||
assert.Equal(t, uint32(1000), respR.RemoteIndex)
|
||||
requireKeysMatch(t, initR, respR)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestKEMSecretMatters checks the ML-KEM secret really reaches the transport
|
||||
// keys: an initiator holding a different decapsulation key cannot complete even
|
||||
// though every DH input is genuine.
|
||||
func TestKEMSecretMatters(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, _, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
|
||||
other, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
initM.kemKey = other
|
||||
|
||||
_, res, err := initM.ProcessPacket(nil, msg2)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, res)
|
||||
}
|
||||
|
||||
func TestKEMTamperedCiphertext(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, respR, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("truncated", func(t *testing.T) {
|
||||
_, res, err := initM.ProcessPacket(nil, msg2[:header.Len+mlkem.CiphertextSize1024-1])
|
||||
require.ErrorIs(t, err, ErrPacketTooShort)
|
||||
assert.Nil(t, res)
|
||||
assert.False(t, initM.Failed())
|
||||
})
|
||||
|
||||
t.Run("flipped ciphertext bit", func(t *testing.T) {
|
||||
bad := bytes.Clone(msg2)
|
||||
bad[header.Len+10] ^= 1
|
||||
_, res, err := initM.ProcessPacket(nil, bad)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, res)
|
||||
assert.False(t, initM.Failed(), "a forged ciphertext must not kill the handshake")
|
||||
})
|
||||
|
||||
t.Run("genuine response still completes", func(t *testing.T) {
|
||||
_, initR, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, initR)
|
||||
requireKeysMatch(t, initR, respR)
|
||||
})
|
||||
}
|
||||
|
||||
// TestKEMBadMsg1 drives processPayload by hand. With the psk modifier msg1's
|
||||
// payload is encrypted under a key derived from the public ephemeral, so a
|
||||
// forged payload would need re-encrypting; the parsing rules are what matter.
|
||||
func TestKEMBadMsg1(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
msg1Flags := subtypeInfos[header.HandshakeIXPSK2MLKEM1024].msgs[0]
|
||||
cert := f.initCS.creds[cert.Version2]
|
||||
payload := func(kemKey []byte) []byte {
|
||||
return MarshalPayload(nil, Payload{
|
||||
Cert: cert.Bytes,
|
||||
CertVersion: uint32(cert.Cert.Version()),
|
||||
InitiatorIndex: 1000,
|
||||
Time: 1,
|
||||
KEMKey: kemKey,
|
||||
})
|
||||
}
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("missing KEM key", func(t *testing.T) {
|
||||
m := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
err := m.processPayload(payload(nil), msg1Flags)
|
||||
require.ErrorIs(t, err, ErrUnexpectedContent)
|
||||
assert.True(t, m.Failed())
|
||||
})
|
||||
|
||||
t.Run("invalid KEM key", func(t *testing.T) {
|
||||
m := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
// Coefficients of 0xfff exceed the modulus, which ML-KEM must reject.
|
||||
bad := bytes.Repeat([]byte{0xff}, mlkem.EncapsulationKeySize1024)
|
||||
err := m.kemEncapsulate(bad)
|
||||
require.ErrorIs(t, err, ErrInvalidKEMKey)
|
||||
err = m.kemEncapsulate(bad[:100])
|
||||
require.ErrorIs(t, err, ErrInvalidKEMKey)
|
||||
})
|
||||
|
||||
t.Run("valid KEM key", func(t *testing.T) {
|
||||
m := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
require.NoError(t, m.kemEncapsulate(dk.EncapsulationKey().Bytes()))
|
||||
assert.Len(t, m.kemCiphertext, mlkem.CiphertextSize1024)
|
||||
})
|
||||
|
||||
t.Run("KEM key on the classical subtype", func(t *testing.T) {
|
||||
m := newTestMachine(t, f.respCS, f.v, false, 2000)
|
||||
classical := subtypeInfos[header.HandshakeIXPSK0].msgs[0]
|
||||
err := m.processPayload(payload(dk.EncapsulationKey().Bytes()), classical)
|
||||
require.ErrorIs(t, err, ErrUnexpectedContent)
|
||||
assert.True(t, m.Failed())
|
||||
})
|
||||
}
|
||||
|
||||
// TestKEMDistinctFromClassical makes sure the two subtypes cannot be mixed: a
|
||||
// classical responder cannot answer a KEM initiator.
|
||||
func TestKEMDistinctFromClassical(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newTestMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
_, _, err = respM.ProcessPacket(nil, msg1)
|
||||
require.ErrorIs(t, err, ErrSubtypeMismatch)
|
||||
}
|
||||
+54
-5
@@ -2,6 +2,8 @@ package handshake
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/mlkem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
@@ -67,6 +69,9 @@ type Machine struct {
|
||||
remoteCertSet bool
|
||||
payloadSet bool
|
||||
failed bool
|
||||
|
||||
kemKey *mlkem.DecapsulationKey1024 // initiator's ephemeral ML-KEM key, until completion
|
||||
kemCiphertext []byte // responder's ciphertext to prefix its response with
|
||||
}
|
||||
|
||||
// NewMachine creates a handshake state machine. The subtype determines both
|
||||
@@ -91,7 +96,7 @@ func NewMachine(
|
||||
return nil, fmt.Errorf("%w: %v", ErrNoCredential, version)
|
||||
}
|
||||
|
||||
hs, err := cred.buildHandshakeState(initiator, info.pattern)
|
||||
hs, err := cred.buildHandshakeState(initiator, info.pattern, info.pskPlacement)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build noise state: %w", err)
|
||||
}
|
||||
@@ -137,7 +142,8 @@ func (m *Machine) requireComplete() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// myMsgFlags returns the flags for the current outgoing message.
|
||||
// myMsgFlags returns the flags for the current outgoing message, which are
|
||||
// also the flags of the next incoming message before it is read.
|
||||
func (m *Machine) myMsgFlags() msgFlags {
|
||||
idx := m.hs.MessageIndex()
|
||||
if idx < len(m.msgs) {
|
||||
@@ -225,7 +231,18 @@ func (m *Machine) ProcessPacket(out, packet []byte) ([]byte, *Result, error) {
|
||||
// noise returns (cs1, cs2) where cs1 is the initiator->responder cipher.
|
||||
// For 3-message patterns where a responder finishes by reading the final
|
||||
// message, this ordering would be wrong; revisit when XX/pqIX lands.
|
||||
msg, eKey, dKey, err := m.hs.ReadMessage(nil, packet[header.Len:])
|
||||
noiseMsg := packet[header.Len:]
|
||||
if m.myMsgFlags().kemCiphertext {
|
||||
var err error
|
||||
// Installing a psk derived from a forged ciphertext is harmless: ReadMessage
|
||||
// then fails without advancing, and the next packet installs its own.
|
||||
noiseMsg, err = m.kemDecapsulate(noiseMsg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
msg, eKey, dKey, err := m.hs.ReadMessage(nil, noiseMsg)
|
||||
if err != nil {
|
||||
// Noise ReadMessage failed. The noise library checkpoints and rolls back
|
||||
// on failure, so the Machine is still alive. The caller can retry with
|
||||
@@ -276,6 +293,8 @@ func (m *Machine) ProcessPacket(out, packet []byte) ([]byte, *Result, error) {
|
||||
}
|
||||
|
||||
func (m *Machine) completed(eKey, dKey *noise.CipherState) *Result {
|
||||
m.kemKey = nil
|
||||
m.kemCiphertext = nil
|
||||
m.result.EKey = eKey
|
||||
m.result.DKey = dKey
|
||||
m.result.MessageIndex = uint64(m.hs.MessageIndex())
|
||||
@@ -284,7 +303,7 @@ func (m *Machine) completed(eKey, dKey *noise.CipherState) *Result {
|
||||
|
||||
func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
if len(msg) == 0 {
|
||||
if flags.expectsPayload || flags.expectsCert {
|
||||
if flags.expectsPayload || flags.expectsCert || flags.kemKey {
|
||||
m.failed = true
|
||||
return ErrMissingContent
|
||||
}
|
||||
@@ -310,6 +329,12 @@ func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
return ErrUnexpectedContent
|
||||
}
|
||||
|
||||
hasKEMKey := len(payload.KEMKey) > 0
|
||||
if hasKEMKey != flags.kemKey {
|
||||
m.failed = true
|
||||
return ErrUnexpectedContent
|
||||
}
|
||||
|
||||
// Process payload
|
||||
if flags.expectsPayload {
|
||||
var remoteIndex uint32
|
||||
@@ -336,6 +361,13 @@ func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
}
|
||||
}
|
||||
|
||||
if flags.kemKey {
|
||||
if err := m.kemEncapsulate(payload.KEMKey); err != nil {
|
||||
m.failed = true
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -380,11 +412,21 @@ func (m *Machine) validateCert(payload Payload) error {
|
||||
}
|
||||
|
||||
func (m *Machine) marshalOutgoing(flags msgFlags) ([]byte, error) {
|
||||
if !flags.expectsPayload && !flags.expectsCert {
|
||||
if !flags.expectsPayload && !flags.expectsCert && !flags.kemKey {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var p Payload
|
||||
if flags.kemKey {
|
||||
if m.kemKey == nil {
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate ML-KEM key: %w", err)
|
||||
}
|
||||
m.kemKey = dk
|
||||
}
|
||||
p.KEMKey = m.kemKey.EncapsulationKey().Bytes()
|
||||
}
|
||||
if flags.expectsPayload {
|
||||
if !m.indexAllocated {
|
||||
index, err := m.allocIndex()
|
||||
@@ -436,6 +478,13 @@ func (m *Machine) buildResponse(out []byte) ([]byte, *noise.CipherState, *noise.
|
||||
uint64(m.hs.MessageIndex()+1),
|
||||
)
|
||||
|
||||
if flags.kemCiphertext {
|
||||
if m.kemCiphertext == nil {
|
||||
return nil, nil, nil, errors.New("no ML-KEM ciphertext to send")
|
||||
}
|
||||
out = append(out, m.kemCiphertext...)
|
||||
}
|
||||
|
||||
// noise.WriteMessage appends the encrypted handshake message to out,
|
||||
// reusing capacity when present.
|
||||
//
|
||||
|
||||
+21
-2
@@ -11,13 +11,16 @@ import (
|
||||
type msgFlags struct {
|
||||
expectsPayload bool // message carries indexes and time
|
||||
expectsCert bool // message carries the certificate
|
||||
kemKey bool // payload carries an ML-KEM encapsulation key
|
||||
kemCiphertext bool // message is prefixed with the ML-KEM ciphertext for the peer's key
|
||||
}
|
||||
|
||||
// subtypeInfo bundles the noise pattern with the per-message flags for a
|
||||
// given handshake subtype.
|
||||
type subtypeInfo struct {
|
||||
pattern noise.HandshakePattern
|
||||
msgs []msgFlags
|
||||
pattern noise.HandshakePattern
|
||||
pskPlacement int // noise psk modifier position, 0 means no psk token
|
||||
msgs []msgFlags
|
||||
}
|
||||
|
||||
// subtypeInfos defines the noise pattern and message content layout for each
|
||||
@@ -32,6 +35,22 @@ var subtypeInfos = map[header.MessageSubType]subtypeInfo{
|
||||
},
|
||||
},
|
||||
|
||||
// IX with an ephemeral ML-KEM-1024 exchange:
|
||||
// msg1 (I->R): payload + cert + encapsulation key
|
||||
// msg2 (R->I): ciphertext || noise(payload + cert)
|
||||
// The responder encapsulates after reading msg1 and mixes the shared secret in
|
||||
// through the psk2 token at the end of msg2. The ciphertext travels outside the
|
||||
// noise message because the initiator needs the secret before it can process
|
||||
// that token.
|
||||
header.HandshakeIXPSK2MLKEM1024: {
|
||||
pattern: noise.HandshakeIX,
|
||||
pskPlacement: 2,
|
||||
msgs: []msgFlags{
|
||||
{expectsPayload: true, expectsCert: true, kemKey: true},
|
||||
{expectsPayload: true, expectsCert: true, kemCiphertext: true},
|
||||
},
|
||||
},
|
||||
|
||||
// XX: 3 messages
|
||||
// msg1 (I->R): payload only
|
||||
// msg2 (R->I): payload + cert
|
||||
|
||||
@@ -20,6 +20,7 @@ type Payload struct {
|
||||
ResponderIndex uint32
|
||||
Time uint64
|
||||
CertVersion uint32
|
||||
KEMKey []byte // ML-KEM encapsulation key, only in subtypes that carry one
|
||||
}
|
||||
|
||||
// Proto field numbers for NebulaHandshakeDetails
|
||||
@@ -29,6 +30,7 @@ const (
|
||||
fieldResponderIndex = 3 // uint32
|
||||
fieldTime = 5 // uint64
|
||||
fieldCertVersion = 8 // uint32
|
||||
fieldKEMKey = 9 // bytes
|
||||
)
|
||||
|
||||
// MarshalPayload encodes a handshake payload in protobuf wire format compatible
|
||||
@@ -57,6 +59,10 @@ func MarshalPayload(out []byte, p Payload) []byte {
|
||||
details = protowire.AppendTag(details, fieldCertVersion, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.CertVersion))
|
||||
}
|
||||
if len(p.KEMKey) > 0 {
|
||||
details = protowire.AppendTag(details, fieldKEMKey, protowire.BytesType)
|
||||
details = protowire.AppendBytes(details, p.KEMKey)
|
||||
}
|
||||
|
||||
out = protowire.AppendTag(out, 1, protowire.BytesType)
|
||||
out = protowire.AppendBytes(out, details)
|
||||
@@ -161,6 +167,16 @@ func unmarshalPayloadDetails(p *Payload, b []byte) error {
|
||||
}
|
||||
p.CertVersion = uint32(v)
|
||||
b = b[n:]
|
||||
case fieldKEMKey:
|
||||
if typ != protowire.BytesType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
v, n := protowire.ConsumeBytes(b)
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.KEMKey = append([]byte(nil), v...)
|
||||
b = b[n:]
|
||||
default:
|
||||
n := protowire.ConsumeFieldValue(num, typ, b)
|
||||
if n < 0 {
|
||||
|
||||
+174
-79
@@ -10,12 +10,15 @@ import (
|
||||
"net/netip"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/ratelimit"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
)
|
||||
|
||||
@@ -49,6 +52,7 @@ type HandshakeConfig struct {
|
||||
tryInterval time.Duration
|
||||
retries int64
|
||||
triggerBuffer int
|
||||
pq pqHandshakeConfig
|
||||
|
||||
messageMetrics *MessageMetrics
|
||||
}
|
||||
@@ -61,20 +65,31 @@ type HandshakeManager struct {
|
||||
vpnIps map[netip.Addr]*HandshakeHostInfo
|
||||
indexes map[uint32]*HandshakeHostInfo
|
||||
|
||||
mainHostMap *HostMap
|
||||
lightHouse *LightHouse
|
||||
outside udp.Conn
|
||||
config HandshakeConfig
|
||||
OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
|
||||
messageMetrics *MessageMetrics
|
||||
metricInitiated metrics.Counter
|
||||
metricTimedOut metrics.Counter
|
||||
metricRejectedBlocklisted metrics.Counter
|
||||
f *Interface
|
||||
l *slog.Logger
|
||||
mainHostMap *HostMap
|
||||
lightHouse *LightHouse
|
||||
outside udp.Conn
|
||||
config HandshakeConfig
|
||||
OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
|
||||
messageMetrics *MessageMetrics
|
||||
metricInitiated metrics.Counter
|
||||
metricTimedOut metrics.Counter
|
||||
f *Interface
|
||||
l *slog.Logger
|
||||
|
||||
// can be used to trigger outbound handshake for the given vpnIp
|
||||
trigger chan netip.Addr
|
||||
|
||||
// pq holds the post-quantum settings, which change on reload.
|
||||
pq atomic.Pointer[pqHandshakeConfig]
|
||||
// pqTable reassembles post-quantum msg1s from senders that have not authenticated yet.
|
||||
pqTable *fragment.Table[pqFragKey, pqFragSource]
|
||||
// pqPeers holds vpn addresses that completed a post-quantum handshake, for sticky mode.
|
||||
pqPeers sync.Map
|
||||
// pqAnswered recognises repeats of post-quantum msg1s already answered.
|
||||
pqAnswered *pqAnswered
|
||||
// pqCookies and pqCookieLimiter serve cookies while pqTable is under load.
|
||||
pqCookies *pqCookies
|
||||
pqCookieLimiter *ratelimit.Limiter
|
||||
}
|
||||
|
||||
type HandshakeHostInfo struct {
|
||||
@@ -90,6 +105,8 @@ type HandshakeHostInfo struct {
|
||||
|
||||
hostinfo *HostInfo
|
||||
machine *handshake.Machine // The handshake state machine, set during stage 0 (initiator) or beginHandshake (responder multi-message)
|
||||
pq *pqAttempt // The initiator's post-quantum attempt, pending alongside the classical one
|
||||
lastPQ bool // Whether the latest attempt was post-quantum
|
||||
}
|
||||
|
||||
func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
|
||||
@@ -118,21 +135,29 @@ func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, s
|
||||
}
|
||||
|
||||
func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
|
||||
return &HandshakeManager{
|
||||
vpnIps: map[netip.Addr]*HandshakeHostInfo{},
|
||||
indexes: map[uint32]*HandshakeHostInfo{},
|
||||
mainHostMap: mainHostMap,
|
||||
lightHouse: lightHouse,
|
||||
outside: outside,
|
||||
config: config,
|
||||
trigger: make(chan netip.Addr, config.triggerBuffer),
|
||||
OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
|
||||
messageMetrics: config.messageMetrics,
|
||||
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
||||
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
||||
metricRejectedBlocklisted: metrics.GetOrRegisterCounter("handshake_manager.rejected.blocklisted", nil),
|
||||
l: l,
|
||||
hm := &HandshakeManager{
|
||||
vpnIps: map[netip.Addr]*HandshakeHostInfo{},
|
||||
indexes: map[uint32]*HandshakeHostInfo{},
|
||||
mainHostMap: mainHostMap,
|
||||
lightHouse: lightHouse,
|
||||
outside: outside,
|
||||
config: config,
|
||||
trigger: make(chan netip.Addr, config.triggerBuffer),
|
||||
OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
|
||||
messageMetrics: config.messageMetrics,
|
||||
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
||||
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
||||
l: l,
|
||||
pqTable: fragment.NewTable[pqFragKey, pqFragSource](pqTableConfig),
|
||||
pqAnswered: newPQAnswered(hsTimeout(config.retries, config.tryInterval)),
|
||||
}
|
||||
pq := config.pq
|
||||
hm.pq.Store(&pq)
|
||||
hm.pqCookies = newPQCookies(time.Now())
|
||||
// Cookie replies are tiny, but a flood of spoofed fragments must not turn
|
||||
// into a flood of replies.
|
||||
hm.pqCookieLimiter, _ = ratelimit.New(256, time.Millisecond)
|
||||
return hm
|
||||
}
|
||||
|
||||
func (hm *HandshakeManager) Run(ctx context.Context) {
|
||||
@@ -147,6 +172,8 @@ func (hm *HandshakeManager) Run(ctx context.Context) {
|
||||
hm.handleOutbound(vpnIP, true)
|
||||
case now := <-clockSource.C:
|
||||
hm.NextOutboundHandshakeTimerTick(now)
|
||||
hm.pqTable.Expire(now)
|
||||
hm.pqAnswered.expire(now)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,7 +183,7 @@ func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *head
|
||||
// don't yet support) are dropped here rather than silently routed through
|
||||
// the IX path. Add a case when introducing a new pattern.
|
||||
switch h.Subtype {
|
||||
case header.HandshakeIXPSK0:
|
||||
case header.HandshakeIXPSK0, pqSubtype:
|
||||
// supported
|
||||
default:
|
||||
hm.l.Debug("dropping handshake with unsupported subtype",
|
||||
@@ -172,6 +199,11 @@ func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *head
|
||||
}
|
||||
}
|
||||
|
||||
if header.IsFragmented(h.Subtype) {
|
||||
hm.handleFragment(via, packet, h)
|
||||
return
|
||||
}
|
||||
|
||||
// First message of a new handshake. The wire format requires RemoteIndex
|
||||
// to be zero here (the initiator has no responder index to fill in yet),
|
||||
// and generateIndex never allocates 0, so any non-zero RemoteIndex on a
|
||||
@@ -183,7 +215,11 @@ func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *head
|
||||
"from", via, "remoteIndex", h.RemoteIndex)
|
||||
return
|
||||
}
|
||||
hm.beginHandshake(via, packet, h)
|
||||
if hm.pqConfig().require {
|
||||
hm.l.Debug("dropping classical handshake, post-quantum handshakes are required", "from", via)
|
||||
return
|
||||
}
|
||||
hm.beginHandshake(via, packet, h, 0)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -232,6 +268,9 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
"style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
|
||||
})
|
||||
}
|
||||
if hh.pq != nil {
|
||||
fields = append(fields, "pqInitiatorIndex", hh.pq.index)
|
||||
}
|
||||
hh.hostinfo.logger(hm.l).Info("Handshake timed out", fields...)
|
||||
hm.metricTimedOut.Inc(1)
|
||||
hm.DeleteHostInfo(hostinfo)
|
||||
@@ -241,25 +280,45 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
// Increment the counter to increase our delay, linear backoff
|
||||
hh.counter++
|
||||
|
||||
// Check if we have a handshake packet to transmit yet
|
||||
if !hh.ready {
|
||||
if !hm.buildStage0Packet(hh) {
|
||||
// Pick this attempt's style and make sure its first message exists. A PQ
|
||||
// attempt sends msg1 as fragments: now goes out immediately, later after the
|
||||
// repair delay, and every attempt offers fresh repair symbols.
|
||||
var now, later [][]byte
|
||||
var machine *handshake.Machine
|
||||
hh.lastPQ = hm.usePQ(hh, vpnIp, lighthouseTriggered)
|
||||
if hh.lastPQ {
|
||||
if hh.pq == nil && !hm.buildPQAttempt(hh) {
|
||||
hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
|
||||
return
|
||||
}
|
||||
var err error
|
||||
now, later, err = hh.pq.sender.Attempt(fragment.DefaultRepair(hh.pq.sender.Layout().K))
|
||||
if err != nil {
|
||||
hostinfo.logger(hm.l).Error("Failed to fragment handshake", "error", err)
|
||||
hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
|
||||
return
|
||||
}
|
||||
machine = hh.pq.machine
|
||||
} else {
|
||||
if !hh.ready {
|
||||
if !hm.buildStage0Packet(hh) {
|
||||
hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
|
||||
return
|
||||
}
|
||||
}
|
||||
// TODO: this hardcodes "always retransmit stage 0", which is correct for
|
||||
// IX (the initiator only ever sends one packet, msg1) but wrong the
|
||||
// moment a 3+ message pattern lands. The retry loop should resend the
|
||||
// most recent outgoing message, not always stage 0. That implies
|
||||
// HandshakeHostInfo tracking a single "currentOutbound" packet (bytes +
|
||||
// header metadata) that gets replaced as the handshake progresses,
|
||||
// instead of indexing into HandshakePacket.
|
||||
now = [][]byte{hostinfo.HandshakePacket[handshakePacketStage0]}
|
||||
machine = hh.machine
|
||||
}
|
||||
|
||||
// TODO: this hardcodes "always retransmit stage 0", which is correct for
|
||||
// IX (the initiator only ever sends one packet, msg1) but wrong the
|
||||
// moment a 3+ message pattern lands. The retry loop should resend the
|
||||
// most recent outgoing message, not always stage 0. That implies
|
||||
// HandshakeHostInfo tracking a single "currentOutbound" packet (bytes +
|
||||
// header metadata) that gets replaced as the handshake progresses,
|
||||
// instead of indexing into HandshakePacket.
|
||||
stage0 := hostinfo.HandshakePacket[handshakePacketStage0]
|
||||
hsFields := m{
|
||||
"stage": uint64(hh.machine.MessageIndex()),
|
||||
"style": header.SubTypeName(header.Handshake, hh.machine.Subtype()),
|
||||
"stage": uint64(machine.MessageIndex()),
|
||||
"style": header.SubTypeName(header.Handshake, machine.Subtype()),
|
||||
}
|
||||
|
||||
remotes := hostinfo.remotes.CopyAddrs(hm.mainHostMap.GetPreferredRanges())
|
||||
@@ -287,8 +346,10 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
// Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
|
||||
var sentTo []netip.AddrPort
|
||||
hostinfo.remotes.ForEach(hm.mainHostMap.GetPreferredRanges(), func(addr netip.AddrPort, _ bool) {
|
||||
hm.messageMetrics.Tx(header.Handshake, hh.machine.Subtype(), 1)
|
||||
err := hm.outside.WriteTo(stage0, addr)
|
||||
hm.messageMetrics.Tx(header.Handshake, machine.Subtype(), int64(len(now)+len(later)))
|
||||
err := hm.sendFragmented(now, later, func(p []byte) error {
|
||||
return hm.outside.WriteTo(p, addr)
|
||||
})
|
||||
if err != nil {
|
||||
// These repeat every attempt, so match the success log below and only shout when the remotes changed
|
||||
level := slog.LevelDebug
|
||||
@@ -324,7 +385,7 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
)
|
||||
}
|
||||
|
||||
hm.f.relayManager.StartRelays(hm.f, vpnIp, hh, stage0)
|
||||
hm.f.relayManager.StartRelays(hm.f, vpnIp, hh, now, later)
|
||||
|
||||
// If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
|
||||
if !lighthouseTriggered {
|
||||
@@ -534,6 +595,10 @@ func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
|
||||
func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
|
||||
for _, addr := range hostinfo.vpnAddrs {
|
||||
if cur, ok := hm.vpnIps[addr]; ok && cur.hostinfo == hostinfo {
|
||||
// A PQ attempt holds its own index alongside the hostinfo's.
|
||||
if idx := cur.pqIndex(); idx != 0 && hm.indexes[idx] == cur {
|
||||
delete(hm.indexes, idx)
|
||||
}
|
||||
delete(hm.vpnIps, addr)
|
||||
}
|
||||
}
|
||||
@@ -644,9 +709,8 @@ func hsTimeout(tries int64, interval time.Duration) time.Duration {
|
||||
return time.Duration(tries / 2 * ((2 * int64(interval)) + (tries-1)*int64(interval)))
|
||||
}
|
||||
|
||||
// buildStage0Packet creates the initial handshake packet for the initiator.
|
||||
func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
|
||||
cs := hm.f.pki.getCertState()
|
||||
// initiatingVersion picks the certificate version to initiate a handshake with.
|
||||
func (hm *HandshakeManager) initiatingVersion(hh *HandshakeHostInfo, cs *CertState) cert.Version {
|
||||
v := cs.DefaultVersion()
|
||||
if hh.initiatingVersionOverride != cert.VersionPre1 {
|
||||
v = hh.initiatingVersionOverride
|
||||
@@ -658,6 +722,13 @@ func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// buildStage0Packet creates the initial handshake packet for the initiator.
|
||||
func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
|
||||
cs := hm.f.pki.getCertState()
|
||||
v := hm.initiatingVersion(hh, cs)
|
||||
|
||||
cred := cs.GetCredential(v)
|
||||
if cred == nil {
|
||||
@@ -696,7 +767,10 @@ func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
|
||||
// beginHandshake handles an incoming handshake packet that doesn't match any
|
||||
// existing pending handshake. It creates a new responder Machine and processes
|
||||
// the first message.
|
||||
func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *header.H) {
|
||||
//
|
||||
// received is the number of bytes a fragmented msg1 arrived in, which bounds the
|
||||
// response sent back before the address is validated; 0 for unfragmented ones.
|
||||
func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *header.H, received int) {
|
||||
f := hm.f
|
||||
cs := f.pki.getCertState()
|
||||
|
||||
@@ -710,7 +784,7 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
machine, err := handshake.NewMachine(
|
||||
v, cs.GetCredential,
|
||||
hm.certVerifier(), func() (uint32, error) { return generateIndex(f.l) },
|
||||
false, header.HandshakeIXPSK0,
|
||||
false, h.Subtype,
|
||||
)
|
||||
if err != nil {
|
||||
f.l.Error("Failed to create handshake machine", "from", via, "error", err)
|
||||
@@ -719,12 +793,7 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
|
||||
response, result, err := machine.ProcessPacket(nil, packet)
|
||||
if err != nil {
|
||||
level := slog.LevelError
|
||||
if errors.Is(err, cert.ErrBlockListed) {
|
||||
level = slog.LevelDebug
|
||||
hm.metricRejectedBlocklisted.Inc(1)
|
||||
}
|
||||
f.l.Log(context.Background(), level, "Failed to process handshake packet", "from", via, "error", err)
|
||||
f.l.Error("Failed to process handshake packet", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -805,11 +874,15 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
|
||||
existing, err := hm.CheckAndComplete(hostinfo, handshakePacketStage0, f)
|
||||
if err != nil {
|
||||
hm.handleCheckAndCompleteError(err, existing, hostinfo, via)
|
||||
hm.handleCheckAndCompleteError(err, existing, hostinfo, via, machine.Subtype(), received)
|
||||
return
|
||||
}
|
||||
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false)
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false, received)
|
||||
if header.IsFragmented(machine.Subtype()) {
|
||||
hm.pqAnswered.add(packet[header.Len:], hostinfo, time.Now())
|
||||
}
|
||||
hm.notePQPeer(machine.Subtype(), vpnAddrs)
|
||||
hostinfo.remotes.RefreshFromHandshake(vpnAddrs)
|
||||
|
||||
// Don't wait for UpdateWorker
|
||||
@@ -820,23 +893,32 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
|
||||
// continueHandshake feeds an incoming packet to an existing pending handshake Machine.
|
||||
func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostInfo, packet []byte) {
|
||||
f := hm.f
|
||||
|
||||
hh.Lock()
|
||||
defer hh.Unlock()
|
||||
|
||||
// Re-verify hh is still tracked. Between queryIndex returning and us taking
|
||||
// hh.Lock, handleOutbound may have timed out and deleted it. Once we hold
|
||||
// hh.Lock no other deleter can race our index: handleOutbound also takes
|
||||
// hh.Lock first, and handleRecvError targets a main-hostmap entry with a
|
||||
// different localIndexId.
|
||||
hm.RLock()
|
||||
cur, ok := hm.indexes[hh.hostinfo.localIndexId]
|
||||
hm.RUnlock()
|
||||
if !ok || cur != hh {
|
||||
if !hm.stillPending(hh, hh.hostinfo.localIndexId) {
|
||||
return
|
||||
}
|
||||
hm.processResponse(via, hh, hh.machine, packet)
|
||||
}
|
||||
|
||||
// stillPending re-verifies hh is still tracked under index. Between queryIndex
|
||||
// returning and the caller taking hh.Lock, handleOutbound may have timed out and
|
||||
// deleted it. Once hh.Lock is held no other deleter can race the index:
|
||||
// handleOutbound also takes hh.Lock first, and handleRecvError targets a
|
||||
// main-hostmap entry with a different localIndexId. The caller must hold hh.Lock.
|
||||
func (hm *HandshakeManager) stillPending(hh *HandshakeHostInfo, index uint32) bool {
|
||||
hm.RLock()
|
||||
defer hm.RUnlock()
|
||||
cur, ok := hm.indexes[index]
|
||||
return ok && cur == hh
|
||||
}
|
||||
|
||||
// processResponse runs a responder's message through one of the initiator's
|
||||
// pending attempts and completes the tunnel when the handshake finishes. The
|
||||
// caller must hold hh.Lock.
|
||||
func (hm *HandshakeManager) processResponse(via ViaSender, hh *HandshakeHostInfo, machine *handshake.Machine, packet []byte) {
|
||||
f := hm.f
|
||||
hostinfo := hh.hostinfo
|
||||
if !via.IsRelayed {
|
||||
if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
|
||||
@@ -846,7 +928,6 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
||||
}
|
||||
}
|
||||
|
||||
machine := hh.machine
|
||||
if machine == nil {
|
||||
f.l.Error("No handshake machine available for continuation",
|
||||
"vpnAddrs", hostinfo.vpnAddrs, "from", via)
|
||||
@@ -856,9 +937,6 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
||||
|
||||
response, result, err := machine.ProcessPacket(nil, packet)
|
||||
if err != nil {
|
||||
if errors.Is(err, cert.ErrBlockListed) {
|
||||
hm.metricRejectedBlocklisted.Inc(1)
|
||||
}
|
||||
// Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
|
||||
if machine.Failed() {
|
||||
f.l.Warn("Failed to process handshake packet, abandoning",
|
||||
@@ -872,7 +950,7 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
||||
}
|
||||
|
||||
if response != nil {
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false)
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false, 0)
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
@@ -985,7 +1063,10 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
||||
hostinfo.vpnAddrs = vpnAddrs
|
||||
hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
|
||||
|
||||
// The classical and PQ attempts each hold an index; keep the one that won.
|
||||
hm.settleIndex(hh, result.LocalIndex)
|
||||
hm.Complete(hostinfo, f)
|
||||
hm.notePQPeer(machine.Subtype(), vpnAddrs)
|
||||
|
||||
if len(hh.packetStore) > 0 {
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
@@ -1064,20 +1145,23 @@ func (hm *HandshakeManager) validatePeerCert(via ViaSender, remoteCert *cert.Cac
|
||||
// cached is true when msg is a stored response being retransmitted because
|
||||
// the peer's stage-1 retransmit landed (the ErrAlreadySeen path); false on a
|
||||
// fresh response.
|
||||
func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool) {
|
||||
//
|
||||
// received is the number of bytes a fragmented msg1 arrived in; it bounds what a
|
||||
// fragmented response may send back. It is ignored for unfragmented subtypes.
|
||||
func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool, received int) {
|
||||
if msg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
f := hm.f
|
||||
f.messageMetrics.Tx(header.Handshake, header.MessageSubType(msg[1]), 1)
|
||||
subtype := header.MessageSubType(msg[1])
|
||||
|
||||
// Common log fields. peerCert may be nil during intermediate
|
||||
// multi-message flows (handshake hasn't completed yet); skip the cert
|
||||
// block if so.
|
||||
logFields := []any{
|
||||
"vpnAddrs", hostinfo.vpnAddrs,
|
||||
"handshake", m{"stage": uint64(2), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)},
|
||||
"handshake", m{"stage": uint64(2), "style": header.SubTypeName(header.Handshake, subtype)},
|
||||
"cached", cached,
|
||||
"initiatorIndex", hostinfo.remoteIndexId,
|
||||
"responderIndex", hostinfo.localIndexId,
|
||||
@@ -1091,6 +1175,17 @@ func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hos
|
||||
)
|
||||
}
|
||||
|
||||
if header.IsFragmented(subtype) {
|
||||
fields := append(logFields, "from", via)
|
||||
if err := hm.sendFragmentedResponse(via, msg, hostinfo, cached, received); err != nil {
|
||||
f.l.Debug("Did not send handshake message", append(fields, "error", err)...)
|
||||
} else {
|
||||
f.l.Info("Handshake message sent", fields...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
f.messageMetrics.Tx(header.Handshake, subtype, 1)
|
||||
if !via.IsRelayed {
|
||||
fields := append(logFields, "from", via)
|
||||
err := f.outside.WriteTo(msg, via.UdpAddr)
|
||||
@@ -1117,10 +1212,10 @@ func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hos
|
||||
// This only fires from the responder-side beginHandshake path, after the
|
||||
// peer cert has been validated and ConnectionState populated, so peerCert
|
||||
// is always non-nil for the cases that log it.
|
||||
func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hostinfo *HostInfo, via ViaSender) {
|
||||
func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hostinfo *HostInfo, via ViaSender, subtype header.MessageSubType, received int) {
|
||||
f := hm.f
|
||||
peerCert := hostinfo.ConnectionState.peerCert
|
||||
hsFields := m{"stage": uint64(1), "style": header.SubTypeName(header.Handshake, header.HandshakeIXPSK0)}
|
||||
hsFields := m{"stage": uint64(1), "style": header.SubTypeName(header.Handshake, subtype)}
|
||||
|
||||
switch err {
|
||||
case ErrAlreadySeen:
|
||||
@@ -1131,7 +1226,7 @@ func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hos
|
||||
// ephemeral keys; a freshly-built one would have different keys and break
|
||||
// the tunnel even though both sides "completed" the handshake.
|
||||
if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
|
||||
hm.sendHandshakeResponse(via, msg, existing, true)
|
||||
hm.sendHandshakeResponse(via, msg, existing, true, received)
|
||||
}
|
||||
|
||||
case ErrExistingHostInfo:
|
||||
|
||||
@@ -0,0 +1,699 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
const (
|
||||
// pqSubtype is the post-quantum handshake this node speaks.
|
||||
pqSubtype = header.HandshakeIXPSK2MLKEM1024
|
||||
|
||||
// DefaultPQRepairDelay is how long repair fragments trail the data fragments.
|
||||
DefaultPQRepairDelay = 10 * time.Millisecond
|
||||
|
||||
// pqAmplification bounds what a responder sends in reply to an unvalidated
|
||||
// address, as a multiple of what it received from it.
|
||||
pqAmplification = 3
|
||||
)
|
||||
|
||||
// pqTableConfig bounds the responder's reassembly of msg1 fragments from senders
|
||||
// that have not authenticated yet.
|
||||
var pqTableConfig = fragment.TableConfig{
|
||||
MaxBytes: 4 << 20,
|
||||
MaxEntries: 1024,
|
||||
MaxPerSource: 4,
|
||||
MaxMsgLen: 16384,
|
||||
TTL: 3 * time.Second,
|
||||
}
|
||||
|
||||
type pqHandshakeConfig struct {
|
||||
initiate bool // start PQ handshakes
|
||||
accept bool // answer PQ handshakes
|
||||
require bool // only PQ handshakes, in either direction
|
||||
sticky bool // never fall back to classical for a peer that completed PQ
|
||||
repairDelay time.Duration // delay between data and repair fragments
|
||||
}
|
||||
|
||||
func pqHandshakeConfigFrom(c *config.C) pqHandshakeConfig {
|
||||
cfg := pqHandshakeConfig{
|
||||
initiate: c.GetBool("handshakes.pq.initiate", false),
|
||||
accept: c.GetBool("handshakes.pq.accept", false),
|
||||
require: c.GetBool("handshakes.pq.require", false),
|
||||
sticky: c.GetBool("handshakes.pq.sticky", false),
|
||||
repairDelay: c.GetDuration("handshakes.pq.repair_delay", DefaultPQRepairDelay),
|
||||
}
|
||||
if cfg.require {
|
||||
cfg.initiate = true
|
||||
cfg.accept = true
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// pqConfig returns the post-quantum settings in effect.
|
||||
func (hm *HandshakeManager) pqConfig() *pqHandshakeConfig {
|
||||
return hm.pq.Load()
|
||||
}
|
||||
|
||||
// reloadPQ applies changed post-quantum settings. Handshakes already in flight
|
||||
// keep going; the new settings apply to the next attempt and packet.
|
||||
func (hm *HandshakeManager) reloadPQ(c *config.C) {
|
||||
if !c.HasChanged("handshakes.pq") {
|
||||
return
|
||||
}
|
||||
old := hm.pqConfig()
|
||||
cfg := pqHandshakeConfigFrom(c)
|
||||
hm.pq.Store(&cfg)
|
||||
hm.l.Info("Post-quantum handshake settings changed",
|
||||
"initiate", cfg.initiate, "oldInitiate", old.initiate,
|
||||
"accept", cfg.accept, "oldAccept", old.accept,
|
||||
"require", cfg.require, "oldRequire", old.require,
|
||||
"sticky", cfg.sticky, "oldSticky", old.sticky,
|
||||
"repairDelay", cfg.repairDelay, "oldRepairDelay", old.repairDelay,
|
||||
)
|
||||
}
|
||||
|
||||
// pqAttempt is the initiator's post-quantum attempt for a pending handshake. It
|
||||
// lives alongside the classical attempt in HandshakeHostInfo and has its own
|
||||
// local index, so whichever answer arrives first wins.
|
||||
type pqAttempt struct {
|
||||
machine *handshake.Machine
|
||||
index uint32
|
||||
sender *fragment.Sender
|
||||
msg2 *fragment.Assembly
|
||||
cookieResendAt time.Time // last resend prompted by a cookie reply
|
||||
heard bool // a msg2 fragment or cookie reply arrived, so the peer speaks PQ
|
||||
}
|
||||
|
||||
// pqFragKey identifies one msg1 being reassembled.
|
||||
type pqFragKey struct {
|
||||
addr netip.AddrPort
|
||||
relay uint32
|
||||
fragID uint32
|
||||
}
|
||||
|
||||
// pqFragSource groups msg1 reassemblies for the per-source quota: an IPv4 /32,
|
||||
// an IPv6 /64, or one relay channel.
|
||||
type pqFragSource struct {
|
||||
prefix netip.Prefix
|
||||
relay uint32
|
||||
}
|
||||
|
||||
func pqFragKeyFor(via ViaSender, fragID uint32) (pqFragKey, pqFragSource) {
|
||||
if via.IsRelayed {
|
||||
return pqFragKey{relay: via.relay.LocalIndex, fragID: fragID},
|
||||
pqFragSource{relay: via.relay.LocalIndex}
|
||||
}
|
||||
addr := via.UdpAddr.Addr().Unmap()
|
||||
bits := 64
|
||||
if addr.Is4() {
|
||||
bits = 32
|
||||
}
|
||||
prefix, _ := addr.Prefix(bits)
|
||||
return pqFragKey{addr: via.UdpAddr, fragID: fragID}, pqFragSource{prefix: prefix}
|
||||
}
|
||||
|
||||
// reassembled rebuilds the packet the handshake Machine expects from the header
|
||||
// of a fragment and the decoded message.
|
||||
func reassembled(h *header.H, msg []byte) []byte {
|
||||
p := make([]byte, header.Len, header.Len+len(msg))
|
||||
header.Encode(p, header.Version, header.Handshake, h.Subtype, h.RemoteIndex, h.MessageCounter)
|
||||
return append(p, msg...)
|
||||
}
|
||||
|
||||
// usePQ decides whether this outbound attempt is post-quantum. A peer that does
|
||||
// not speak PQ silently drops it, so timer retries alternate between PQ and
|
||||
// classical, starting with PQ. An attempt triggered early by a lighthouse reply
|
||||
// is sending to addresses nothing has been sent to yet, and a new path gets the
|
||||
// PQ attempt first. With require, or for a peer that completed a PQ handshake
|
||||
// when sticky is on, every attempt is PQ. Once anything has come back for the PQ
|
||||
// attempt the peer evidently speaks PQ, and a classical attempt would only race
|
||||
// it, so classical stops getting turns.
|
||||
func (hm *HandshakeManager) usePQ(hh *HandshakeHostInfo, vpnIp netip.Addr, triggered bool) bool {
|
||||
cfg := hm.pqConfig()
|
||||
switch {
|
||||
case !cfg.initiate:
|
||||
return false
|
||||
case cfg.require:
|
||||
return true
|
||||
case hh.pq != nil && hh.pq.heard:
|
||||
return true
|
||||
case cfg.sticky:
|
||||
if _, ok := hm.pqPeers.Load(vpnIp); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return hh.counter <= 1 || triggered || !hh.lastPQ
|
||||
}
|
||||
|
||||
// relayEstablished pushes the pending handshake with target through a relay that
|
||||
// just came up, rather than leaving it for the next retry. Nothing has gone over
|
||||
// the relay yet, so like any new path it gets the PQ attempt first, which then
|
||||
// counts as the PQ turn: the next retry is classical, as if it had been sent on
|
||||
// schedule. Without this, relays coming up while the first attempt is in flight
|
||||
// handed every relayed handshake to the classical retry.
|
||||
func (hm *HandshakeManager) relayEstablished(target netip.Addr, relayHI *HostInfo, relay *Relay) {
|
||||
hh := hm.queryVpnIp(target)
|
||||
if hh == nil {
|
||||
return
|
||||
}
|
||||
hh.Lock()
|
||||
defer hh.Unlock()
|
||||
if hm.queryVpnIp(target) != hh {
|
||||
return
|
||||
}
|
||||
|
||||
var now, later [][]byte
|
||||
switch {
|
||||
case hh.pq != nil:
|
||||
var err error
|
||||
now, later, err = hh.pq.sender.Attempt(fragment.DefaultRepair(hh.pq.sender.Layout().K))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hh.lastPQ = true
|
||||
case hh.ready:
|
||||
now = [][]byte{hh.hostinfo.HandshakePacket[handshakePacketStage0]}
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
f := hm.f
|
||||
hh.hostinfo.logger(hm.l).Info("Send handshake via new relay", "relay", relayHI.vpnAddrs[0])
|
||||
_ = hm.sendFragmented(now, later, func(p []byte) error {
|
||||
f.SendVia(relayHI, relay, p, make([]byte, 12), make([]byte, mtu), false, 0)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// buildPQAttempt creates the initiator's PQ Machine and msg1 sender.
|
||||
func (hm *HandshakeManager) buildPQAttempt(hh *HandshakeHostInfo) bool {
|
||||
cs := hm.f.pki.getCertState()
|
||||
v := hm.initiatingVersion(hh, cs)
|
||||
if cs.GetCredential(v) == nil {
|
||||
hm.f.l.Error("Unable to handshake with host because no certificate is available",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "certVersion", v)
|
||||
return false
|
||||
}
|
||||
|
||||
pq := &pqAttempt{}
|
||||
machine, err := handshake.NewMachine(
|
||||
v, cs.GetCredential,
|
||||
hm.certVerifier(), func() (uint32, error) { return hm.allocatePQIndex(hh, pq) },
|
||||
true, pqSubtype,
|
||||
)
|
||||
if err != nil {
|
||||
hm.f.l.Error("Failed to create handshake machine",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
|
||||
return false
|
||||
}
|
||||
|
||||
msg, err := machine.Initiate(nil)
|
||||
if err != nil {
|
||||
hm.f.l.Error("Failed to initiate handshake",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
|
||||
hm.releasePQIndex(hh, pq)
|
||||
return false
|
||||
}
|
||||
|
||||
sender, err := fragment.NewSender(msg[header.Len:], pqSubtype, 0, 1, pq.index)
|
||||
if err != nil {
|
||||
hm.f.l.Error("Failed to fragment handshake",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
|
||||
hm.releasePQIndex(hh, pq)
|
||||
return false
|
||||
}
|
||||
|
||||
pq.machine = machine
|
||||
pq.sender = sender
|
||||
hh.pq = pq
|
||||
return true
|
||||
}
|
||||
|
||||
// allocatePQIndex registers a local index for the PQ attempt. Unlike
|
||||
// allocateIndex it leaves hostinfo.localIndexId alone; that is settled when one
|
||||
// of the attempts completes.
|
||||
func (hm *HandshakeManager) allocatePQIndex(hh *HandshakeHostInfo, pq *pqAttempt) (uint32, error) {
|
||||
hm.mainHostMap.RLock()
|
||||
defer hm.mainHostMap.RUnlock()
|
||||
hm.Lock()
|
||||
defer hm.Unlock()
|
||||
|
||||
for range 32 {
|
||||
index, err := generateIndex(hm.l)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
_, inPending := hm.indexes[index]
|
||||
_, inMain := hm.mainHostMap.Indexes[index]
|
||||
|
||||
if !inMain && !inPending {
|
||||
pq.index = index
|
||||
hm.indexes[index] = hh
|
||||
return index, nil
|
||||
}
|
||||
}
|
||||
|
||||
return 0, errors.New("failed to generate unique localIndexId")
|
||||
}
|
||||
|
||||
func (hm *HandshakeManager) releasePQIndex(hh *HandshakeHostInfo, pq *pqAttempt) {
|
||||
hm.Lock()
|
||||
defer hm.Unlock()
|
||||
if pq.index != 0 && hm.indexes[pq.index] == hh {
|
||||
delete(hm.indexes, pq.index)
|
||||
}
|
||||
}
|
||||
|
||||
// settleIndex makes winner the hostinfo's local index and releases the index of
|
||||
// the attempt that lost.
|
||||
func (hm *HandshakeManager) settleIndex(hh *HandshakeHostInfo, winner uint32) {
|
||||
hm.Lock()
|
||||
defer hm.Unlock()
|
||||
for _, idx := range []uint32{hh.hostinfo.localIndexId, hh.pqIndex()} {
|
||||
if idx != 0 && idx != winner && hm.indexes[idx] == hh {
|
||||
delete(hm.indexes, idx)
|
||||
}
|
||||
}
|
||||
hh.hostinfo.localIndexId = winner
|
||||
}
|
||||
|
||||
func (hh *HandshakeHostInfo) pqIndex() uint32 {
|
||||
if hh.pq == nil {
|
||||
return 0
|
||||
}
|
||||
return hh.pq.index
|
||||
}
|
||||
|
||||
// handleFragment routes one fragment of a PQ handshake message.
|
||||
func (hm *HandshakeManager) handleFragment(via ViaSender, packet []byte, h *header.H) {
|
||||
if h.MessageCounter == pqCookieCounter {
|
||||
hm.handleCookie(via, packet, h)
|
||||
return
|
||||
}
|
||||
|
||||
fh, sym, err := fragment.Parse(packet[header.Len:])
|
||||
if err != nil {
|
||||
hm.l.Debug("dropping malformed handshake fragment", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
switch h.MessageCounter {
|
||||
case 1:
|
||||
if !hm.pqConfig().accept {
|
||||
hm.l.Debug("dropping post-quantum handshake, not accepting them", "from", via)
|
||||
return
|
||||
}
|
||||
if h.RemoteIndex != 0 {
|
||||
hm.l.Debug("dropping stage-1 handshake with non-zero RemoteIndex",
|
||||
"from", via, "remoteIndex", h.RemoteIndex)
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
key, src := pqFragKeyFor(via, fh.FragID)
|
||||
if hm.pqTable.Load() >= pqCookieLoad && !(fh.HasCookie() && hm.pqCookies.valid(key, fh.Cookie, now)) {
|
||||
hm.sendCookie(via, fh, key, len(packet), now)
|
||||
return
|
||||
}
|
||||
res, err := hm.pqTable.Add(key, src, now, fh, sym)
|
||||
if err != nil {
|
||||
hm.l.Debug("dropping handshake fragment", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
if existing := hm.pqAnswered.lookup(res.Msg, time.Now()); existing != nil {
|
||||
// Already answered: resend, rate limited, with fresh symbols.
|
||||
if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
|
||||
hm.sendHandshakeResponse(via, msg, existing, true, res.Received)
|
||||
}
|
||||
return
|
||||
}
|
||||
hm.beginHandshake(via, reassembled(h, res.Msg), h, res.Received)
|
||||
|
||||
case 2:
|
||||
if hh := hm.queryIndex(h.RemoteIndex); hh != nil {
|
||||
hm.continuePQ(via, hh, h, fh, sym)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// continuePQ collects msg2 fragments for the initiator's PQ attempt.
|
||||
func (hm *HandshakeManager) continuePQ(via ViaSender, hh *HandshakeHostInfo, h *header.H, fh fragment.Header, sym []byte) {
|
||||
hh.Lock()
|
||||
defer hh.Unlock()
|
||||
|
||||
pq := hh.pq
|
||||
if pq == nil || pq.index != h.RemoteIndex || !hm.stillPending(hh, pq.index) {
|
||||
return
|
||||
}
|
||||
pq.heard = true
|
||||
|
||||
if pq.msg2 == nil {
|
||||
a, err := fragment.NewAssembly(fh)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pq.msg2 = a
|
||||
}
|
||||
ready, err := pq.msg2.Add(fh, sym)
|
||||
if errors.Is(err, fragment.ErrMismatch) {
|
||||
// The responder's FragID and MsgLen never change, so this is a stray or a
|
||||
// forgery. Start over from this fragment rather than wedge.
|
||||
pq.msg2 = nil
|
||||
return
|
||||
}
|
||||
if err != nil || !ready {
|
||||
return
|
||||
}
|
||||
|
||||
msg, err := pq.msg2.Decode()
|
||||
pq.msg2 = nil
|
||||
if err != nil {
|
||||
hm.l.Debug("failed to decode handshake fragments", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
hm.processResponse(via, hh, pq.machine, reassembled(h, msg))
|
||||
}
|
||||
|
||||
// sendFragmented sends packets to a peer: now immediately and later after the
|
||||
// repair delay. It returns the first error from the immediate sends; errors from
|
||||
// delayed sends are only logged.
|
||||
func (hm *HandshakeManager) sendFragmented(now, later [][]byte, send func([]byte) error) error {
|
||||
var first error
|
||||
for _, p := range now {
|
||||
if err := send(p); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
sendLater := func() {
|
||||
for _, p := range later {
|
||||
if err := send(p); err != nil {
|
||||
hm.l.Debug("Failed to send handshake repair fragment", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
delay := hm.pqConfig().repairDelay
|
||||
switch {
|
||||
case len(later) == 0:
|
||||
case delay <= 0:
|
||||
sendLater()
|
||||
default:
|
||||
time.AfterFunc(delay, sendLater)
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
// sendFragmentedResponse sends the responder's msg2 as fragments. A resend of a
|
||||
// cached response (cached) offers fresh symbols and is rate limited to one per
|
||||
// retry interval. received is how many bytes the triggering msg1 took, which
|
||||
// bounds what may be sent back before the address is validated.
|
||||
func (hm *HandshakeManager) sendFragmentedResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool, received int) error {
|
||||
now := time.Now()
|
||||
if cached {
|
||||
last := hostinfo.handshakeResendAt.Load()
|
||||
if now.UnixNano()-last < int64(hm.config.tryInterval) ||
|
||||
!hostinfo.handshakeResendAt.CompareAndSwap(last, now.UnixNano()) {
|
||||
return errors.New("handshake response resend rate limited")
|
||||
}
|
||||
} else {
|
||||
hostinfo.handshakeResendAt.Store(now.UnixNano())
|
||||
}
|
||||
|
||||
var h header.H
|
||||
if err := h.Parse(msg); err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := fragment.NewSender(msg[header.Len:], h.Subtype, h.RemoteIndex, h.MessageCounter, hostinfo.localIndexId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
l := s.Layout()
|
||||
repair := fragment.DefaultRepair(l.K)
|
||||
if received > 0 {
|
||||
pktLen := header.Len + fragment.HeaderLen + l.SymbolSize
|
||||
budget := pqAmplification * received / pktLen
|
||||
if budget < l.K {
|
||||
return errors.New("handshake response exceeds the amplification budget")
|
||||
}
|
||||
repair = min(repair, budget-l.K)
|
||||
}
|
||||
|
||||
n := uint32(l.K + repair)
|
||||
s.SetNext(int(hostinfo.handshakeNextSymbol.Add(n) - n))
|
||||
pkts, later, err := s.Attempt(repair)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if via.IsRelayed {
|
||||
if via.relay == nil {
|
||||
return errors.New("both addr and via.relay are nil")
|
||||
}
|
||||
// We received a valid handshake on this relay, so make sure the relay
|
||||
// state reflects that, in case it had been marked Disestablished.
|
||||
hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
|
||||
via.relayHI.relayState.UpdateRelayForByIdxState(via.relay.LocalIndex, Established)
|
||||
}
|
||||
hm.f.messageMetrics.Tx(header.Handshake, h.Subtype, int64(len(pkts)+len(later)))
|
||||
return hm.sendFragmented(pkts, later, hm.sendTo(via))
|
||||
}
|
||||
|
||||
// notePQPeer remembers peers that completed a PQ handshake, for sticky mode.
|
||||
func (hm *HandshakeManager) notePQPeer(subtype header.MessageSubType, vpnAddrs []netip.Addr) {
|
||||
if !hm.pqConfig().sticky || subtype != pqSubtype {
|
||||
return
|
||||
}
|
||||
for _, a := range vpnAddrs {
|
||||
hm.pqPeers.Store(a, struct{}{})
|
||||
}
|
||||
if hm.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hm.l.Debug("Remembering post-quantum peer", "vpnAddrs", vpnAddrs)
|
||||
}
|
||||
}
|
||||
|
||||
// pqAnswered remembers the msg1s a responder recently answered, keyed by hash,
|
||||
// so a repeat is recognised before any noise, KEM or certificate work. Repeats
|
||||
// are routine: the trailing repair fragments of an attempt rebuild a msg1 that
|
||||
// its data fragments already completed, and a retrying initiator offers fresh
|
||||
// symbols for the same msg1. Entries only exist for completed handshakes, which
|
||||
// need a valid certificate, and live as long as an initiator keeps retrying.
|
||||
type pqAnswered struct {
|
||||
sync.Mutex
|
||||
ttl time.Duration
|
||||
entries map[[sha256.Size]byte]pqAnsweredEntry
|
||||
}
|
||||
|
||||
type pqAnsweredEntry struct {
|
||||
hostinfo *HostInfo
|
||||
at time.Time
|
||||
}
|
||||
|
||||
const pqAnsweredMax = 4096
|
||||
|
||||
func newPQAnswered(ttl time.Duration) *pqAnswered {
|
||||
return &pqAnswered{ttl: ttl, entries: map[[sha256.Size]byte]pqAnsweredEntry{}}
|
||||
}
|
||||
|
||||
func (a *pqAnswered) add(msg1 []byte, hostinfo *HostInfo, now time.Time) {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
if len(a.entries) >= pqAnsweredMax {
|
||||
for k := range a.entries {
|
||||
delete(a.entries, k)
|
||||
break
|
||||
}
|
||||
}
|
||||
a.entries[sha256.Sum256(msg1)] = pqAnsweredEntry{hostinfo: hostinfo, at: now}
|
||||
}
|
||||
|
||||
func (a *pqAnswered) lookup(msg1 []byte, now time.Time) *HostInfo {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
e, ok := a.entries[sha256.Sum256(msg1)]
|
||||
if !ok || now.Sub(e.at) > a.ttl {
|
||||
return nil
|
||||
}
|
||||
return e.hostinfo
|
||||
}
|
||||
|
||||
func (a *pqAnswered) expire(now time.Time) {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
for k, e := range a.entries {
|
||||
if now.Sub(e.at) > a.ttl {
|
||||
delete(a.entries, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A responder whose msg1 table is under load stops keeping state for senders
|
||||
// that have not shown they receive at their address. It answers a fragment
|
||||
// without a valid cookie with a cookie reply and keeps nothing; the initiator
|
||||
// resends with the cookie attached. This is WireGuard's under-load cookie, QUIC's
|
||||
// Retry and SCTP's state cookie: one extra round trip, only while under attack.
|
||||
const (
|
||||
// pqCookieLoad is the table load above which msg1 fragments need a cookie.
|
||||
pqCookieLoad = 0.5
|
||||
|
||||
// pqCookieCounter marks a cookie reply in the header's message counter.
|
||||
// Handshake messages count from 1.
|
||||
pqCookieCounter = 0
|
||||
|
||||
// pqCookieRotate is how often the cookie secret changes. A cookie stays
|
||||
// valid for between one and two rotations.
|
||||
pqCookieRotate = 2 * time.Minute
|
||||
|
||||
pqCookieReplyLen = header.Len + fragment.CookieLen
|
||||
)
|
||||
|
||||
// pqCookies mints and checks cookies: an HMAC over the sender's address (or relay
|
||||
// channel) and FragID under a rotating secret, with the previous secret still
|
||||
// accepted.
|
||||
type pqCookies struct {
|
||||
sync.Mutex
|
||||
secrets [2][32]byte
|
||||
rotatedAt time.Time
|
||||
}
|
||||
|
||||
func newPQCookies(now time.Time) *pqCookies {
|
||||
c := &pqCookies{rotatedAt: now}
|
||||
_, _ = rand.Read(c.secrets[0][:])
|
||||
_, _ = rand.Read(c.secrets[1][:])
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *pqCookies) rotate(now time.Time) {
|
||||
if now.Sub(c.rotatedAt) < pqCookieRotate {
|
||||
return
|
||||
}
|
||||
c.secrets[1] = c.secrets[0]
|
||||
_, _ = rand.Read(c.secrets[0][:])
|
||||
c.rotatedAt = now
|
||||
}
|
||||
|
||||
func cookieMAC(secret []byte, key pqFragKey) fragment.Cookie {
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
addr := key.addr.Addr().As16()
|
||||
mac.Write(addr[:])
|
||||
var b [10]byte
|
||||
binary.BigEndian.PutUint16(b[0:], key.addr.Port())
|
||||
binary.BigEndian.PutUint32(b[2:], key.relay)
|
||||
binary.BigEndian.PutUint32(b[6:], key.fragID)
|
||||
mac.Write(b[:])
|
||||
var c fragment.Cookie
|
||||
copy(c[:], mac.Sum(nil))
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *pqCookies) make(key pqFragKey, now time.Time) fragment.Cookie {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.rotate(now)
|
||||
return cookieMAC(c.secrets[0][:], key)
|
||||
}
|
||||
|
||||
func (c *pqCookies) valid(key pqFragKey, cookie fragment.Cookie, now time.Time) bool {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.rotate(now)
|
||||
for _, s := range c.secrets {
|
||||
want := cookieMAC(s[:], key)
|
||||
if hmac.Equal(want[:], cookie[:]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// sendCookie answers a msg1 fragment that arrived without a valid cookie while
|
||||
// under load. The reply is never larger than what triggered it, and replies are
|
||||
// rate limited as a whole.
|
||||
func (hm *HandshakeManager) sendCookie(via ViaSender, fh fragment.Header, key pqFragKey, received int, now time.Time) {
|
||||
if received < pqCookieReplyLen {
|
||||
return
|
||||
}
|
||||
if _, ok := hm.pqCookieLimiter.Allow(); !ok {
|
||||
return
|
||||
}
|
||||
c := hm.pqCookies.make(key, now)
|
||||
reply := make([]byte, header.Len, pqCookieReplyLen)
|
||||
header.Encode(reply, header.Version, header.Handshake, pqSubtype, fh.FragID, pqCookieCounter)
|
||||
reply = append(reply, c[:]...)
|
||||
hm.f.messageMetrics.Tx(header.Handshake, pqSubtype, 1)
|
||||
if err := hm.sendTo(via)(reply); err != nil {
|
||||
hm.l.Debug("Failed to send handshake cookie", "to", via, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleCookie attaches a responder's cookie to the PQ attempt it names and
|
||||
// resends right away, at most once per retry interval, rather than waiting for
|
||||
// the next attempt.
|
||||
func (hm *HandshakeManager) handleCookie(via ViaSender, packet []byte, h *header.H) {
|
||||
if len(packet) != pqCookieReplyLen {
|
||||
return
|
||||
}
|
||||
hh := hm.queryIndex(h.RemoteIndex)
|
||||
if hh == nil {
|
||||
return
|
||||
}
|
||||
hh.Lock()
|
||||
defer hh.Unlock()
|
||||
|
||||
pq := hh.pq
|
||||
if pq == nil || pq.index != h.RemoteIndex || !hm.stillPending(hh, pq.index) {
|
||||
return
|
||||
}
|
||||
var c fragment.Cookie
|
||||
copy(c[:], packet[header.Len:])
|
||||
pq.sender.SetCookie(c)
|
||||
pq.heard = true
|
||||
|
||||
now := time.Now()
|
||||
if now.Sub(pq.cookieResendAt) < hm.config.tryInterval {
|
||||
return
|
||||
}
|
||||
pq.cookieResendAt = now
|
||||
pkts, later, err := pq.sender.Attempt(fragment.DefaultRepair(pq.sender.Layout().K))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hm.messageMetrics.Tx(header.Handshake, pqSubtype, int64(len(pkts)+len(later)))
|
||||
if err := hm.sendFragmented(pkts, later, hm.sendTo(via)); err != nil {
|
||||
hm.l.Debug("Failed to resend handshake with cookie", "to", via, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// sendTo returns a function sending a packet back the way via came: directly, or
|
||||
// through the relay it arrived on.
|
||||
func (hm *HandshakeManager) sendTo(via ViaSender) func([]byte) error {
|
||||
f := hm.f
|
||||
if !via.IsRelayed {
|
||||
return func(p []byte) error {
|
||||
return f.outside.WriteTo(p, via.UdpAddr)
|
||||
}
|
||||
}
|
||||
return func(p []byte) error {
|
||||
if via.relay == nil {
|
||||
return errors.New("both addr and via.relay are nil")
|
||||
}
|
||||
f.SendVia(via.relayHI, via.relay, p, make([]byte, 12), make([]byte, mtu), false, 0)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// recordingConn captures what is written to it.
|
||||
type recordingConn struct {
|
||||
udp.NoopConn
|
||||
sync.Mutex
|
||||
sent [][]byte
|
||||
}
|
||||
|
||||
func (c *recordingConn) WriteTo(b []byte, _ netip.AddrPort) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.sent = append(c.sent, append([]byte(nil), b...))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *recordingConn) take() [][]byte {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
s := c.sent
|
||||
c.sent = nil
|
||||
return s
|
||||
}
|
||||
|
||||
func newPQTestManager(t *testing.T) (*HandshakeManager, *recordingConn) {
|
||||
l := test.NewLogger()
|
||||
conn := &recordingConn{}
|
||||
cfg := defaultHandshakeConfig
|
||||
cfg.pq = pqHandshakeConfig{initiate: true, accept: true}
|
||||
hm := NewHandshakeManager(l, newHostMap(l), newTestLighthouse(), conn, cfg)
|
||||
hm.f = &Interface{
|
||||
handshakeManager: hm,
|
||||
outside: conn,
|
||||
messageMetrics: newMessageMetricsOnlyRecvError(),
|
||||
l: l,
|
||||
}
|
||||
return hm, conn
|
||||
}
|
||||
|
||||
// fragmentIndexes checks every packet is a fragment of the expected response and
|
||||
// returns their symbol indexes.
|
||||
func fragmentIndexes(t *testing.T, pkts [][]byte, fragID, remoteIndex uint32) []int {
|
||||
t.Helper()
|
||||
var out []int
|
||||
for _, p := range pkts {
|
||||
require.LessOrEqual(t, len(p), fragment.MaxPacketLen)
|
||||
var h header.H
|
||||
require.NoError(t, h.Parse(p))
|
||||
assert.Equal(t, pqSubtype, h.Subtype)
|
||||
assert.Equal(t, remoteIndex, h.RemoteIndex)
|
||||
assert.Equal(t, uint64(2), h.MessageCounter)
|
||||
fh, _, err := fragment.Parse(p[header.Len:])
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fragID, fh.FragID)
|
||||
out = append(out, int(fh.Index))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSendFragmentedResponse(t *testing.T) {
|
||||
hm, conn := newPQTestManager(t)
|
||||
via := ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.1:4242")}
|
||||
hostinfo := &HostInfo{localIndexId: 77}
|
||||
|
||||
// A 2000 byte message is 2 symbols of 1000, so packets of 1024 bytes.
|
||||
msg := make([]byte, header.Len, header.Len+2000)
|
||||
header.Encode(msg, header.Version, header.Handshake, pqSubtype, 5, 2)
|
||||
r := rand.New(rand.NewPCG(1, 1))
|
||||
for range 2000 {
|
||||
msg = append(msg, byte(r.Uint32()))
|
||||
}
|
||||
const pktLen = header.Len + fragment.HeaderLen + 1000
|
||||
|
||||
t.Run("first send", func(t *testing.T) {
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, false, 0))
|
||||
assert.Equal(t, []int{0, 1, 2, 3}, fragmentIndexes(t, conn.take(), 77, 5))
|
||||
})
|
||||
|
||||
t.Run("resends are rate limited", func(t *testing.T) {
|
||||
require.Error(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, 10*pktLen))
|
||||
assert.Empty(t, conn.take())
|
||||
})
|
||||
|
||||
allowResend := func() {
|
||||
hostinfo.handshakeResendAt.Store(time.Now().Add(-time.Second).UnixNano())
|
||||
}
|
||||
|
||||
t.Run("resend offers fresh symbols", func(t *testing.T) {
|
||||
allowResend()
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, 10*pktLen))
|
||||
assert.Equal(t, []int{4, 5, 6, 7}, fragmentIndexes(t, conn.take(), 77, 5))
|
||||
})
|
||||
|
||||
t.Run("amplification budget trims repair", func(t *testing.T) {
|
||||
allowResend()
|
||||
// 3x of a little over one packet allows 3 packets: both data and 1 repair.
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, pktLen+10))
|
||||
assert.Equal(t, []int{8, 9, 10}, fragmentIndexes(t, conn.take(), 77, 5))
|
||||
})
|
||||
|
||||
t.Run("amplification budget below the data refuses", func(t *testing.T) {
|
||||
allowResend()
|
||||
require.Error(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, pktLen/2))
|
||||
assert.Empty(t, conn.take())
|
||||
})
|
||||
}
|
||||
|
||||
func TestPQAnswered(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
a := newPQAnswered(5 * time.Second)
|
||||
hi := &HostInfo{}
|
||||
|
||||
assert.Nil(t, a.lookup([]byte("msg1"), now))
|
||||
a.add([]byte("msg1"), hi, now)
|
||||
assert.Same(t, hi, a.lookup([]byte("msg1"), now.Add(time.Second)))
|
||||
assert.Nil(t, a.lookup([]byte("other"), now))
|
||||
assert.Nil(t, a.lookup([]byte("msg1"), now.Add(6*time.Second)), "stale entries are not answered")
|
||||
|
||||
a.expire(now.Add(6 * time.Second))
|
||||
assert.Empty(t, a.entries)
|
||||
|
||||
for i := range pqAnsweredMax + 10 {
|
||||
a.add([]byte{byte(i), byte(i >> 8)}, hi, now)
|
||||
}
|
||||
assert.Len(t, a.entries, pqAnsweredMax)
|
||||
}
|
||||
|
||||
func TestPQFragKeyFor(t *testing.T) {
|
||||
k1, s1 := pqFragKeyFor(ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.1:4242")}, 9)
|
||||
k2, s2 := pqFragKeyFor(ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.1:4243")}, 9)
|
||||
assert.NotEqual(t, k1, k2, "different ports are different messages")
|
||||
assert.Equal(t, s1, s2, "but share an IPv4 /32 quota")
|
||||
|
||||
_, s3 := pqFragKeyFor(ViaSender{UdpAddr: netip.MustParseAddrPort("[2001:db8::1]:1")}, 9)
|
||||
_, s4 := pqFragKeyFor(ViaSender{UdpAddr: netip.MustParseAddrPort("[2001:db8::ffff]:1")}, 9)
|
||||
assert.Equal(t, s3, s4, "an IPv6 /64 shares a quota")
|
||||
|
||||
_, s5 := pqFragKeyFor(ViaSender{UdpAddr: netip.MustParseAddrPort("[::ffff:192.0.2.1]:1")}, 9)
|
||||
assert.Equal(t, s1, s5, "v4-mapped addresses count as IPv4")
|
||||
}
|
||||
|
||||
func TestPQCookies(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
c := newPQCookies(now)
|
||||
key := pqFragKey{addr: netip.MustParseAddrPort("192.0.2.1:4242"), fragID: 9}
|
||||
|
||||
cookie := c.make(key, now)
|
||||
assert.True(t, c.valid(key, cookie, now))
|
||||
|
||||
for _, other := range []pqFragKey{
|
||||
{addr: netip.MustParseAddrPort("192.0.2.2:4242"), fragID: 9},
|
||||
{addr: netip.MustParseAddrPort("192.0.2.1:4243"), fragID: 9},
|
||||
{addr: netip.MustParseAddrPort("192.0.2.1:4242"), fragID: 10},
|
||||
{addr: netip.MustParseAddrPort("192.0.2.1:4242"), relay: 1, fragID: 9},
|
||||
} {
|
||||
assert.False(t, c.valid(other, cookie, now), "%+v", other)
|
||||
}
|
||||
|
||||
now = now.Add(pqCookieRotate)
|
||||
assert.True(t, c.valid(key, cookie, now), "the previous secret is still accepted")
|
||||
assert.NotEqual(t, cookie, c.make(key, now), "new cookies come from the new secret")
|
||||
|
||||
now = now.Add(pqCookieRotate)
|
||||
assert.False(t, c.valid(key, cookie, now), "two rotations retire a cookie")
|
||||
}
|
||||
|
||||
// pqMsg1Fragment builds the first fragment of a msg1, optionally with a cookie.
|
||||
func pqMsg1Fragment(t *testing.T, fragID uint32, cookie *fragment.Cookie) ([]byte, *header.H) {
|
||||
t.Helper()
|
||||
s, err := fragment.NewSender(make([]byte, 2000), pqSubtype, 0, 1, fragID)
|
||||
require.NoError(t, err)
|
||||
if cookie != nil {
|
||||
s.SetCookie(*cookie)
|
||||
}
|
||||
pkts, _, err := s.Attempt(0)
|
||||
require.NoError(t, err)
|
||||
var h header.H
|
||||
require.NoError(t, h.Parse(pkts[0]))
|
||||
return pkts[0], &h
|
||||
}
|
||||
|
||||
// fillPQTable puts the responder's msg1 table at the cookie threshold.
|
||||
func fillPQTable(t *testing.T, hm *HandshakeManager) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
for i := 0; hm.pqTable.Load() < pqCookieLoad; i++ {
|
||||
p, _ := pqMsg1Fragment(t, uint32(i+1), nil)
|
||||
fh, sym, err := fragment.Parse(p[header.Len:])
|
||||
require.NoError(t, err)
|
||||
addr := netip.AddrPortFrom(netip.AddrFrom4([4]byte{198, 18, byte(i >> 8), byte(i)}), 4242)
|
||||
key, src := pqFragKeyFor(ViaSender{UdpAddr: addr}, fh.FragID)
|
||||
_, err = hm.pqTable.Add(key, src, now, fh, sym)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPQCookieUnderLoad(t *testing.T) {
|
||||
hm, conn := newPQTestManager(t)
|
||||
via := ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.1:4242")}
|
||||
|
||||
t.Run("no cookie needed below the threshold", func(t *testing.T) {
|
||||
p, h := pqMsg1Fragment(t, 5000, nil)
|
||||
before := hm.pqTable.Len()
|
||||
hm.handleFragment(via, p, h)
|
||||
assert.Empty(t, conn.take())
|
||||
assert.Equal(t, before+1, hm.pqTable.Len())
|
||||
})
|
||||
|
||||
fillPQTable(t, hm)
|
||||
|
||||
var cookie fragment.Cookie
|
||||
t.Run("a fragment without a cookie gets one and leaves no state", func(t *testing.T) {
|
||||
p, h := pqMsg1Fragment(t, 7, nil)
|
||||
before := hm.pqTable.Len()
|
||||
hm.handleFragment(via, p, h)
|
||||
assert.Equal(t, before, hm.pqTable.Len())
|
||||
|
||||
sent := conn.take()
|
||||
require.Len(t, sent, 1)
|
||||
reply := sent[0]
|
||||
require.Len(t, reply, pqCookieReplyLen)
|
||||
var rh header.H
|
||||
require.NoError(t, rh.Parse(reply))
|
||||
assert.Equal(t, header.Handshake, rh.Type)
|
||||
assert.Equal(t, pqSubtype, rh.Subtype)
|
||||
assert.Equal(t, uint32(7), rh.RemoteIndex, "the reply names the initiator's FragID")
|
||||
assert.Equal(t, uint64(pqCookieCounter), rh.MessageCounter)
|
||||
copy(cookie[:], reply[header.Len:])
|
||||
})
|
||||
|
||||
t.Run("a forged cookie gets a fresh one", func(t *testing.T) {
|
||||
bad := cookie
|
||||
bad[0] ^= 1
|
||||
p, h := pqMsg1Fragment(t, 7, &bad)
|
||||
before := hm.pqTable.Len()
|
||||
hm.handleFragment(via, p, h)
|
||||
assert.Equal(t, before, hm.pqTable.Len())
|
||||
assert.Len(t, conn.take(), 1)
|
||||
})
|
||||
|
||||
t.Run("the cookie gets the fragment in", func(t *testing.T) {
|
||||
p, h := pqMsg1Fragment(t, 7, &cookie)
|
||||
before := hm.pqTable.Len()
|
||||
hm.handleFragment(via, p, h)
|
||||
assert.Equal(t, before+1, hm.pqTable.Len())
|
||||
assert.Empty(t, conn.take())
|
||||
})
|
||||
|
||||
t.Run("a cookie is bound to its address", func(t *testing.T) {
|
||||
p, h := pqMsg1Fragment(t, 7, &cookie)
|
||||
hm.handleFragment(ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.99:4242")}, p, h)
|
||||
assert.Len(t, conn.take(), 1, "another address gets its own cookie instead")
|
||||
})
|
||||
|
||||
t.Run("a reply never outgrows what prompted it", func(t *testing.T) {
|
||||
p, h := pqMsg1Fragment(t, 8, nil)
|
||||
hm.sendCookie(via, fragment.Header{FragID: 8}, pqFragKey{}, pqCookieReplyLen-1, time.Now())
|
||||
assert.Empty(t, conn.take())
|
||||
hm.handleFragment(via, p, h)
|
||||
assert.Len(t, conn.take(), 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPQHandleCookie(t *testing.T) {
|
||||
hm, conn := newPQTestManager(t)
|
||||
via := ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.1:4242")}
|
||||
|
||||
s, err := fragment.NewSender(make([]byte, 2000), pqSubtype, 0, 1, 99)
|
||||
require.NoError(t, err)
|
||||
_, _, err = s.Attempt(2)
|
||||
require.NoError(t, err)
|
||||
hh := &HandshakeHostInfo{hostinfo: &HostInfo{}, pq: &pqAttempt{index: 99, sender: s}}
|
||||
hm.indexes[99] = hh
|
||||
|
||||
reply := make([]byte, header.Len, pqCookieReplyLen)
|
||||
header.Encode(reply, header.Version, header.Handshake, pqSubtype, 99, pqCookieCounter)
|
||||
reply = append(reply, bytes16(0xab)...)
|
||||
var h header.H
|
||||
require.NoError(t, h.Parse(reply))
|
||||
|
||||
hm.handleFragment(via, reply, &h)
|
||||
assert.True(t, hh.pq.heard, "a cookie reply shows the peer speaks PQ")
|
||||
sent := conn.take()
|
||||
require.Len(t, sent, 4, "an immediate resend of fresh symbols")
|
||||
for i, p := range sent {
|
||||
fh, _, err := fragment.Parse(p[header.Len:])
|
||||
require.NoError(t, err)
|
||||
assert.True(t, fh.HasCookie())
|
||||
assert.Equal(t, fragment.Cookie(bytes16(0xab)), fh.Cookie)
|
||||
assert.Equal(t, uint8(4+i), fh.Index)
|
||||
}
|
||||
|
||||
hm.handleFragment(via, reply, &h)
|
||||
assert.Empty(t, conn.take(), "immediate resends are rate limited")
|
||||
|
||||
t.Run("replies for other indexes are ignored", func(t *testing.T) {
|
||||
other := append([]byte(nil), reply...)
|
||||
header.Encode(other, header.Version, header.Handshake, pqSubtype, 98, pqCookieCounter)
|
||||
var oh header.H
|
||||
require.NoError(t, oh.Parse(other))
|
||||
hh.pq.cookieResendAt = time.Time{}
|
||||
hm.handleFragment(via, other, &oh)
|
||||
assert.Empty(t, conn.take())
|
||||
})
|
||||
}
|
||||
|
||||
func bytes16(b byte) []byte {
|
||||
out := make([]byte, 16)
|
||||
for i := range out {
|
||||
out[i] = b
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestReloadPQ(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
require.NoError(t, c.LoadString(`handshakes: {pq: {initiate: false}}`))
|
||||
cfg := defaultHandshakeConfig
|
||||
cfg.pq = pqHandshakeConfigFrom(c)
|
||||
hm := NewHandshakeManager(l, newHostMap(l), newTestLighthouse(), &udp.NoopConn{}, cfg)
|
||||
c.RegisterReloadCallback(hm.reloadPQ)
|
||||
|
||||
assert.Equal(t, pqHandshakeConfig{repairDelay: DefaultPQRepairDelay}, *hm.pqConfig())
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(`handshakes: {pq: {initiate: true, accept: true, sticky: true, repair_delay: 25ms}}`))
|
||||
assert.Equal(t, pqHandshakeConfig{initiate: true, accept: true, sticky: true, repairDelay: 25 * time.Millisecond}, *hm.pqConfig())
|
||||
|
||||
before := hm.pqConfig()
|
||||
require.NoError(t, c.ReloadConfigString(`handshakes: {try_interval: 1s, pq: {initiate: true, accept: true, sticky: true, repair_delay: 25ms}}`))
|
||||
assert.Same(t, before, hm.pqConfig(), "an unrelated change leaves the settings alone")
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(`handshakes: {}`))
|
||||
assert.Equal(t, pqHandshakeConfig{repairDelay: DefaultPQRepairDelay}, *hm.pqConfig(), "removing the section restores the defaults")
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(`handshakes: {pq: {require: true}}`))
|
||||
assert.Equal(t, pqHandshakeConfig{initiate: true, accept: true, require: true, repairDelay: DefaultPQRepairDelay}, *hm.pqConfig(), "require implies initiate and accept")
|
||||
}
|
||||
|
||||
func TestUsePQ(t *testing.T) {
|
||||
hm, _ := newPQTestManager(t)
|
||||
peer := netip.MustParseAddr("10.1.0.1")
|
||||
set := func(cfg pqHandshakeConfig) { hm.pq.Store(&cfg) }
|
||||
|
||||
// attempts plays a run of attempts, given whether each was triggered early,
|
||||
// and returns which were PQ.
|
||||
attempts := func(triggered ...bool) []bool {
|
||||
hh := &HandshakeHostInfo{}
|
||||
var out []bool
|
||||
for _, tr := range triggered {
|
||||
hh.counter++
|
||||
hh.lastPQ = hm.usePQ(hh, peer, tr)
|
||||
out = append(out, hh.lastPQ)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
set(pqHandshakeConfig{})
|
||||
assert.Equal(t, []bool{false, false, false}, attempts(false, false, false), "off")
|
||||
|
||||
set(pqHandshakeConfig{initiate: true})
|
||||
assert.Equal(t, []bool{true, false, true, false}, attempts(false, false, false, false), "timer retries alternate, PQ first")
|
||||
assert.Equal(t, []bool{true, true, false, true, false}, attempts(false, true, false, true, false), "an early trigger is a new path, which gets PQ first")
|
||||
assert.Equal(t, []bool{true, true, false}, attempts(true, true, false), "a triggered first attempt is PQ")
|
||||
|
||||
t.Run("hearing back stops the classical turns", func(t *testing.T) {
|
||||
hh := &HandshakeHostInfo{pq: &pqAttempt{}}
|
||||
hh.counter, hh.lastPQ = 1, true
|
||||
hh.counter++
|
||||
assert.False(t, hm.usePQ(hh, peer, false), "unheard, the classical attempt gets its turn")
|
||||
hh.pq.heard = true
|
||||
assert.True(t, hm.usePQ(hh, peer, false))
|
||||
})
|
||||
|
||||
set(pqHandshakeConfig{initiate: true, accept: true, require: true})
|
||||
assert.Equal(t, []bool{true, true, true, true}, attempts(false, false, true, false), "require never offers classical")
|
||||
|
||||
set(pqHandshakeConfig{initiate: true, sticky: true})
|
||||
assert.Equal(t, []bool{true, false}, attempts(false, false), "sticky alternates until the peer has done PQ")
|
||||
hm.notePQPeer(pqSubtype, []netip.Addr{peer})
|
||||
assert.Equal(t, []bool{true, true, true}, attempts(false, false, false), "then only PQ")
|
||||
}
|
||||
@@ -1,17 +1,12 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/gaissmai/bart"
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
@@ -240,89 +235,6 @@ func TestHandleIncomingDispatch(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestBlocklistedHandshakeLogLevelAndCounter(t *testing.T) {
|
||||
ca, _, caKey, _ := ct.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
pool := ct.NewTestCAPool(ca)
|
||||
|
||||
newCredential := func(name, network string) (cert.Certificate, *handshake.Credential) {
|
||||
c, _, rawKey, _ := ct.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey,
|
||||
name, ca.NotBefore(), ca.NotAfter(), []netip.Prefix{netip.MustParsePrefix(network)}, nil, nil)
|
||||
privateKey, _, _, err := cert.UnmarshalPrivateKeyFromPEM(rawKey)
|
||||
require.NoError(t, err)
|
||||
certBytes, err := c.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
cipherSuite := noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashSHA256)
|
||||
return c, handshake.NewCredential(c, certBytes, privateKey, cipherSuite)
|
||||
}
|
||||
|
||||
initiatorCert, initiatorCredential := newCredential("initiator", "10.0.0.1/24")
|
||||
responderCert, responderCredential := newCredential("responder", "10.0.0.2/24")
|
||||
fingerprint, err := initiatorCert.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
pool.BlocklistFingerprint(fingerprint)
|
||||
|
||||
initiator, err := handshake.NewMachine(cert.Version2,
|
||||
func(cert.Version) *handshake.Credential { return initiatorCredential },
|
||||
func(c cert.Certificate) (*cert.CachedCertificate, error) {
|
||||
return pool.VerifyCertificate(time.Now(), c)
|
||||
},
|
||||
func() (uint32, error) { return 1, nil }, true, header.HandshakeIXPSK0)
|
||||
require.NoError(t, err)
|
||||
packet, err := initiator.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
handler := &capturingHandler{}
|
||||
logger := slog.New(handler)
|
||||
pki := &PKI{}
|
||||
pki.cs.Store(&CertState{initiatingVersion: cert.Version2, v2Credential: responderCredential})
|
||||
pki.caPool.Store(pool)
|
||||
hm := NewHandshakeManager(logger, nil, nil, nil, defaultHandshakeConfig)
|
||||
hm.metricRejectedBlocklisted = metrics.NewCounter()
|
||||
hm.f = &Interface{pki: pki, l: logger}
|
||||
via := ViaSender{UdpAddr: netip.MustParseAddrPort("198.51.100.7:4242")}
|
||||
|
||||
hm.beginHandshake(via, packet, nil)
|
||||
entry := findEntry(t, handler.entries, "Failed to process handshake packet")
|
||||
assert.Equal(t, slog.LevelDebug, entry.Level)
|
||||
require.ErrorIs(t, entry.Attrs["error"].(error), cert.ErrBlockListed)
|
||||
assert.Equal(t, int64(1), hm.metricRejectedBlocklisted.Count())
|
||||
|
||||
handler.entries = nil
|
||||
hm.beginHandshake(via, nil, nil)
|
||||
entry = findEntry(t, handler.entries, "Failed to process handshake packet")
|
||||
assert.Equal(t, slog.LevelError, entry.Level)
|
||||
assert.Equal(t, int64(1), hm.metricRejectedBlocklisted.Count())
|
||||
|
||||
// The initiator sees the same rejection in continueHandshake, after a
|
||||
// responder has accepted its first packet and sent a valid reply.
|
||||
cleanPool := ct.NewTestCAPool(ca)
|
||||
responder, err := handshake.NewMachine(cert.Version2,
|
||||
func(cert.Version) *handshake.Credential { return responderCredential },
|
||||
func(c cert.Certificate) (*cert.CachedCertificate, error) {
|
||||
return cleanPool.VerifyCertificate(time.Now(), c)
|
||||
},
|
||||
func() (uint32, error) { return 2, nil }, false, header.HandshakeIXPSK0)
|
||||
require.NoError(t, err)
|
||||
response, _, err := responder.ProcessPacket(nil, packet)
|
||||
require.NoError(t, err)
|
||||
|
||||
responderFingerprint, err := responderCert.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
pool.BlocklistFingerprint(responderFingerprint)
|
||||
|
||||
initiatingHM := NewHandshakeManager(logger, nil, nil, nil, defaultHandshakeConfig)
|
||||
initiatingHM.metricRejectedBlocklisted = metrics.NewCounter()
|
||||
initiatingHM.f = &Interface{l: logger}
|
||||
hh := &HandshakeHostInfo{
|
||||
machine: initiator,
|
||||
hostinfo: &HostInfo{localIndexId: 1, vpnAddrs: []netip.Addr{netip.MustParseAddr("10.0.0.2")}},
|
||||
}
|
||||
initiatingHM.indexes[1] = hh
|
||||
via.IsRelayed = true // skip the remote allow list before certificate validation
|
||||
initiatingHM.continueHandshake(via, hh, response)
|
||||
assert.Equal(t, int64(1), initiatingHM.metricRejectedBlocklisted.Count())
|
||||
}
|
||||
|
||||
// Test_PendingHandshakeHasRemotes covers create-tunnel -address: a pending hostinfo must already
|
||||
// carry its RemoteList when StartHandshake runs its callback, so SetRemote there, before the
|
||||
// handshake loop has run, is safe and the address becomes one the handshake is sent to.
|
||||
|
||||
+14
-2
@@ -67,8 +67,19 @@ const (
|
||||
const (
|
||||
HandshakeIXPSK0 MessageSubType = 0
|
||||
HandshakeXXPSK0 MessageSubType = 1
|
||||
|
||||
// HandshakeIXPSK2MLKEM1024 is IX with an ephemeral ML-KEM-1024 exchange mixed
|
||||
// in through the psk2 slot. Its messages exceed the MTU and travel as
|
||||
// fragments (see handshake/fragment).
|
||||
HandshakeIXPSK2MLKEM1024 MessageSubType = 2
|
||||
)
|
||||
|
||||
// IsFragmented reports whether handshake messages of this subtype travel as
|
||||
// fragments.
|
||||
func IsFragmented(st MessageSubType) bool {
|
||||
return st == HandshakeIXPSK2MLKEM1024
|
||||
}
|
||||
|
||||
var ErrHeaderTooShort = errors.New("header is too short")
|
||||
|
||||
var subTypeTestMap = map[MessageSubType]string{
|
||||
@@ -88,7 +99,8 @@ var subTypeMap = map[MessageType]*map[MessageSubType]string{
|
||||
Test: &subTypeTestMap,
|
||||
CloseTunnel: &subTypeNoneMap,
|
||||
Handshake: {
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXPSK2MLKEM1024: "ix_psk2_mlkem1024",
|
||||
},
|
||||
Control: &subTypeNoneMap,
|
||||
}
|
||||
@@ -199,7 +211,7 @@ func IsValidSubType(t MessageType, s MessageSubType) bool {
|
||||
case Message:
|
||||
return s == MessageNone || s == MessageRelay
|
||||
case Handshake:
|
||||
return s == HandshakeIXPSK0
|
||||
return s == HandshakeIXPSK0 || s == HandshakeIXPSK2MLKEM1024
|
||||
case Test:
|
||||
return s == TestReply || s == TestRequest
|
||||
case Control, CloseTunnel, RecvError, LightHouse:
|
||||
|
||||
@@ -96,7 +96,8 @@ func TestTypeMap(t *testing.T) {
|
||||
Test: &subTypeTestMap,
|
||||
CloseTunnel: &subTypeNoneMap,
|
||||
Handshake: {
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXPSK2MLKEM1024: "ix_psk2_mlkem1024",
|
||||
},
|
||||
Control: &subTypeNoneMap,
|
||||
}, subTypeMap)
|
||||
@@ -122,6 +123,7 @@ func TestIsValidSubType(t *testing.T) {
|
||||
assert.False(t, IsValidSubType(Message, 2))
|
||||
|
||||
assert.True(t, IsValidSubType(Handshake, HandshakeIXPSK0))
|
||||
assert.True(t, IsValidSubType(Handshake, HandshakeIXPSK2MLKEM1024))
|
||||
// HandshakeXXPSK0 is defined but not a wire-valid subtype.
|
||||
assert.False(t, IsValidSubType(Handshake, HandshakeXXPSK0))
|
||||
|
||||
|
||||
+10
-7
@@ -260,6 +260,11 @@ type HostInfo struct {
|
||||
// We need these to avoid replayed handshake packets creating new hostinfos which causes churn
|
||||
HandshakePacket map[uint8][]byte
|
||||
|
||||
// A responder resending a fragmented handshake response offers symbols it has
|
||||
// not sent before, at most once per retry interval.
|
||||
handshakeResendAt atomic.Int64 // unix nanos of the last send
|
||||
handshakeNextSymbol atomic.Uint32 // next fragment symbol index to offer
|
||||
|
||||
// nextLHQuery is the earliest we can ask the lighthouse for new information.
|
||||
// This is used to limit lighthouse re-queries in chatty clients
|
||||
nextLHQuery atomic.Int64
|
||||
@@ -316,9 +321,9 @@ type cachedPacketMetrics struct {
|
||||
func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
|
||||
hm := newHostMap(l)
|
||||
|
||||
hm.reload(c, true, nil)
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
hm.reload(c, false, r)
|
||||
hm.reload(c, true)
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
hm.reload(c, false)
|
||||
})
|
||||
|
||||
l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
|
||||
@@ -337,8 +342,7 @@ func newHostMap(l *slog.Logger) *HostMap {
|
||||
}
|
||||
}
|
||||
|
||||
// r is nil on the initial load
|
||||
func (hm *HostMap) reload(c *config.C, initial bool, r *config.Reload) {
|
||||
func (hm *HostMap) reload(c *config.C, initial bool) {
|
||||
if initial || c.HasChanged("preferred_ranges") {
|
||||
var preferredRanges []netip.Prefix
|
||||
rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
|
||||
@@ -349,9 +353,8 @@ func (hm *HostMap) reload(c *config.C, initial bool, r *config.Reload) {
|
||||
if err != nil {
|
||||
hm.l.Warn("Failed to parse preferred ranges, ignoring",
|
||||
"error", err,
|
||||
"range", rawPreferredRange,
|
||||
"range", rawPreferredRanges,
|
||||
)
|
||||
r.Failed()
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -447,16 +447,3 @@ func TestHostInfo_markOutOnly(t *testing.T) {
|
||||
assert.True(t, h.markOut(6), "a relayed send must not consume the epoch edge")
|
||||
assert.False(t, h.markOut(6))
|
||||
}
|
||||
|
||||
// A preferred range that doesn't parse is skipped and the rest are used, the reload says one was skipped
|
||||
func TestHostMap_reloadBadPreferredRangeFails(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
require.NoError(t, c.LoadString("preferred_ranges: [10.0.0.0/8]\n"))
|
||||
hm := NewHostMapFromConfig(l, c)
|
||||
|
||||
res := c.ReloadConfigString("preferred_ranges: [10.0.0.0/8, nope]\n")
|
||||
require.NoError(t, res.Err)
|
||||
assert.True(t, res.Failed)
|
||||
assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}, hm.GetPreferredRanges())
|
||||
}
|
||||
-235
@@ -1,235 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
)
|
||||
|
||||
type identityFlags struct {
|
||||
Address string
|
||||
|
||||
// addressSet records that -address was given at all, so a line that left it out is
|
||||
// told to pass it and one that passed it empty is told the value did not parse. Neither
|
||||
// is answered with this node's identity, which is whoami's to report: a program
|
||||
// passing a connection's remote address through must get an error for a value it
|
||||
// failed to fill in, not the daemon's own identity to authorize against.
|
||||
addressSet bool
|
||||
}
|
||||
|
||||
// setAddress is -address's setter. flag.Func rather than StringVar so that presence is
|
||||
// known; its String is empty, which is what a client building a line from the schema
|
||||
// sees as the default.
|
||||
func (f *identityFlags) setAddress(v string) error {
|
||||
f.Address = v
|
||||
f.addressSet = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// hostIdentity is what identity reports: the identity a certificate asserts for a host,
|
||||
// and nothing else. Every field is read from a certificate nebula verified when the
|
||||
// tunnel came up, or from our own, which is what lets a program on this host make an
|
||||
// authorization decision from it, within one limit. Nebula drops an inbound packet
|
||||
// whose source address is not in the sender's certificate, and one with an overlay
|
||||
// source address that arrived through a peer's unsafe network rather than from the node
|
||||
// holding it, so for a connection that arrived on the nebula interface the source
|
||||
// address is the sender's and this is the sender's identity. A connection that arrived
|
||||
// on any other interface with an overlay source address was never checked by nebula at
|
||||
// all, so a program authorizing on this answer should confirm the connection came in
|
||||
// on the nebula interface. The field names are an API: the info API serves this shape
|
||||
// to programs that were not built against nebula.
|
||||
type hostIdentity struct {
|
||||
Name string `json:"name"`
|
||||
VpnAddrs []netip.Addr `json:"vpnAddrs"`
|
||||
Networks []netip.Prefix `json:"networks"`
|
||||
UnsafeNetworks []netip.Prefix `json:"unsafeNetworks"`
|
||||
Groups []string `json:"groups"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Issuer string `json:"issuer"`
|
||||
NotBefore time.Time `json:"notBefore"`
|
||||
NotAfter time.Time `json:"notAfter"`
|
||||
CertVersion int `json:"certVersion"`
|
||||
}
|
||||
|
||||
// runIdentity answers for whoever owns the address: this node, when it is one of ours, or
|
||||
// the peer behind an established tunnel. The address is required. This node's own
|
||||
// identity is whoami's to report, so a caller that failed to pass an address is told so
|
||||
// rather than handed an identity it could mistake for its peer's.
|
||||
func runIdentity(ifce *Interface, args *identityFlags, a []string) (commands.Result, error) {
|
||||
// print-cert takes its address as an operand; this takes a flag, because the query
|
||||
// string of the info API names its parameters and an operand has no name there. One
|
||||
// spelling on every surface, so the mistake is named rather than ignored.
|
||||
if len(a) > 0 {
|
||||
return commands.Failed("identity takes the vpn addr as -address, not as an operand: identity -address %s", a[0]), nil
|
||||
}
|
||||
|
||||
if !args.addressSet {
|
||||
return commands.Failed("No vpn addr was provided, use -address <vpn addr>[:port]; whoami prints this node's own identity"), nil
|
||||
}
|
||||
|
||||
vpnAddr, err := parseVpnAddrWithOptionalPort(args.Address)
|
||||
if err != nil {
|
||||
return commands.Failed("The provided vpn addr could not be parsed: %s", args.Address), nil
|
||||
}
|
||||
|
||||
crt, fingerprint := findCertificateForVpnAddr(ifce.pki.getCertState(), ifce.hostMap, vpnAddr)
|
||||
if crt == nil {
|
||||
return commands.NotFound("No active tunnel for vpn addr: %s", vpnAddr), nil
|
||||
}
|
||||
|
||||
id, err := newHostIdentity(crt, fingerprint)
|
||||
if err != nil {
|
||||
return commands.Result{}, err
|
||||
}
|
||||
|
||||
return commands.Value(id), nil
|
||||
}
|
||||
|
||||
// runWhoami answers with this node's own identity, from its own certificate.
|
||||
func runWhoami(ifce *Interface) (commands.Result, error) {
|
||||
crt := ownCertificate(ifce.pki.getCertState())
|
||||
if crt == nil {
|
||||
return commands.Failed("No certificate is loaded"), nil
|
||||
}
|
||||
|
||||
id, err := newHostIdentity(crt, "")
|
||||
if err != nil {
|
||||
return commands.Result{}, err
|
||||
}
|
||||
|
||||
return commands.Value(id), nil
|
||||
}
|
||||
|
||||
// textIdentity is the human rendering, shared by every surface.
|
||||
func textIdentity(id hostIdentity, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w,
|
||||
"name: %s\nvpn addrs: %s\nnetworks: %s\nunsafe networks: %s\ngroups: %s\nfingerprint: %s\nissuer: %s\nnot before: %s\nnot after: %s\ncert version: %d\n",
|
||||
id.Name,
|
||||
joinStringers(id.VpnAddrs),
|
||||
joinStringers(id.Networks),
|
||||
joinStringers(id.UnsafeNetworks),
|
||||
strings.Join(id.Groups, ", "),
|
||||
id.Fingerprint,
|
||||
id.Issuer,
|
||||
id.NotBefore.Format(time.RFC3339),
|
||||
id.NotAfter.Format(time.RFC3339),
|
||||
id.CertVersion,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func joinStringers[T fmt.Stringer](in []T) string {
|
||||
parts := make([]string, 0, len(in))
|
||||
for _, v := range in {
|
||||
parts = append(parts, v.String())
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
// newHostIdentity reads the identity out of a certificate. fingerprint is the
|
||||
// certificate's when the caller already holds it, as a verified peer certificate does,
|
||||
// and "" to have it hashed here. Slices are always allocated so a host with no groups
|
||||
// reports [] rather than null.
|
||||
func newHostIdentity(crt cert.Certificate, fingerprint string) (hostIdentity, error) {
|
||||
if fingerprint == "" {
|
||||
fp, err := crt.Fingerprint()
|
||||
if err != nil {
|
||||
return hostIdentity{}, err
|
||||
}
|
||||
fingerprint = fp
|
||||
}
|
||||
|
||||
networks, unsafeNetworks, groups := crt.Networks(), crt.UnsafeNetworks(), crt.Groups()
|
||||
id := hostIdentity{
|
||||
Name: crt.Name(),
|
||||
VpnAddrs: make([]netip.Addr, 0, len(networks)),
|
||||
Networks: append(make([]netip.Prefix, 0, len(networks)), networks...),
|
||||
UnsafeNetworks: append(make([]netip.Prefix, 0, len(unsafeNetworks)), unsafeNetworks...),
|
||||
Groups: append(make([]string, 0, len(groups)), groups...),
|
||||
Fingerprint: fingerprint,
|
||||
Issuer: crt.Issuer(),
|
||||
NotBefore: crt.NotBefore(),
|
||||
NotAfter: crt.NotAfter(),
|
||||
CertVersion: int(crt.Version()),
|
||||
}
|
||||
for _, n := range networks {
|
||||
id.VpnAddrs = append(id.VpnAddrs, n.Addr())
|
||||
}
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// ownCertificate is this node's certificate: the v2 one when it is loaded, else the v1.
|
||||
// A v2 certificate is a superset of the v1 and may carry more networks, and it is the
|
||||
// one newCertState builds myVpnAddrsTable from, so an address that matched that table is
|
||||
// always listed in the certificate reported here. It is nil only when no certificate is
|
||||
// loaded, which a running nebula never has.
|
||||
func ownCertificate(cs *CertState) cert.Certificate {
|
||||
if cs == nil {
|
||||
return nil
|
||||
}
|
||||
if crt := cs.getCertificate(cert.Version2); crt != nil {
|
||||
return crt
|
||||
}
|
||||
return cs.getCertificate(cert.Version1)
|
||||
}
|
||||
|
||||
// findCertificateForVpnAddr answers who owns a vpn address: this node, from its own
|
||||
// certificate state, since the hostmap never carries an entry for ourselves, or the peer
|
||||
// behind an established tunnel. The certificate is nil when the address is unknown,
|
||||
// when the tunnel is still pending and when it is mid teardown. A peer's comes with the
|
||||
// fingerprint nebula computed when it verified the certificate; our own comes with "",
|
||||
// since none is kept for it. identity and print-cert go through it, and the lighthouse's
|
||||
// DNS TXT lookup through the two halves, so no surface disagrees about whose address it
|
||||
// is; the TXT record alone keeps answering with the certificate handshakes start with.
|
||||
func findCertificateForVpnAddr(cs *CertState, hostMap *HostMap, ip netip.Addr) (crt cert.Certificate, fingerprint string) {
|
||||
if ownsVpnAddr(cs, ip) {
|
||||
return ownCertificate(cs), ""
|
||||
}
|
||||
return peerCertificateForVpnAddr(hostMap, ip)
|
||||
}
|
||||
|
||||
// ownsVpnAddr reports whether ip is one of this node's own vpn addresses.
|
||||
func ownsVpnAddr(cs *CertState, ip netip.Addr) bool {
|
||||
return cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip)
|
||||
}
|
||||
|
||||
// peerCertificateForVpnAddr is the certificate of the peer behind an established tunnel
|
||||
// to ip, with the fingerprint nebula computed when it verified it, or nil when there is
|
||||
// no such tunnel. See findCertificateForVpnAddr.
|
||||
func peerCertificateForVpnAddr(hostMap *HostMap, ip netip.Addr) (crt cert.Certificate, fingerprint string) {
|
||||
hostinfo := hostMap.QueryVpnAddr(ip)
|
||||
if hostinfo == nil {
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
cc := hostinfo.GetCert()
|
||||
if cc == nil {
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
return cc.Certificate, cc.Fingerprint
|
||||
}
|
||||
|
||||
// parseVpnAddrWithOptionalPort reads a vpn address alone or with a port,
|
||||
// 192.168.100.7:54321 or [fd00::1]:443, so a program can pass a connection's remote
|
||||
// address through as its runtime reported it. A 4in6 address (::ffff:a.b.c.d) is
|
||||
// unmapped, which is how an IPv4 peer arrives on a dual stack listener, and a zone is
|
||||
// dropped, since no vpn address carries one.
|
||||
func parseVpnAddrWithOptionalPort(s string) (netip.Addr, error) {
|
||||
ip, err := netip.ParseAddr(s)
|
||||
if err != nil {
|
||||
ap, err := netip.ParseAddrPort(s)
|
||||
if err != nil {
|
||||
return netip.Addr{}, err
|
||||
}
|
||||
ip = ap.Addr()
|
||||
}
|
||||
|
||||
return ip.Unmap().WithZone(""), nil
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// identityFixture is an Interface with our own certificate loaded and one peer behind an
|
||||
// established tunnel, which is all identity reads.
|
||||
func identityFixture(t *testing.T) (*Interface, cert.Certificate) {
|
||||
t.Helper()
|
||||
|
||||
l := test.NewLogger()
|
||||
me := netip.MustParseAddr("10.0.0.1")
|
||||
peer := netip.MustParsePrefix("10.0.0.2/24")
|
||||
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
peerCert, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "peer", time.Time{}, time.Time{},
|
||||
[]netip.Prefix{peer}, []netip.Prefix{netip.MustParsePrefix("192.168.1.0/24")}, []string{"web", "db"})
|
||||
|
||||
hm := newHostMap(l)
|
||||
hm.Hosts[peer.Addr()] = &HostInfo{
|
||||
vpnAddrs: []netip.Addr{peer.Addr()},
|
||||
ConnectionState: &ConnectionState{peerCert: &cert.CachedCertificate{Certificate: peerCert}},
|
||||
}
|
||||
// A tunnel still handshaking has no certificate yet, and must not be reported.
|
||||
hm.Hosts[netip.MustParseAddr("10.0.0.3")] = &HostInfo{
|
||||
vpnAddrs: []netip.Addr{netip.MustParseAddr("10.0.0.3")},
|
||||
ConnectionState: &ConnectionState{},
|
||||
}
|
||||
|
||||
return &Interface{pki: newTestPKI(t, "me", []netip.Addr{me}), hostMap: hm}, peerCert
|
||||
}
|
||||
|
||||
// identity runs the command with -address given as address.
|
||||
func identity(t *testing.T, f *Interface, address string, operands ...string) commands.Result {
|
||||
t.Helper()
|
||||
fs := &identityFlags{}
|
||||
require.NoError(t, fs.setAddress(address))
|
||||
r, err := runIdentity(f, fs, operands)
|
||||
require.NoError(t, err)
|
||||
return r
|
||||
}
|
||||
|
||||
// whoami runs the whoami command.
|
||||
func whoami(t *testing.T, f *Interface) commands.Result {
|
||||
t.Helper()
|
||||
r, err := runWhoami(f)
|
||||
require.NoError(t, err)
|
||||
return r
|
||||
}
|
||||
|
||||
// TestWhoamiWithoutACertificateRefuses: no certificate is a refusal with the reason, as
|
||||
// print-cert answers it, not an error a surface collapses to "command failed".
|
||||
func TestWhoamiWithoutACertificateRefuses(t *testing.T) {
|
||||
r := whoami(t, &Interface{pki: &PKI{}})
|
||||
assert.False(t, r.OK)
|
||||
assert.Equal(t, "No certificate is loaded", r.Reason)
|
||||
}
|
||||
|
||||
func TestWhoamiReportsThisNode(t *testing.T) {
|
||||
f, _ := identityFixture(t)
|
||||
|
||||
r := whoami(t, f)
|
||||
require.True(t, r.OK)
|
||||
id, ok := r.Value.(hostIdentity)
|
||||
require.True(t, ok, "got %T", r.Value)
|
||||
assert.Equal(t, "me", id.Name)
|
||||
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, id.VpnAddrs)
|
||||
assert.Equal(t, 2, id.CertVersion)
|
||||
assert.NotEmpty(t, id.Fingerprint)
|
||||
assert.NotEmpty(t, id.Issuer)
|
||||
|
||||
// Our own address answers the same way: the hostmap never holds ourselves.
|
||||
self := identity(t, f, "10.0.0.1")
|
||||
assert.Equal(t, id, self.Value)
|
||||
}
|
||||
|
||||
func TestIdentityReportsAPeerFromItsCertificate(t *testing.T) {
|
||||
f, peerCert := identityFixture(t)
|
||||
|
||||
for _, addr := range []string{
|
||||
"10.0.0.2",
|
||||
"10.0.0.2:54321", // a connection's RemoteAddr, as a server has it
|
||||
"::ffff:10.0.0.2", // the same peer seen through a dual stack listener
|
||||
"[::ffff:10.0.0.2]:8", // and with a port
|
||||
} {
|
||||
r := identity(t, f, addr)
|
||||
require.True(t, r.OK, "%s: %s", addr, r.Reason)
|
||||
id := r.Value.(hostIdentity)
|
||||
assert.Equal(t, "peer", id.Name, addr)
|
||||
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.0.0.2")}, id.VpnAddrs, addr)
|
||||
assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.2/24")}, id.Networks, addr)
|
||||
assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("192.168.1.0/24")}, id.UnsafeNetworks, addr)
|
||||
assert.Equal(t, []string{"web", "db"}, id.Groups, addr)
|
||||
assert.Equal(t, peerCert.Issuer(), id.Issuer, addr)
|
||||
assert.Equal(t, peerCert.NotAfter(), id.NotAfter, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentityRefusals: the ways a lookup fails are told apart, because a program
|
||||
// deciding whether to let a connection in treats them differently.
|
||||
func TestIdentityRefusals(t *testing.T) {
|
||||
f, _ := identityFixture(t)
|
||||
|
||||
unknown := identity(t, f, "10.0.0.9")
|
||||
assert.False(t, unknown.OK)
|
||||
assert.True(t, unknown.NotFound, "no tunnel is a not found")
|
||||
assert.Equal(t, "No active tunnel for vpn addr: 10.0.0.9", unknown.Reason)
|
||||
|
||||
pending := identity(t, f, "10.0.0.3:1")
|
||||
assert.True(t, pending.NotFound, "a tunnel without a certificate yet is not active")
|
||||
assert.Equal(t, "No active tunnel for vpn addr: 10.0.0.3", pending.Reason, "the reason names the address, not the port")
|
||||
|
||||
garbage := identity(t, f, "not-an-address")
|
||||
assert.False(t, garbage.OK)
|
||||
assert.False(t, garbage.NotFound, "an address that does not parse is the caller's mistake")
|
||||
assert.Equal(t, "The provided vpn addr could not be parsed: not-an-address", garbage.Reason)
|
||||
|
||||
// An address that was given and is empty is a caller that failed to fill it in, and
|
||||
// must not be answered with our own identity.
|
||||
empty := identity(t, f, "")
|
||||
assert.False(t, empty.OK)
|
||||
assert.False(t, empty.NotFound)
|
||||
assert.Equal(t, "The provided vpn addr could not be parsed: ", empty.Reason)
|
||||
|
||||
operand := identity(t, f, "", "10.0.0.2")
|
||||
assert.False(t, operand.OK)
|
||||
assert.Contains(t, operand.Reason, "identity -address 10.0.0.2")
|
||||
|
||||
// No address at all is a caller that forgot the parameter, and is pointed at whoami
|
||||
// rather than handed this node's identity.
|
||||
omitted, err := runIdentity(f, &identityFlags{}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, omitted.OK)
|
||||
assert.False(t, omitted.NotFound)
|
||||
assert.Contains(t, omitted.Reason, "-address")
|
||||
assert.Contains(t, omitted.Reason, "whoami")
|
||||
}
|
||||
|
||||
// TestOwnCertificatePrefersV2: with both versions loaded, the v2 certificate is the one
|
||||
// myVpnAddrsTable is built from and may carry addresses the v1 does not, so it is the one
|
||||
// whoami and an identity lookup of our own address report, whichever version handshakes
|
||||
// are initiated with.
|
||||
func TestOwnCertificatePrefersV2(t *testing.T) {
|
||||
v4 := netip.MustParsePrefix("10.0.0.1/24")
|
||||
ca1, _, caKey1, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
v1, _, _, _ := cert_test.NewTestCert(cert.Version1, cert.Curve_CURVE25519, ca1, caKey1, "me", time.Time{}, time.Time{}, []netip.Prefix{v4}, nil, nil)
|
||||
ca2, _, caKey2, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
v2, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca2, caKey2, "me", time.Time{}, time.Time{},
|
||||
[]netip.Prefix{v4, netip.MustParsePrefix("fd00::1/64")}, nil, nil)
|
||||
|
||||
assert.Nil(t, ownCertificate(nil))
|
||||
assert.Equal(t, v1, ownCertificate(&CertState{v1Cert: v1, initiatingVersion: cert.Version1}))
|
||||
assert.Equal(t, v2, ownCertificate(&CertState{v2Cert: v2, initiatingVersion: cert.Version2}))
|
||||
assert.Equal(t, v2, ownCertificate(&CertState{v1Cert: v1, v2Cert: v2, initiatingVersion: cert.Version1}),
|
||||
"the initiating version is v1, the reported certificate is still the v2")
|
||||
}
|
||||
|
||||
// TestIdentityShapes pins the JSON a program reads and the text a person reads. The
|
||||
// field names are an API served to programs not built against nebula.
|
||||
func TestIdentityShapes(t *testing.T) {
|
||||
f, _ := identityFixture(t)
|
||||
r := identity(t, f, "10.0.0.2")
|
||||
|
||||
b, err := json.Marshal(r.Payload())
|
||||
require.NoError(t, err)
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(b, &got))
|
||||
var keys []string
|
||||
for k := range got {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
assert.ElementsMatch(t, []string{
|
||||
"name", "vpnAddrs", "networks", "unsafeNetworks", "groups",
|
||||
"fingerprint", "issuer", "notBefore", "notAfter", "certVersion",
|
||||
}, keys)
|
||||
|
||||
// Empty lists marshal as [], never null.
|
||||
self := whoami(t, f)
|
||||
b, err = json.Marshal(self.Payload())
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(b), `"groups":[]`)
|
||||
assert.Contains(t, string(b), `"unsafeNetworks":[]`)
|
||||
|
||||
out := &bytes.Buffer{}
|
||||
require.NoError(t, commands.Render(&commands.Command{Name: commands.Identity, Text: commands.Typed(textIdentity)}, r, commands.FormatText, out))
|
||||
assert.Contains(t, out.String(), "name: peer\n")
|
||||
assert.Contains(t, out.String(), "vpn addrs: 10.0.0.2\n")
|
||||
assert.Contains(t, out.String(), "groups: web, db\n")
|
||||
assert.Contains(t, out.String(), "cert version: 2\n")
|
||||
}
|
||||
|
||||
func TestParseVpnAddrWithOptionalPort(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"10.0.0.2": "10.0.0.2",
|
||||
"10.0.0.2:443": "10.0.0.2",
|
||||
"fd00::1": "fd00::1",
|
||||
"[fd00::1]:443": "fd00::1",
|
||||
"::ffff:10.0.0.2": "10.0.0.2",
|
||||
"[::ffff:10.0.0.2]:1": "10.0.0.2",
|
||||
"fe80::1%eth0": "fe80::1",
|
||||
} {
|
||||
got, err := parseVpnAddrWithOptionalPort(in)
|
||||
require.NoError(t, err, in)
|
||||
assert.Equal(t, netip.MustParseAddr(want), got, in)
|
||||
}
|
||||
|
||||
for _, in := range []string{"", "10.0.0.2:", ":443", "10.0.0", "example.com:80"} {
|
||||
_, err := parseVpnAddrWithOptionalPort(in)
|
||||
assert.Error(t, err, in)
|
||||
}
|
||||
}
|
||||
+19
-71
@@ -124,8 +124,6 @@ type Interface struct {
|
||||
// reused (every udp.Conn ListenOut guarantees that ordering).
|
||||
batchers []*batch.MultiCoalescer
|
||||
wg sync.WaitGroup
|
||||
// readers covers just the listenIn and listenOut goroutines, wg also holds the construction token Close releases
|
||||
readers sync.WaitGroup
|
||||
|
||||
udpTxErrLimiter *ratelimit.Limiter // udp direct transmit error log limiter
|
||||
udpRelayTxErrLimiter *ratelimit.Limiter // udp relay transmit error log limiter
|
||||
@@ -343,18 +341,14 @@ func (f *Interface) activate() error {
|
||||
func (f *Interface) run() {
|
||||
// Launch n queues to read packets from udp
|
||||
for i := 0; i < f.routines; i++ {
|
||||
f.readers.Add(1)
|
||||
f.wg.Go(func() {
|
||||
defer f.readers.Done()
|
||||
f.listenOut(i)
|
||||
})
|
||||
}
|
||||
|
||||
// Launch n queues to read packets from tun dev
|
||||
for i := 0; i < f.routines; i++ {
|
||||
f.readers.Add(1)
|
||||
f.wg.Go(func() {
|
||||
defer f.readers.Done()
|
||||
f.listenIn(f.queues[i], i)
|
||||
})
|
||||
}
|
||||
@@ -515,11 +509,10 @@ func (f *Interface) flushSendBatch(sb *batch.SendBatch, q int) {
|
||||
|
||||
func (f *Interface) RegisterConfigChangeCallbacks(c *config.C) {
|
||||
c.RegisterReloadCallback(f.reloadFirewall)
|
||||
for _, reload := range []func(*config.C){
|
||||
f.reloadSendRecvError, f.reloadAcceptRecvError, f.reloadDisconnectInvalid, f.reloadMisc,
|
||||
} {
|
||||
c.RegisterReloadCallback(func(c *config.C, _ *config.Reload) { reload(c) })
|
||||
}
|
||||
c.RegisterReloadCallback(f.reloadSendRecvError)
|
||||
c.RegisterReloadCallback(f.reloadAcceptRecvError)
|
||||
c.RegisterReloadCallback(f.reloadDisconnectInvalid)
|
||||
c.RegisterReloadCallback(f.reloadMisc)
|
||||
|
||||
for _, udpConn := range f.writers {
|
||||
c.RegisterReloadCallback(udpConn.ReloadConfig)
|
||||
@@ -536,19 +529,18 @@ func (f *Interface) reloadDisconnectInvalid(c *config.C) {
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
||||
func (f *Interface) reloadFirewall(c *config.C) {
|
||||
cs := f.pki.getCertState()
|
||||
curCert := cs.getCertificate(cert.Version2)
|
||||
if curCert == nil {
|
||||
curCert = cs.getCertificate(cert.Version1)
|
||||
}
|
||||
|
||||
// Compare with what the running firewall was built from, not the last config, so a firewall that failed to build
|
||||
// is tried again. The cert is the one this reload brought, PKI registers its reload callback before this one
|
||||
src := c.Render("firewall")
|
||||
if src != "" && src == f.firewall.source && curCert != nil &&
|
||||
slices.Equal(curCert.Networks(), f.firewall.assignedNetworks) &&
|
||||
slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks) {
|
||||
// The firewall builds its routableNetworks set from the certificate's UnsafeNetworks at construction.
|
||||
// Check to see if that set has changed, and if so, rebuild the firewall.
|
||||
certUnsafeChanged := curCert != nil && !slices.Equal(curCert.UnsafeNetworks(), f.firewall.unsafeNetworks)
|
||||
|
||||
if !c.HasChanged("firewall") && !certUnsafeChanged {
|
||||
f.l.Debug("No firewall config change detected")
|
||||
return
|
||||
}
|
||||
@@ -556,7 +548,6 @@ func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
||||
fw, err := NewFirewallFromConfig(f.l, cs, c)
|
||||
if err != nil {
|
||||
f.l.Error("Error while creating firewall during reload", "error", err)
|
||||
r.Failed()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -689,14 +680,6 @@ func (f *Interface) GetCertState() *CertState {
|
||||
return f.pki.getCertState()
|
||||
}
|
||||
|
||||
// shutdowner is a udp.Conn or overlay.Device whose readers can be woken without releasing their fds
|
||||
type shutdowner interface {
|
||||
Shutdown() error
|
||||
}
|
||||
|
||||
// readerShutdownTimeout bounds how long Close waits on woken readers before releasing their fds anyway
|
||||
const readerShutdownTimeout = 5 * time.Second
|
||||
|
||||
// Close releases the interface's resources: the udp sockets and the tun device.
|
||||
// It is idempotent and safe to call at any point in the lifecycle, including on an interface that never activated,
|
||||
// calls after the first return nil without doing anything.
|
||||
@@ -706,55 +689,20 @@ func (f *Interface) Close() error {
|
||||
}
|
||||
|
||||
var errs []error
|
||||
closeUdp := func(i int, u udp.Conn) {
|
||||
if err := u.Close(); err != nil {
|
||||
|
||||
// Release the udp readers
|
||||
for i, u := range f.writers {
|
||||
err := u.Close()
|
||||
if err != nil {
|
||||
f.l.Error("Error while closing udp socket", "error", err, "writer", i)
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
closeTun := func() {
|
||||
if err := f.inside.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Wake every reader before releasing any fd, one that loops back into a syscall on a reused fd number never wakes.
|
||||
// Anything without Shutdown is closed right away, as before.
|
||||
var deferred []func()
|
||||
for i, u := range f.writers {
|
||||
if s, ok := u.(shutdowner); ok {
|
||||
if err := s.Shutdown(); err != nil {
|
||||
f.l.Error("Error while shutting down udp socket", "error", err, "writer", i)
|
||||
errs = append(errs, err)
|
||||
}
|
||||
deferred = append(deferred, func() { closeUdp(i, u) })
|
||||
} else {
|
||||
closeUdp(i, u)
|
||||
}
|
||||
}
|
||||
if s, ok := f.inside.(shutdowner); ok {
|
||||
if err := s.Shutdown(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
deferred = append(deferred, closeTun)
|
||||
} else {
|
||||
closeTun()
|
||||
}
|
||||
|
||||
if len(deferred) > 0 {
|
||||
readersDone := make(chan struct{})
|
||||
go func() {
|
||||
f.readers.Wait()
|
||||
close(readersDone)
|
||||
}()
|
||||
select {
|
||||
case <-readersDone:
|
||||
case <-time.After(readerShutdownTimeout):
|
||||
f.l.Warn("Readers did not stop, closing their fds anyway", "timeout", readerShutdownTimeout)
|
||||
}
|
||||
for _, closeFn := range deferred {
|
||||
closeFn()
|
||||
}
|
||||
// Release the tun device (closing the tun also closes all readers)
|
||||
closeErr := f.inside.Close()
|
||||
if closeErr != nil {
|
||||
errs = append(errs, closeErr)
|
||||
}
|
||||
|
||||
// Release the construction token so waiters know the resources are gone
|
||||
|
||||
+4
-81
@@ -65,10 +65,10 @@ func TestReloadFirewall_CertUnsafeNetworksChanged(t *testing.T) {
|
||||
pki.cs.Store(&CertState{v2Cert: c2, initiatingVersion: cert.Version2})
|
||||
|
||||
// Reload with the same YAML so HasChanged("firewall") reports false.
|
||||
require.NoError(t, cfg.ReloadConfigString(rawYAML).Err)
|
||||
require.NoError(t, cfg.ReloadConfigString(rawYAML))
|
||||
require.False(t, cfg.HasChanged("firewall"))
|
||||
|
||||
f.reloadFirewall(cfg, nil)
|
||||
f.reloadFirewall(cfg)
|
||||
|
||||
assert.NotSame(t, fw, f.firewall, "firewall pointer should have been replaced")
|
||||
assert.Equal(t, newUnsafe, f.firewall.unsafeNetworks)
|
||||
@@ -113,85 +113,8 @@ func TestReloadFirewall_NoChange(t *testing.T) {
|
||||
l: l,
|
||||
}
|
||||
|
||||
require.NoError(t, cfg.ReloadConfigString(rawYAML).Err)
|
||||
f.reloadFirewall(cfg, nil)
|
||||
require.NoError(t, cfg.ReloadConfigString(rawYAML))
|
||||
f.reloadFirewall(cfg)
|
||||
|
||||
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)
|
||||
|
||||
// The running firewall still isn't built from what the config asks for, so the same reload fails again
|
||||
for range 2 {
|
||||
res := cfg.ReloadConfigString(rules("nope"))
|
||||
require.NoError(t, res.Err)
|
||||
assert.True(t, res.Failed)
|
||||
assert.Same(t, fw, f.firewall)
|
||||
}
|
||||
|
||||
res := cfg.ReloadConfigString(rules("tcp"))
|
||||
require.NoError(t, res.Err)
|
||||
assert.False(t, res.Failed)
|
||||
assert.NotSame(t, fw, f.firewall)
|
||||
}
|
||||
|
||||
// Every input the firewall is built from rebuilds it when it changes, and nothing else does
|
||||
func TestReloadFirewall_RebuildsOnAnyInput(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
networks := []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}
|
||||
base := "firewall:\n inbound:\n - port: any\n proto: any\n host: any\n"
|
||||
setup := func() (*config.C, *Interface, *PKI) {
|
||||
pki := &PKI{}
|
||||
pki.cs.Store(&CertState{v2Cert: &dummyCert{version: cert.Version2, networks: networks}, initiatingVersion: cert.Version2})
|
||||
cfg := config.NewC(l)
|
||||
require.NoError(t, cfg.LoadString(base))
|
||||
fw, err := NewFirewallFromConfig(l, pki.getCertState(), cfg)
|
||||
require.NoError(t, err)
|
||||
f := &Interface{pki: pki, firewall: fw, l: l}
|
||||
cfg.RegisterReloadCallback(f.reloadFirewall)
|
||||
return cfg, f, pki
|
||||
}
|
||||
setCert := func(pki *PKI, networks, unsafe []netip.Prefix) {
|
||||
pki.cs.Store(&CertState{v2Cert: &dummyCert{version: cert.Version2, networks: networks, unsafeNetworks: unsafe}, initiatingVersion: cert.Version2})
|
||||
}
|
||||
|
||||
cases := map[string]struct {
|
||||
cfg string
|
||||
cert func(*PKI)
|
||||
want bool
|
||||
}{
|
||||
"nothing": {base + "punchy:\n punch: true\n", nil, false},
|
||||
"rules": {base + " outbound:\n - port: any\n proto: any\n host: any\n", nil, true},
|
||||
"inbound_action": {base + " inbound_action: reject\n", nil, true},
|
||||
"conntrack": {base + " conntrack:\n tcp_timeout: 1m\n", nil, true},
|
||||
"networks": {base, func(p *PKI) { setCert(p, []netip.Prefix{netip.MustParsePrefix("10.0.0.2/24")}, nil) }, true},
|
||||
"unsafe_networks": {base, func(p *PKI) { setCert(p, networks, []netip.Prefix{netip.MustParsePrefix("192.168.0.0/24")}) }, true},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
cfg, f, pki := setup()
|
||||
old := f.firewall
|
||||
if tc.cert != nil {
|
||||
tc.cert(pki)
|
||||
}
|
||||
res := cfg.ReloadConfigString(tc.cfg)
|
||||
require.NoError(t, res.Err)
|
||||
assert.False(t, res.Failed)
|
||||
assert.Equal(t, tc.want, f.firewall != old)
|
||||
})
|
||||
}
|
||||
}
|
||||
+4
-10
@@ -138,21 +138,18 @@ func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, c
|
||||
h.metrics = newLighthouseMetrics()
|
||||
}
|
||||
|
||||
err := h.reload(c, true, nil)
|
||||
err := h.reload(c, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
r.RestartRequiredIfChanged("lighthouse.am_lighthouse", "listen.port", "handshakes.query_buffer", "stats.lighthouse_metrics")
|
||||
err := h.reload(c, false, r)
|
||||
c.RegisterReloadCallback(func(c *config.C) {
|
||||
err := h.reload(c, false)
|
||||
switch v := err.(type) {
|
||||
case *util.ContextualError:
|
||||
v.Log(l)
|
||||
r.Failed()
|
||||
case error:
|
||||
l.Error("failed to reload lighthouse", "error", err)
|
||||
r.Failed()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -193,8 +190,7 @@ func (lh *LightHouse) GetUpdateInterval() int64 {
|
||||
return lh.interval.Load()
|
||||
}
|
||||
|
||||
// r is nil on the initial load
|
||||
func (lh *LightHouse) reload(c *config.C, initial bool, r *config.Reload) error {
|
||||
func (lh *LightHouse) reload(c *config.C, initial bool) error {
|
||||
if initial || c.HasChanged("lighthouse.advertise_addrs") {
|
||||
rawAdvAddrs := c.GetStringSlice("lighthouse.advertise_addrs", []string{})
|
||||
advAddrs := make([]netip.AddrPort, 0)
|
||||
@@ -229,7 +225,6 @@ func (lh *LightHouse) reload(c *config.C, initial bool, r *config.Reload) error
|
||||
"addr", rawAddr,
|
||||
"entry", i+1,
|
||||
)
|
||||
r.Failed()
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -388,7 +383,6 @@ func (lh *LightHouse) reload(c *config.C, initial bool, r *config.Reload) error
|
||||
"relay", v,
|
||||
"error", err,
|
||||
)
|
||||
r.Failed()
|
||||
} else {
|
||||
lh.l.Info("Read relay from config", "relay", v)
|
||||
relaysForMe = append(relaysForMe, configRIP)
|
||||
|
||||
+14
-59
@@ -87,15 +87,15 @@ func TestReloadLighthouseInterval(t *testing.T) {
|
||||
lh.ifce = &mockEncWriter{}
|
||||
|
||||
// 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").Err)
|
||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 5"))
|
||||
assert.Equal(t, int64(5), lh.interval.Load())
|
||||
|
||||
// Subsequent calls are killed off by the LightHouse.Reload function
|
||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 10").Err)
|
||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 10"))
|
||||
assert.Equal(t, int64(10), lh.interval.Load())
|
||||
|
||||
// If this completes then nothing is stealing our reload routine
|
||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 11").Err)
|
||||
require.NoError(t, c.ReloadConfigString("lighthouse:\n interval: 11"))
|
||||
assert.Equal(t, int64(11), lh.interval.Load())
|
||||
}
|
||||
|
||||
@@ -296,7 +296,7 @@ func TestLighthouse_reload(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
c.ReloadConfigString(string(rc))
|
||||
|
||||
err = lh.reload(c, false, nil)
|
||||
err = lh.reload(c, false)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
@@ -334,7 +334,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
||||
}
|
||||
rc, err := yaml.Marshal(nc)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
||||
|
||||
rl := lh.Query(staticHost)
|
||||
require.NotNil(t, rl)
|
||||
@@ -350,7 +350,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
||||
}
|
||||
rc, err = yaml.Marshal(nc)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
||||
|
||||
rl = lh.Query(staticHost)
|
||||
require.NotNil(t, rl)
|
||||
@@ -358,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{}))
|
||||
|
||||
// Reload with the same config. An unchanged entry must not duplicate.
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
||||
|
||||
rl = lh.Query(staticHost)
|
||||
require.NotNil(t, rl)
|
||||
@@ -373,7 +373,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
||||
}
|
||||
rc, err = yaml.Marshal(nc)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
||||
|
||||
// Add a second host alongside the first. Both should be present, neither duplicated.
|
||||
nc = map[string]any{
|
||||
@@ -384,7 +384,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
||||
}
|
||||
rc, err = yaml.Marshal(nc)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
||||
|
||||
rl = lh.Query(staticHost)
|
||||
require.NotNil(t, rl)
|
||||
@@ -406,7 +406,7 @@ func TestLighthouse_reloadStaticHostMap(t *testing.T) {
|
||||
}
|
||||
rc, err = yaml.Marshal(nc)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)).Err)
|
||||
require.NoError(t, c.ReloadConfigString(string(rc)))
|
||||
|
||||
_, isStatic := lh.GetStaticHostList()[staticHost]
|
||||
assert.False(t, isStatic)
|
||||
@@ -966,13 +966,13 @@ func TestLighthouse_reloadRelaysTriggersUpdate(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, lh.updateTrigger)
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(base+"relay:\n relays: [10.128.0.6]\n").Err)
|
||||
require.NoError(t, c.ReloadConfigString(base+"relay:\n relays: [10.128.0.6]\n"))
|
||||
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)
|
||||
require.NoError(t, c.ReloadConfigString(base+"relay:\n relays: [10.128.0.6, nope]\n"))
|
||||
assert.Equal(t, []netip.Addr{netip.MustParseAddr("10.128.0.6")}, lh.GetRelaysForMe())
|
||||
assert.Empty(t, lh.updateTrigger)
|
||||
}
|
||||
@@ -988,57 +988,12 @@ func TestLighthouse_reloadAmRelayAlone(t *testing.T) {
|
||||
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)
|
||||
require.NoError(t, c.ReloadConfigString(base+" am_relay: true\n"))
|
||||
assert.Empty(t, lh.GetRelaysForMe())
|
||||
require.Len(t, lh.updateTrigger, 1)
|
||||
<-lh.updateTrigger
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(base+" am_relay: false\n").Err)
|
||||
require.NoError(t, c.ReloadConfigString(base+" am_relay: false\n"))
|
||||
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())
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Access is who may reach a socket beyond the account nebula runs as: the node's mode,
|
||||
// and the group that shares the socket when the config names one.
|
||||
//
|
||||
// It is the dockerd model (-G): the operator names a group, nebula hands the socket to
|
||||
// it, and who is in the group is managed outside nebula. On unix the mode is the
|
||||
// socket node's and the group becomes its owning group; on windows the group is an
|
||||
// entry in the pipe's security descriptor and the mode means nothing to a pipe.
|
||||
type Access struct {
|
||||
Mode os.FileMode
|
||||
Group Group
|
||||
}
|
||||
|
||||
// Group is a group named in the config, resolved to what the platform checks. The zero
|
||||
// Group is none.
|
||||
type Group struct {
|
||||
// Name is what the config said.
|
||||
Name string
|
||||
|
||||
// ID is the platform's identifier for it: a gid on unix, a SID on windows.
|
||||
ID string
|
||||
}
|
||||
|
||||
const (
|
||||
// ownerOnlyMode is a socket's mode when no group shares it: the account nebula runs
|
||||
// as, and nobody else.
|
||||
ownerOnlyMode os.FileMode = 0600
|
||||
|
||||
// groupSocketMode is the mode a socket takes when a group shares it and the config
|
||||
// names no other: the account nebula runs as and the group, and nobody else.
|
||||
groupSocketMode os.FileMode = 0660
|
||||
)
|
||||
|
||||
// errReopenForAccess is returned by applyAccess on a platform whose access control is
|
||||
// fixed when the endpoint is created, so a change means creating it again.
|
||||
var errReopenForAccess = errors.New("access is fixed at listen time")
|
||||
|
||||
// ownerOnly is the control socket's access when no group is configured. The mode
|
||||
// itself is not configurable there; what an operator can choose is a group,
|
||||
// CtlGroupKey, which makes it groupSocketMode.
|
||||
func ownerOnly() Access { return Access{Mode: ownerOnlyMode} }
|
||||
|
||||
// shared reports whether a group shares the socket.
|
||||
func (a Access) shared() bool { return a.Group.ID != "" }
|
||||
|
||||
// String renders the access for a log line.
|
||||
func (a Access) String() string {
|
||||
if !a.shared() {
|
||||
return modeString(a.Mode)
|
||||
}
|
||||
return fmt.Sprintf("%s group %s (%s)", modeString(a.Mode), a.Group.Name, a.Group.ID)
|
||||
}
|
||||
|
||||
// groupFromConfig reads the group a key names, the zero Group when it names none. The
|
||||
// name is resolved here, when the config is read, so a group that does not exist is a
|
||||
// config error reported with the key rather than a bind that fails later.
|
||||
func groupFromConfig(c interface{ GetString(string, string) string }, key string) (Group, error) {
|
||||
name := c.GetString(key, "")
|
||||
if name == "" {
|
||||
return Group{}, nil
|
||||
}
|
||||
|
||||
id, err := lookupGroupID(name)
|
||||
if err != nil {
|
||||
return Group{}, fmt.Errorf("%s: %w", key, err)
|
||||
}
|
||||
return Group{Name: name, ID: id}, nil
|
||||
}
|
||||
|
||||
func modeString(m os.FileMode) string {
|
||||
return fmt.Sprintf("%04o", m)
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// ownGroup returns a group this process may hand a socket to: its own effective group,
|
||||
// by name and by gid, which is the one chown accepts from an unprivileged user.
|
||||
func ownGroup(t *testing.T) (name, gid string) {
|
||||
t.Helper()
|
||||
gid = strconv.Itoa(os.Getegid())
|
||||
g, err := user.LookupGroupId(gid)
|
||||
require.NoError(t, err)
|
||||
return g.Name, gid
|
||||
}
|
||||
|
||||
func socketGroup(t *testing.T, path string) uint32 {
|
||||
t.Helper()
|
||||
fi, err := os.Lstat(path)
|
||||
require.NoError(t, err)
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
require.True(t, ok)
|
||||
return uint32(st.Gid)
|
||||
}
|
||||
|
||||
// TestLookupGroupID: a group is named as the host names it or by its gid; a gid the
|
||||
// host does not list is accepted as chown would accept it, and a name it does not list
|
||||
// is a mistake to report.
|
||||
func TestLookupGroupID(t *testing.T) {
|
||||
name, gid := ownGroup(t)
|
||||
|
||||
got, err := lookupGroupID(name)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gid, got)
|
||||
|
||||
got, err = lookupGroupID(gid)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gid, got)
|
||||
|
||||
got, err = lookupGroupID("4000000000")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "4000000000", got)
|
||||
|
||||
_, err = lookupGroupID("no-such-group-nebula-test")
|
||||
require.ErrorContains(t, err, "does not exist")
|
||||
}
|
||||
|
||||
// TestControlAccessFromConfig: no group is the owner-only socket; a group is 0660 with
|
||||
// that group; a group the host does not know is a config error naming the key.
|
||||
func TestControlAccessFromConfig(t *testing.T) {
|
||||
name, gid := ownGroup(t)
|
||||
load := func(body string) (Access, error) {
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(body))
|
||||
return controlAccessFrom(c)
|
||||
}
|
||||
|
||||
acc, err := load("local_api: {}\n")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ownerOnly(), acc)
|
||||
|
||||
acc, err = load("local_api:\n control:\n group: " + name + "\n")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0660), acc.Mode)
|
||||
assert.Equal(t, name, acc.Group.Name)
|
||||
assert.Equal(t, gid, acc.Group.ID)
|
||||
|
||||
_, err = load("local_api:\n control:\n group: no-such-group-nebula-test\n")
|
||||
require.ErrorContains(t, err, CtlGroupKey)
|
||||
assert.ErrorContains(t, err, "does not exist")
|
||||
}
|
||||
|
||||
// TestControlSocketIsHandedToTheGroup: the socket is created with the group's gid and
|
||||
// 0660, whatever the umask, and a reload that takes the group away tightens the socket
|
||||
// in place, without moving it. The endpoint is shared, so this covers the info API too.
|
||||
func TestControlSocketIsHandedToTheGroup(t *testing.T) {
|
||||
old := unix.Umask(0077)
|
||||
defer unix.Umask(old)
|
||||
|
||||
name, gid := ownGroup(t)
|
||||
want, err := strconv.ParseUint(gid, 10, 32)
|
||||
require.NoError(t, err)
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
path := testSocket(t)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: 0660, Group: Group{Name: name, ID: gid}}))
|
||||
defer s.Stop()
|
||||
|
||||
fi, err := os.Lstat(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0660), fi.Mode().Perm())
|
||||
assert.Equal(t, uint32(want), socketGroup(t, path))
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
fi, err = os.Lstat(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0600), fi.Mode().Perm())
|
||||
assert.Equal(t, path, s.Path())
|
||||
|
||||
_, err = (&Client{Path: path}).Describe()
|
||||
require.NoError(t, err, "the same listener is still serving")
|
||||
}
|
||||
|
||||
// TestControlSocketWithAGroupTrustsTheKernel: with a group sharing the socket, the
|
||||
// kernel's check on connect is the access control and the daemon's peer check stands
|
||||
// aside, so a connection the peer check alone would refuse is served. Without a group
|
||||
// the same connection is refused; see TestPeerCheckRefusesAnotherUser.
|
||||
func TestControlSocketWithAGroupTrustsTheKernel(t *testing.T) {
|
||||
if !peerCheckSupported {
|
||||
t.Skip("no peer credentials on this platform")
|
||||
}
|
||||
name, gid := ownGroup(t)
|
||||
|
||||
me := currentUID()
|
||||
asUID(t, me+1)
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
asUID(t, me)
|
||||
|
||||
path := testSocket(t)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: 0660, Group: Group{Name: name, ID: gid}}))
|
||||
defer s.Stop()
|
||||
|
||||
_, err := (&Client{Path: path}).Describe()
|
||||
require.NoError(t, err, "the socket's group admitted us; the peer check must not refuse")
|
||||
|
||||
// Taking the group away on a reload puts the peer check back.
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
_, err = (&Client{Path: path}).Describe()
|
||||
require.ErrorContains(t, err, "not permitted")
|
||||
}
|
||||
|
||||
// TestInfoAccessFromConfig: a group with no mode is 0660; a mode that gives the group
|
||||
// nothing is refused, with the mode that would; an explicit mode with group bits is
|
||||
// kept as given.
|
||||
func TestInfoAccessFromConfig(t *testing.T) {
|
||||
name, gid := ownGroup(t)
|
||||
load := func(body string) (infoConfig, error) {
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(body))
|
||||
return infoConfigFrom(c)
|
||||
}
|
||||
section := func(extra string) string {
|
||||
return "local_api:\n info:\n enabled: true\n socket: /run/nebula/info.sock\n" + extra
|
||||
}
|
||||
|
||||
cfg, err := load(section(" group: " + name + "\n"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0660), cfg.Access.Mode)
|
||||
assert.Equal(t, gid, cfg.Access.Group.ID)
|
||||
|
||||
cfg, err = load(section(" group: " + name + "\n socket_mode: \"0664\"\n"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0664), cfg.Access.Mode)
|
||||
|
||||
_, err = load(section(" group: " + name + "\n socket_mode: \"0600\"\n"))
|
||||
require.ErrorContains(t, err, "gives group "+name+" no access")
|
||||
require.ErrorContains(t, err, `"0660"`)
|
||||
|
||||
cfg, err = load(section(""))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ownerOnly(), cfg.Access)
|
||||
}
|
||||
|
||||
// TestRemovingTheGroupHandsTheSocketBack: a reload that drops the group key leaves the
|
||||
// mode the operator set but returns the socket to the daemon's own group, so the old
|
||||
// group's members are no longer admitted. The socket is first handed to a group this
|
||||
// process belongs to other than its own, which not every host offers.
|
||||
func TestRemovingTheGroupHandsTheSocketBack(t *testing.T) {
|
||||
own := os.Getegid()
|
||||
groups, err := os.Getgroups()
|
||||
require.NoError(t, err)
|
||||
other := -1
|
||||
for _, g := range groups {
|
||||
if g != own {
|
||||
other = g
|
||||
break
|
||||
}
|
||||
}
|
||||
if other < 0 {
|
||||
t.Skip("this process belongs to no group but its own")
|
||||
}
|
||||
gid := strconv.Itoa(other)
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
path := testSocket(t)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: 0660, Group: Group{Name: gid, ID: gid}}))
|
||||
defer s.Stop()
|
||||
assert.Equal(t, uint32(other), socketGroup(t, path))
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: 0660}))
|
||||
assert.Equal(t, uint32(own), socketGroup(t, path), "the daemon's own group again")
|
||||
fi, err := os.Lstat(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0660), fi.Mode().Perm(), "the mode is the operator's")
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// TestLookupGroupIDOnWindows: an account name resolves to its SID, a SID written out
|
||||
// is accepted as it is, and an account the host does not know is reported.
|
||||
func TestLookupGroupIDOnWindows(t *testing.T) {
|
||||
users, err := windows.CreateWellKnownSid(windows.WinBuiltinUsersSid)
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := lookupGroupID("Users")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, users.String(), got)
|
||||
|
||||
got, err = lookupGroupID(users.String())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, users.String(), got)
|
||||
|
||||
_, err = lookupGroupID("no-such-account-nebula-test")
|
||||
require.ErrorContains(t, err, "does not exist")
|
||||
}
|
||||
|
||||
// TestSDDLAdmitsTheGroup: the descriptor is the owner, SYSTEM and Administrators with
|
||||
// full access, plus the group with what a client needs and nothing generic, so a
|
||||
// member cannot create an instance of the pipe; see pipeClientAccess.
|
||||
func TestSDDLAdmitsTheGroup(t *testing.T) {
|
||||
sddl, err := sddlFor(ownerOnly())
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, sddl, "S-1-5-32-545")
|
||||
|
||||
sddl, err = sddlFor(Access{Mode: groupSocketMode, Group: Group{Name: "Users", ID: "S-1-5-32-545"}})
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, sddl, "(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x120083;;;S-1-5-32-545)")
|
||||
assert.Zero(t, pipeClientAccess&windows.FILE_APPEND_DATA, "FILE_APPEND_DATA is FILE_CREATE_PIPE_INSTANCE on a pipe")
|
||||
assert.Zero(t, pipeClientAccess&(windows.GENERIC_READ|windows.GENERIC_WRITE|windows.GENERIC_ALL))
|
||||
}
|
||||
|
||||
// TestUnprotectedNameWarning: a pipe outside the protected namespace is warned about,
|
||||
// since anyone could have created the name first; one under it, however spelled, is not.
|
||||
func TestUnprotectedNameWarning(t *testing.T) {
|
||||
assert.Empty(t, unprotectedNameWarning(DefaultSocketPath))
|
||||
assert.Empty(t, unprotectedNameWarning(`\\.\PIPE\protectedprefix\administrators\nebula-info`))
|
||||
assert.Contains(t, unprotectedNameWarning(`\\.\pipe\nebula-info`), protectedPrefix)
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
//go:build darwin || freebsd || netbsd || openbsd
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// applyAccess sets the owning group and the mode of the socket node at path, and of
|
||||
// nothing a link at path names. The node is looked at without following links and must
|
||||
// be a socket of ours; the chown and the chmod are fchownat and fchmodat with
|
||||
// AT_SYMLINK_NOFOLLOW, which these kernels honour, so a symlink put at path in the one
|
||||
// syscall between the look and either call gets its own group or mode changed, which
|
||||
// means nothing, and not its target's. A socket cannot be opened, and there is no O_PATH
|
||||
// here to hold the inode across the calls the way the linux side does, so a hard link
|
||||
// to a file of somebody's choosing swapped in during that one syscall would be changed;
|
||||
// that needs the file on the socket's filesystem and the right to link to it, which
|
||||
// darwin and the BSDs grant to any user by default.
|
||||
func applyAccess(path string, acc Access) error {
|
||||
fi, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkOwnSocket(path, fi); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// With no group configured the socket is handed back to the daemon's own group, so a
|
||||
// reload that drops the key takes the access away; see the linux side.
|
||||
gid, err := gidFor(acc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := unix.Fchownat(unix.AT_FDCWD, path, -1, gid, unix.AT_SYMLINK_NOFOLLOW); err != nil {
|
||||
return &os.PathError{Op: "chown", Path: path, Err: err}
|
||||
}
|
||||
|
||||
if err := unix.Fchmodat(unix.AT_FDCWD, path, uint32(acc.Mode.Perm()), unix.AT_SYMLINK_NOFOLLOW); err != nil {
|
||||
return &os.PathError{Op: "chmod", Path: path, Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// applyAccess sets the owning group and the mode of the socket node at path, and of
|
||||
// nothing else. The node is opened O_PATH, which takes a reference to the inode without
|
||||
// opening the socket itself (a socket cannot be opened, and O_PATH does not try), and
|
||||
// O_NOFOLLOW, so a symlink at path is a refusal rather than a target. What the
|
||||
// descriptor holds is checked to be a socket of ours, and the chown and the chmod are
|
||||
// then made through /proc/self/fd, which names that inode whatever is at path by then:
|
||||
// a node swapped between the look and the change, for a link or for a hard link to a
|
||||
// file of somebody's choosing, is not what gets the group or the mode. This is how
|
||||
// glibc implements fchmodat(AT_SYMLINK_NOFOLLOW) too.
|
||||
//
|
||||
// Without /proc the change falls back to fchownat and fchmodat2, which do not follow a
|
||||
// link but are by path again, so a swap in the one syscall between the check and each
|
||||
// would be changed. Older than kernel 6.6 with no /proc, the mode is not set and the
|
||||
// socket is not served.
|
||||
func applyAccess(path string, acc Access) error {
|
||||
// The look is for the message: a link or a plain file is named as what it is, which
|
||||
// the O_PATH open's ELOOP or the fstat below would say less well.
|
||||
fi, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkOwnSocket(path, fi); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fd, err := unix.Open(path, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return &os.PathError{Op: "open", Path: path, Err: err}
|
||||
}
|
||||
defer unix.Close(fd)
|
||||
|
||||
// What the descriptor holds is what the changes land on; the Lstat above looked at
|
||||
// the path, which may have changed since.
|
||||
var st unix.Stat_t
|
||||
if err := unix.Fstat(fd, &st); err != nil {
|
||||
return &os.PathError{Op: "fstat", Path: path, Err: err}
|
||||
}
|
||||
if st.Mode&unix.S_IFMT != unix.S_IFSOCK || st.Uid != currentUID() {
|
||||
return fmt.Errorf("%s was replaced while its access was being set, refusing to change it", path)
|
||||
}
|
||||
|
||||
// The /proc name of the inode the descriptor holds. ENOENT from it means no /proc.
|
||||
held := "/proc/self/fd/" + strconv.Itoa(fd)
|
||||
|
||||
// The group first: a chown by root clears the setgid bit, which a socket never has,
|
||||
// but the mode is pinned afterwards either way. With no group configured the socket
|
||||
// is handed back to the daemon's own, so taking the key out of the config on a reload
|
||||
// takes the access away as surely as a restart would.
|
||||
gid, err := gidFor(acc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = unix.Chown(held, -1, gid)
|
||||
if err == unix.ENOENT {
|
||||
err = unix.Fchownat(unix.AT_FDCWD, path, -1, gid, unix.AT_SYMLINK_NOFOLLOW)
|
||||
}
|
||||
if err != nil {
|
||||
return &os.PathError{Op: "chown", Path: path, Err: err}
|
||||
}
|
||||
|
||||
perm := uint32(acc.Mode.Perm())
|
||||
err = unix.Chmod(held, perm)
|
||||
if err == unix.ENOENT {
|
||||
err = unix.Fchmodat(unix.AT_FDCWD, path, perm, unix.AT_SYMLINK_NOFOLLOW)
|
||||
}
|
||||
if err != nil {
|
||||
return &os.PathError{Op: "chmod", Path: path, Err: err}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
)
|
||||
|
||||
// DialTimeout bounds the connect to a socket that exists but is not being served.
|
||||
const DialTimeout = 5 * time.Second
|
||||
|
||||
// ResponseTimeout bounds the exchange once connected: sending the request and waiting
|
||||
// for the daemon's answer. The daemon drops a client that is slow to send in 10s and one
|
||||
// that is slow to read in 30s, so this is the other side of the same bargain, with room
|
||||
// for the slowest command (a hostmap dump on a large network) before a stalled daemon is
|
||||
// given up on. Client.Timeout overrides it.
|
||||
const ResponseTimeout = 60 * time.Second
|
||||
|
||||
// MaxResponseBytes bounds what a client will read back. A response carries one command's
|
||||
// output, and a hostmap dump on a large network is the realistic worst case.
|
||||
const MaxResponseBytes = 64 << 20
|
||||
|
||||
// Client talks to a nebula listening at Path.
|
||||
type Client struct {
|
||||
Path string
|
||||
|
||||
// Timeout bounds the request and response once connected. Zero means
|
||||
// ResponseTimeout.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// ReplyError is an answer the client could not read: the daemon was reached and wrote
|
||||
// something back, but not a response this client understands. The daemon is not
|
||||
// nebula, or not a version this client speaks to.
|
||||
type ReplyError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *ReplyError) Error() string { return "the daemon's reply could not be read: " + e.Err.Error() }
|
||||
func (e *ReplyError) Unwrap() error { return e.Err }
|
||||
|
||||
// DaemonError is a refusal the daemon answered with: the connection worked, the request
|
||||
// was read, and the daemon said no. It is told apart from a failure to reach the daemon
|
||||
// so that a client does not send its user after a socket path, or a sudo, when the daemon
|
||||
// was right there and answered. A protocol version the daemon does not speak, a socket at
|
||||
// its connection limit and a peer the daemon will not serve all arrive as one of these.
|
||||
type DaemonError struct {
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *DaemonError) Error() string { return e.Msg }
|
||||
|
||||
// Describe asks the daemon which commands it serves and what parameters they take, so a
|
||||
// client can offer them without having been built against this daemon.
|
||||
func (c *Client) Describe() ([]commands.CommandSchema, error) {
|
||||
res, err := c.do(&Request{Version: ProtocolVersion, Describe: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if res.Error != "" {
|
||||
return nil, &DaemonError{Msg: res.Error}
|
||||
}
|
||||
|
||||
schema := []commands.CommandSchema{}
|
||||
if err := json.Unmarshal(res.Result, &schema); err != nil {
|
||||
return nil, &ReplyError{Err: fmt.Errorf("could not parse the command schema: %w", err)}
|
||||
}
|
||||
|
||||
return schema, nil
|
||||
}
|
||||
|
||||
// Invoke runs one command and returns what the daemon said. params are the command's
|
||||
// options by name, as the strings a command line parsed them from; a program speaking
|
||||
// the protocol directly may send JSON's own types instead, see Request.Params. An empty
|
||||
// format asks for JSON, which is the API's default; "text" asks the daemon to apply the
|
||||
// command's own human rendering.
|
||||
func (c *Client) Invoke(command string, params map[string]string, args []string, format string) (*Response, error) {
|
||||
var wire map[string]any
|
||||
if len(params) > 0 {
|
||||
wire = make(map[string]any, len(params))
|
||||
for k, v := range params {
|
||||
wire[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
return c.do(&Request{
|
||||
Version: ProtocolVersion,
|
||||
Command: command,
|
||||
Params: wire,
|
||||
Args: args,
|
||||
Format: format,
|
||||
})
|
||||
}
|
||||
|
||||
// do sends one request and reads the one response.
|
||||
//
|
||||
// Nothing is checked about the socket before the connect: its mode is the kernel's to
|
||||
// enforce, and a socket that is not ours to connect to is refused there with a
|
||||
// permission error, which the caller turns into advice.
|
||||
func (c *Client) do(req *Request) (*Response, error) {
|
||||
conn, err := dial(c.Path, DialTimeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Without this a daemon that accepts and then stalls, blocked inside a command or
|
||||
// stopped with SIGSTOP, hangs the client for good, and a script wrapping it never
|
||||
// completes. One deadline covers the write and the read: the answer is due within
|
||||
// the budget, however the time is spent.
|
||||
timeout := c.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = ResponseTimeout
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(timeout))
|
||||
|
||||
// If we get a write error, save that fact but then look for a response from the server.
|
||||
// Some error conditions manifest as the server accepting our connection, writing an
|
||||
// error, and then closing the connection. Our write races against that close.
|
||||
writeErr := error(nil)
|
||||
if err := writeFrame(conn, req); err != nil {
|
||||
writeErr = fmt.Errorf("could not send request: %w", err)
|
||||
}
|
||||
|
||||
res, err := readResponse(conn)
|
||||
if err != nil {
|
||||
// Something answered and it was not a response: the daemon was reached, and
|
||||
// that is the message even when it hung up before the request was written,
|
||||
// which a daemon that is not nebula is likely to do.
|
||||
var fe *frameError
|
||||
if errors.As(err, &fe) {
|
||||
return nil, &ReplyError{Err: err}
|
||||
}
|
||||
if writeErr != nil {
|
||||
return nil, writeErr
|
||||
}
|
||||
var ne net.Error
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
return nil, fmt.Errorf("the daemon did not answer within %s", timeout)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func readResponse(conn net.Conn) (*Response, error) {
|
||||
res := &Response{}
|
||||
if err := readFrame(conn, MaxResponseBytes, "response", res, false); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil, errors.New("the daemon closed the connection without answering")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// endpoint is the lifecycle the two local APIs share: one socket at a path, bound and
|
||||
// given up under a mutex, moved by binding the new path before the old one is released,
|
||||
// and stopped when the context that brought it up ends. What is served on the socket,
|
||||
// and by what, is the embedding server's: it hands rebindLocked a serve function and
|
||||
// gets back the thing to close.
|
||||
type endpoint struct {
|
||||
l *slog.Logger
|
||||
|
||||
// name is what the endpoint is called in its own log lines and errors, so the two
|
||||
// read apart.
|
||||
name string
|
||||
|
||||
mu sync.Mutex
|
||||
|
||||
// closer stops the serving when closed: the listener itself, or the server that owns
|
||||
// it. It is nil while the endpoint is stopped, which is what stopped means here.
|
||||
closer io.Closer
|
||||
path string
|
||||
access Access
|
||||
unwatch func() bool
|
||||
|
||||
// id identifies the node listen created at path, so a reload can tell whether the
|
||||
// socket is still there and Stop whether the node it would unlink is still ours.
|
||||
id socketID
|
||||
}
|
||||
|
||||
// socketID identifies a socket's node on the filesystem, by device and inode on unix.
|
||||
// The zero value is no identity: a platform with no node to identify, or one that could
|
||||
// not be read, and removeSocket then unlinks without looking.
|
||||
type socketID struct {
|
||||
dev, ino uint64
|
||||
}
|
||||
|
||||
// Path returns the socket path currently being served, or "" when stopped.
|
||||
func (e *endpoint) Path() string {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.path
|
||||
}
|
||||
|
||||
// rebindLocked brings the endpoint up at path with acc, moves it there, or, when it is
|
||||
// already there, applies a changed access; with nothing changed it does nothing, which
|
||||
// is what lets Wire's first attempt and its reload callback be the same call.
|
||||
//
|
||||
// The new socket is bound before the old one is given up: a bad path in a reloaded
|
||||
// config leaves the operator with the endpoint they already had rather than none. serve
|
||||
// is handed the new listener once it is certain to be kept and returns what to close to
|
||||
// stop serving it; what becomes of the old socket's connections is that closer's.
|
||||
//
|
||||
// The caller holds e.mu for the whole operation, bind included. Releasing it around
|
||||
// listen would let a Stop land in between, and this would then install a fresh socket on
|
||||
// an endpoint that had just shut down, leaving a live socket on disk until the process
|
||||
// exits. listen does not take e.mu, so holding it costs the other methods one bind's
|
||||
// wait, at most the stale socket probe, once per reload.
|
||||
func (e *endpoint) rebindLocked(ctx context.Context, path string, acc Access, serve func(net.Listener) io.Closer) error {
|
||||
reopening := false
|
||||
if e.closer != nil && e.path == path {
|
||||
if cur, ok := identifySocket(path); ok && cur == e.id {
|
||||
if e.access == acc {
|
||||
return nil
|
||||
}
|
||||
err := applyAccess(path, acc)
|
||||
if err == nil {
|
||||
e.access = acc
|
||||
e.l.Info("Changed the "+e.name+"'s socket access", "path", path, "access", acc.String())
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, errReopenForAccess) {
|
||||
return fmt.Errorf("could not change the access of %s: %w", path, err)
|
||||
}
|
||||
|
||||
// The platform fixes access when the endpoint is created, so it is created
|
||||
// again. The name cannot be held twice, so the old one goes first, and a bind
|
||||
// that then fails leaves the endpoint down rather than on the old access the
|
||||
// operator asked to change; that is reported below.
|
||||
reopening = true
|
||||
old := e.closer
|
||||
e.forgetLocked()
|
||||
_ = old.Close()
|
||||
} else {
|
||||
// The node at the path is not the one this endpoint bound: something outside
|
||||
// nebula removed it, logind clearing /run/user/<uid> on logout or a unit
|
||||
// cleaning a RuntimeDirectory= it shares, or replaced it. The listener is still
|
||||
// open and nothing can reach it, so it is given up now and the path is bound
|
||||
// afresh below; listen's stale check decides whether whatever is there now may
|
||||
// be cleared. Given up first, rather than after a successful bind as a move
|
||||
// does, so that a bind that fails leaves the endpoint reported as down, which
|
||||
// it is, instead of serving a path nothing can reach.
|
||||
e.l.Warn("The "+e.name+"'s socket is no longer at its path, binding it again", "path", path)
|
||||
old := e.closer
|
||||
e.forgetLocked()
|
||||
_ = old.Close()
|
||||
}
|
||||
}
|
||||
|
||||
ln, err := listen(path, acc)
|
||||
if err != nil {
|
||||
if reopening {
|
||||
return fmt.Errorf("the %s was closed to change its access and could not be created again: %w", e.name, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
id, _ := identifySocket(path)
|
||||
|
||||
// A reload that arrives during shutdown must not bring the endpoint back. Stop is
|
||||
// not terminal (a Rebind after Stop is allowed, and is how an endpoint whose first
|
||||
// bind failed comes up), so whether it is running is no guide; the context is what
|
||||
// shutdown cancels, and it is checked here, while nothing else can change the state.
|
||||
if err := ctx.Err(); err != nil {
|
||||
release(ln, path, id)
|
||||
return fmt.Errorf("not starting the %s, nebula is shutting down: %w", e.name, err)
|
||||
}
|
||||
|
||||
old, oldPath, oldID := e.closer, e.path, e.id
|
||||
e.closer = serve(ln)
|
||||
e.path = path
|
||||
e.access = acc
|
||||
e.id = id
|
||||
e.watchLocked(ctx)
|
||||
|
||||
// Stop serving the old socket. When it was on this same path its node is already
|
||||
// gone, and the node there now is the new socket's, so only the closer goes.
|
||||
if old != nil {
|
||||
if oldPath == path {
|
||||
_ = old.Close()
|
||||
} else {
|
||||
release(old, oldPath, oldID)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// watchLocked stops the endpoint when ctx is cancelled. One watcher covers a run of the
|
||||
// endpoint, from the first bind that succeeds until Stop: a daemon whose initial listen
|
||||
// failed and which later Rebinds onto a good path from a reloaded config still needs its
|
||||
// socket removed on shutdown, and a Rebind on a running endpoint must not stack a second
|
||||
// watcher on the same ctx. Stop detaches the watcher, so an endpoint started again
|
||||
// afterwards is watched on the ctx that started it, and the ctx of an earlier run no
|
||||
// longer reaches it whenever that one ends. Callers hold e.mu.
|
||||
func (e *endpoint) watchLocked(ctx context.Context) {
|
||||
if e.unwatch != nil {
|
||||
return
|
||||
}
|
||||
e.unwatch = context.AfterFunc(ctx, e.Stop)
|
||||
}
|
||||
|
||||
// Stop closes the endpoint and removes its socket. Work in flight is the closer's
|
||||
// business: a listener leaves the connections it already accepted to finish, a server
|
||||
// cuts them off.
|
||||
//
|
||||
// The whole of it runs under e.mu, closer and socket included, so a Rebind cannot land
|
||||
// between the state change and the close and find a path that is still bound by the
|
||||
// socket it is replacing.
|
||||
func (e *endpoint) Stop() {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
||||
if e.closer == nil {
|
||||
return
|
||||
}
|
||||
|
||||
release(e.closer, e.path, e.id)
|
||||
e.forgetLocked()
|
||||
}
|
||||
|
||||
// forgetLocked drops the state of a run once its socket has been given up, the watcher
|
||||
// with it: one watcher covers one run, and a bind that follows starts a new one on the
|
||||
// ctx it was given. The watcher is set whenever closer is; when the Stop that got here
|
||||
// is the watcher's own, stopping one that has already fired is a no-op.
|
||||
func (e *endpoint) forgetLocked() {
|
||||
e.closer, e.path, e.access, e.id = nil, "", Access{}, socketID{}
|
||||
if e.unwatch != nil {
|
||||
e.unwatch()
|
||||
e.unwatch = nil
|
||||
}
|
||||
}
|
||||
|
||||
// release gives up a socket's closer and the node at its path. The node goes first,
|
||||
// while the socket is still open: for as long as it is, the node is this endpoint's,
|
||||
// since a starting daemon's stale check refuses to remove a socket that answers. The
|
||||
// other order opens a window between the close and the unlink in which a new daemon can
|
||||
// find the node stale, clear it and bind its own at the same path, which the unlink then
|
||||
// takes from under it, leaving that daemon serving a socket nothing can reach. listen
|
||||
// turns off the listener's own unlink on close so this is the only unlink. id is the
|
||||
// node listen created, and the only node removeSocket will remove: one that replaced it,
|
||||
// another daemon's socket bound after ours was taken from under us, is left alone.
|
||||
func release(c io.Closer, path string, id socketID) {
|
||||
removeSocket(path, id)
|
||||
_ = c.Close()
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// lookupGroupID resolves a group's name, or a numeric gid, to the gid as a string. A
|
||||
// gid that the group database does not list is accepted as chown would accept it: the
|
||||
// operator may be naming a group the host will learn about later, or one that only a
|
||||
// directory service knows.
|
||||
func lookupGroupID(name string) (string, error) {
|
||||
if g, err := user.LookupGroup(name); err == nil {
|
||||
return g.Gid, nil
|
||||
}
|
||||
|
||||
if _, err := strconv.ParseUint(name, 10, 32); err == nil {
|
||||
return name, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("group %q does not exist on this host", name)
|
||||
}
|
||||
|
||||
// gidFor returns the gid the socket is owned by under acc: the configured group's, or
|
||||
// the daemon's own effective group when none is configured.
|
||||
func gidFor(acc Access) (int, error) {
|
||||
if !acc.shared() {
|
||||
return os.Getegid(), nil
|
||||
}
|
||||
gid, err := strconv.ParseUint(acc.Group.ID, 10, 32)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("group %q resolved to %q, which is not a gid", acc.Group.Name, acc.Group.ID)
|
||||
}
|
||||
return int(gid), nil
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// lookupGroupID resolves an account name, local or domain qualified, or a SID written
|
||||
// out, to the SID as a string, which is how the pipe's security descriptor names it.
|
||||
// Any account the host can resolve is accepted, as docker accepts any SID for its -G: a
|
||||
// group is the natural thing to name, but the descriptor does not care.
|
||||
func lookupGroupID(name string) (string, error) {
|
||||
if strings.HasPrefix(strings.ToUpper(name), "S-1-") {
|
||||
sid, err := windows.StringToSid(name)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%q is not a SID: %w", name, err)
|
||||
}
|
||||
return sid.String(), nil
|
||||
}
|
||||
|
||||
sid, _, _, err := windows.LookupSID("", name)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("account %q does not exist on this host: %w", name, err)
|
||||
}
|
||||
return sid.String(), nil
|
||||
}
|
||||
@@ -1,452 +0,0 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"golang.org/x/net/netutil"
|
||||
)
|
||||
|
||||
// The info API's config keys. It is off until InfoEnabledKey is true and InfoSocketKey
|
||||
// names a socket; nothing is derived, because the programs that will dial it have to be
|
||||
// told where it is anyway.
|
||||
const (
|
||||
InfoEnabledKey = "local_api.info.enabled"
|
||||
InfoSocketKey = "local_api.info.socket"
|
||||
InfoModeKey = "local_api.info.socket_mode"
|
||||
InfoGroupKey = "local_api.info.group"
|
||||
)
|
||||
|
||||
const (
|
||||
// infoMaxConns bounds the connections held open at once. Beyond it the kernel
|
||||
// queues, which is what an HTTP client expects of a busy server; the control socket
|
||||
// refuses instead because its clients are people at a prompt.
|
||||
infoMaxConns = 64
|
||||
|
||||
infoWriteTimeout = 30 * time.Second
|
||||
infoIdleTimeout = 60 * time.Second
|
||||
infoMaxHeaderBytes = 64 * 1024
|
||||
)
|
||||
|
||||
// The read deadlines are variables so a test can shorten them. infoReadTimeout bounds
|
||||
// the whole request, not only its headers: a request is a GET with a query string and
|
||||
// the handlers never read a body, but net/http drains an unread body after the handler
|
||||
// returns, and without a deadline on that read a client sending a body a byte at a time
|
||||
// would hold its connection slot for as long as it liked, and sixty-four of them would
|
||||
// hold every slot. A body is refused as well, see refuseBody, but net/http drains it
|
||||
// before it closes, so this deadline is what ends a client that announced a body and
|
||||
// never sent it.
|
||||
var (
|
||||
infoReadHeaderTimeout = 10 * time.Second
|
||||
infoReadTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
// servedOnInfo decides what the info API will run: the commands that report identity
|
||||
// and nothing else, which the commands declare about themselves. Filter adds help to
|
||||
// the result, so a client can ask what is served; help on a filtered registry describes
|
||||
// only that registry.
|
||||
func servedOnInfo(c *commands.Command) bool {
|
||||
return c.Identity
|
||||
}
|
||||
|
||||
// notServedOnInfo explains a refusal, naming the surfaces that will run the command.
|
||||
const notServedOnInfo = "the info API serves identity lookups only; the ssh debug server and nebula ctl serve the rest"
|
||||
|
||||
// InfoServer serves the identity commands over HTTP, on a socket an operator may open to
|
||||
// other users on the host.
|
||||
//
|
||||
// It is the second local API, and the opposite of the control socket in who it is for.
|
||||
// The control socket is for the user who runs nebula, serves nearly everything and needs
|
||||
// no configuration. This one is for every other program on the machine, a web server
|
||||
// that wants to know who is on the other end of a connection arriving over the overlay,
|
||||
// say, and it is off until an operator names a socket and a mode for it. What it serves
|
||||
// is decided by the commands themselves, Command.Identity: the identity a certificate
|
||||
// asserts and nothing operational, so opening it to a group of services, or to everyone
|
||||
// on the host, gives away nothing the overlay did not already tell them.
|
||||
//
|
||||
// HTTP, so that no client library is needed. GET /v1/<command>?<flag>=<value> runs a
|
||||
// command with its options as the query string and answers with the command's JSON, the
|
||||
// same value the control socket and -json produce. GET /v1 describes what is served. A
|
||||
// refusal is a 4xx with {"error": reason}: 404 when the command said the thing asked
|
||||
// about does not exist (commands.NotFound), 400 for a parameter or an argument the
|
||||
// command would not take, 403 for a command this surface withholds.
|
||||
type InfoServer struct {
|
||||
endpoint
|
||||
|
||||
// reg is the identity commands this surface serves, filtered from the daemon's
|
||||
// registry when the server was built.
|
||||
reg *commands.Registry
|
||||
}
|
||||
|
||||
// NewInfoServer returns an InfoServer that serves the identity commands in reg. reg is
|
||||
// complete when it arrives: nebula registers every command before it wires its local
|
||||
// APIs, and nothing registers one later, so the filter is taken once here rather than
|
||||
// kept up to date against the source.
|
||||
func NewInfoServer(l *slog.Logger, reg *commands.Registry) *InfoServer {
|
||||
return &InfoServer{
|
||||
endpoint: endpoint{l: l, name: "local info API"},
|
||||
reg: reg.Filter(servedOnInfo, notServedOnInfo),
|
||||
}
|
||||
}
|
||||
|
||||
// Rebind brings the server up at path with mode, moves it there, or, when it is already
|
||||
// there, applies a changed mode; endpoint.rebindLocked says what that promises. It is
|
||||
// the one way the server comes up, so Wire's reload callback and its first attempt are
|
||||
// the same call.
|
||||
func (s *InfoServer) Rebind(ctx context.Context, path string, acc Access) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return s.rebindLocked(ctx, path, acc, func(ln net.Listener) io.Closer {
|
||||
srv := &http.Server{
|
||||
Handler: s.handler(),
|
||||
ReadHeaderTimeout: infoReadHeaderTimeout,
|
||||
ReadTimeout: infoReadTimeout,
|
||||
WriteTimeout: infoWriteTimeout,
|
||||
IdleTimeout: infoIdleTimeout,
|
||||
MaxHeaderBytes: infoMaxHeaderBytes,
|
||||
ErrorLog: slog.NewLogLogger(s.l.Handler(), slog.LevelDebug),
|
||||
}
|
||||
|
||||
s.l.Info("Local info API listening", "path", path, "access", acc.String())
|
||||
if w := unprotectedNameWarning(path); w != "" {
|
||||
s.l.Warn("Local info API is served on a pipe name that is not protected", "path", path, "risk", w)
|
||||
}
|
||||
go s.serve(srv, ln)
|
||||
|
||||
// Closing the server closes the listener Serve was handed, and a Serve that has
|
||||
// not started yet closes it on its way out, so the node is never left bound by a
|
||||
// listener nothing is accepting from. Requests in flight are cut off rather than
|
||||
// waited for: a reload must not hang on a slow client, and the answer is a lookup
|
||||
// the client can simply repeat.
|
||||
return srv
|
||||
})
|
||||
}
|
||||
|
||||
// serve runs the HTTP server on ln until it is closed. Only an error other than the
|
||||
// close is worth a line: Stop and Rebind are the two things that close it.
|
||||
func (s *InfoServer) serve(srv *http.Server, ln net.Listener) {
|
||||
err := srv.Serve(netutil.LimitListener(ln, infoMaxConns))
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, net.ErrClosed) {
|
||||
s.l.Error("Local info API stopped serving", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handler builds the routes. Every answer is JSON, the misses included, so a client
|
||||
// never has to parse net/http's text for a path or method it did not expect. That
|
||||
// includes a path ServeMux would clean and redirect, /v1/../v1/x or //v1/x, which is
|
||||
// refused outright: nothing legitimate sends one, and a redirect is one more thing a
|
||||
// client would have to follow.
|
||||
func (s *InfoServer) handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /v1", s.handleDescribe)
|
||||
mux.HandleFunc("GET /v1/{command}", s.handleCommand)
|
||||
mux.HandleFunc("/v1", methodNotAllowed)
|
||||
mux.HandleFunc("/v1/{command}", methodNotAllowed)
|
||||
mux.HandleFunc("/", notFoundRoute)
|
||||
return s.recovering(refuseBody(mux))
|
||||
}
|
||||
|
||||
// refuseBody answers a request that carries a body with 400, before any handler sees
|
||||
// it, and has the connection closed after the reply rather than kept for another
|
||||
// request. Nothing here reads a body; one is a mistake, and the client is told what to
|
||||
// do instead. net/http still drains what the body it announced it would send, up to the
|
||||
// read deadline, so the deadline is what bounds a client that never sends it.
|
||||
func refuseBody(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.ContentLength != 0 || len(r.TransferEncoding) > 0 {
|
||||
w.Header().Set("Connection", "close")
|
||||
writeJSONError(w, http.StatusBadRequest, "the info API takes no request body; put the command's parameters in the query string")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// recovering turns a panic in a command into a 500 and a log line rather than a dropped
|
||||
// connection, which is all net/http would offer, and keeps the daemon up, which is what
|
||||
// matters: this surface is reachable by whoever the operator opened it to. The handlers
|
||||
// produce their whole answer before writing any of it, so a panic in Run always finds
|
||||
// the response unwritten.
|
||||
func (s *InfoServer) recovering(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
s.l.Error("Recovered from panic serving a local info API request",
|
||||
"panic", rec,
|
||||
"path", r.URL.Path,
|
||||
"query", r.URL.RawQuery,
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
writeJSONError(w, http.StatusInternalServerError, "command failed")
|
||||
}
|
||||
}()
|
||||
|
||||
if path.Clean(r.URL.Path) != r.URL.Path {
|
||||
notFoundRoute(w, r)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// handleDescribe answers GET /v1 with the schema of every command served here, the same
|
||||
// document the control socket's describe returns for its own surface.
|
||||
func (s *InfoServer) handleDescribe(w http.ResponseWriter, _ *http.Request) {
|
||||
body, err := json.Marshal(s.reg.Schema())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, body)
|
||||
}
|
||||
|
||||
// handleCommand answers GET /v1/<command>: the query string carries the command's
|
||||
// parameters, and the response body is the command's JSON. A request body is never
|
||||
// read. It is the control socket's serve with HTTP's vocabulary for the outcomes.
|
||||
func (s *InfoServer) handleCommand(w http.ResponseWriter, r *http.Request) {
|
||||
name := commands.Name(r.PathValue("command"))
|
||||
|
||||
reg := s.reg
|
||||
cmd, err := reg.Resolve(name)
|
||||
if err != nil {
|
||||
// A command this surface withholds is a different answer from one that does not
|
||||
// exist, and Resolve says which; only the status is picked here.
|
||||
status := http.StatusNotFound
|
||||
var withheld *commands.WithheldError
|
||||
if errors.As(err, &withheld) {
|
||||
status = http.StatusForbidden
|
||||
}
|
||||
writeJSONError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Parsed strictly: the lenient parser on the request drops a pair it cannot decode
|
||||
// and keeps the rest, and a request that lost its address would be answered as one
|
||||
// that never had it, which for print-cert is this node's own certificate.
|
||||
q, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "malformed query string: "+err.Error())
|
||||
return
|
||||
}
|
||||
params, format, err := queryParams(q, reg.SchemaFor(cmd))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
res, err := commands.Invoke(commands.Request{Command: cmd, Params: params})
|
||||
if err != nil {
|
||||
var pe *commands.ParamError
|
||||
if errors.As(err, &pe) {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Run failed. The sentence is for the operator's log; the caller, who may be
|
||||
// anyone the operator admitted, is told that it failed and no more.
|
||||
s.l.Warn("Local info API command failed", "command", name, "error", err)
|
||||
writeJSONError(w, http.StatusInternalServerError, "command failed")
|
||||
return
|
||||
}
|
||||
|
||||
// A command that acts does so before this surface's one reply, whose body is the
|
||||
// outcome; see Command.Then.
|
||||
if cmd.Then != nil && res.OK {
|
||||
res = cmd.Then()
|
||||
}
|
||||
|
||||
// A refusal is answered before an empty Result is: the zero Result is a refusal with
|
||||
// nothing to say, which exits 1 over ssh and must not read as success here. One with
|
||||
// no reason is the command's fault, as a Run error is, and is answered the same way.
|
||||
if !res.OK {
|
||||
if res.Reason == "" {
|
||||
s.l.Warn("Local info API command refused without a reason", "command", name)
|
||||
writeJSONError(w, http.StatusInternalServerError, "command failed")
|
||||
return
|
||||
}
|
||||
status := http.StatusBadRequest
|
||||
if res.NotFound {
|
||||
status = http.StatusNotFound
|
||||
}
|
||||
writeJSONError(w, status, res.Reason)
|
||||
return
|
||||
}
|
||||
|
||||
if res.Empty() {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
// The same rendering function every surface uses, so the value here is byte for
|
||||
// byte what -json prints at an ssh prompt.
|
||||
buf := &bytes.Buffer{}
|
||||
if err := commands.Render(cmd, res, format, buf); err != nil {
|
||||
s.l.Warn("Local info API could not render a result", "command", name, "error", err)
|
||||
writeJSONError(w, http.StatusInternalServerError, "command failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, buf.Bytes())
|
||||
}
|
||||
|
||||
// queryParams reads a query string as a command's parameters. Each key is a flag of the
|
||||
// command, by name, in the form the control socket takes them; one given twice is
|
||||
// refused rather than silently picking either. The presentation flags are read as a
|
||||
// command line reads them, and set apart: the answer is JSON regardless, and pretty
|
||||
// indents it.
|
||||
func queryParams(q url.Values, schema commands.CommandSchema) (map[string]string, commands.Format, error) {
|
||||
var params, presentation map[string]string
|
||||
for _, k := range slices.Sorted(maps.Keys(q)) {
|
||||
vs := q[k]
|
||||
if len(vs) > 1 {
|
||||
return nil, commands.FormatUnset, fmt.Errorf("parameter %q was given more than once", k)
|
||||
}
|
||||
|
||||
into := ¶ms
|
||||
if k == commands.FlagJSON || k == commands.FlagPretty {
|
||||
into = &presentation
|
||||
}
|
||||
if *into == nil {
|
||||
*into = map[string]string{}
|
||||
}
|
||||
v := vs[0]
|
||||
// ?raw is ?raw=true, as -raw is -raw=true on a command line.
|
||||
if v == "" && isBoolParam(schema, k) {
|
||||
v = "true"
|
||||
}
|
||||
(*into)[k] = v
|
||||
}
|
||||
|
||||
format, err := commands.PresentationFormat(presentation)
|
||||
if err != nil {
|
||||
return nil, commands.FormatUnset, err
|
||||
}
|
||||
if format == commands.FormatUnset {
|
||||
format = commands.FormatJSON
|
||||
}
|
||||
|
||||
return params, format, nil
|
||||
}
|
||||
|
||||
// isBoolParam reports whether name is one of the command's boolean flags.
|
||||
func isBoolParam(schema commands.CommandSchema, name string) bool {
|
||||
for _, f := range schema.Flags {
|
||||
if f.Name == name {
|
||||
return f.Bool
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Allow", http.MethodGet)
|
||||
writeJSONError(w, http.StatusMethodNotAllowed, fmt.Sprintf("%s is not allowed; the info API is read only, use GET", r.Method))
|
||||
}
|
||||
|
||||
func notFoundRoute(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusNotFound, fmt.Sprintf("no such path %s; GET /v1 lists the commands and GET /v1/<command> runs one", r.URL.Path))
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body []byte) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, msg string) {
|
||||
body, _ := json.Marshal(map[string]string{"error": msg})
|
||||
writeJSON(w, status, append(body, '\n'))
|
||||
}
|
||||
|
||||
// infoConfig is the info API section of a config, read and checked.
|
||||
type infoConfig struct {
|
||||
Enabled bool
|
||||
Path string
|
||||
Access Access
|
||||
}
|
||||
|
||||
// infoConfigFrom reads the info API section. A disabled section needs nothing else to be
|
||||
// right; an enabled one needs a socket path, a group that exists if it names one, and
|
||||
// a mode that parses if it names one. A group with no mode means groupSocketMode, and a
|
||||
// mode that gives a named group nothing is refused: it would be a group that cannot
|
||||
// connect, which is not what naming one asks for.
|
||||
func infoConfigFrom(c *config.C) (infoConfig, error) {
|
||||
cfg := infoConfig{Enabled: c.GetBool(InfoEnabledKey, false)}
|
||||
if !cfg.Enabled {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
p := c.GetString(InfoSocketKey, "")
|
||||
if p == "" {
|
||||
return cfg, fmt.Errorf("%s is true but %s is not set; the info API needs a socket path", InfoEnabledKey, InfoSocketKey)
|
||||
}
|
||||
if err := checkSocketPath(InfoSocketKey, p); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.Path = p
|
||||
|
||||
group, err := groupFromConfig(c, InfoGroupKey)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
// With neither a mode nor a group named, the daemon's user alone, so that enabling
|
||||
// the API does not open it to anyone until the operator says who.
|
||||
def := ownerOnlyMode
|
||||
if group.ID != "" {
|
||||
def = groupSocketMode
|
||||
}
|
||||
|
||||
mode, err := parseSocketMode(c.Get(InfoModeKey), def)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("%s: %w", InfoModeKey, err)
|
||||
}
|
||||
// On unix the mode is what admits the group, so one that shuts it out is a config
|
||||
// error; on windows the group is an entry in the pipe's security descriptor and the
|
||||
// mode means nothing to a pipe, so it is not held against the group there.
|
||||
if runtime.GOOS != "windows" && group.ID != "" && mode&0070 == 0 {
|
||||
return cfg, fmt.Errorf("%s %s gives group %s no access to the socket; use \"%04o\" or leave the mode unset", InfoModeKey, modeString(mode), group.Name, mode|0060)
|
||||
}
|
||||
cfg.Access = Access{Mode: mode, Group: group}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// parseSocketMode reads an octal mode written as a string. A bare 0660 in yaml is an
|
||||
// integer, and which integer depends on the parser (octal 432 under YAML 1.1, decimal
|
||||
// 660 under 1.2), so a number is refused with the fix rather than quietly applied as
|
||||
// whichever mode its digits happen to spell in octal.
|
||||
func parseSocketMode(raw any, def os.FileMode) (os.FileMode, error) {
|
||||
switch v := raw.(type) {
|
||||
case nil:
|
||||
return def, nil
|
||||
case string:
|
||||
mode, err := strconv.ParseUint(v, 8, 32)
|
||||
if err != nil || mode&^0777 != 0 {
|
||||
return 0, fmt.Errorf("%q is not an octal file mode such as \"0660\"", v)
|
||||
}
|
||||
return os.FileMode(mode), nil
|
||||
default:
|
||||
return 0, fmt.Errorf("must be a quoted octal string such as \"0660\", not the number %v; yaml reads a bare mode as a decimal or octal integer depending on the parser", v)
|
||||
}
|
||||
}
|
||||
@@ -1,432 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type whoamiFlags struct {
|
||||
Name string
|
||||
Shout bool
|
||||
}
|
||||
|
||||
// infoRegistry holds one identity command, whoami, whose -name selects an outcome, and
|
||||
// one command the info API must withhold.
|
||||
func infoRegistry() *commands.Registry {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "whoami",
|
||||
ShortDescription: "reports who a name belongs to",
|
||||
Identity: true,
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := &whoamiFlags{}
|
||||
fl.StringVar(&s.Name, "name", "", "the name to look up")
|
||||
fl.BoolVar(&s.Shout, "shout", false, "answers in capitals")
|
||||
return fl, s
|
||||
},
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
if f := fs.(*whoamiFlags); f.Shout {
|
||||
return commands.Value(map[string]any{"name": strings.ToUpper(f.Name)}), nil
|
||||
}
|
||||
switch name := fs.(*whoamiFlags).Name; name {
|
||||
case "":
|
||||
return commands.Value(map[string]any{"name": "me", "groups": []string{}}), nil
|
||||
case "nobody":
|
||||
return commands.NotFound("No active tunnel for vpn addr: %s", name), nil
|
||||
case "bad":
|
||||
return commands.Failed("The provided vpn addr could not be parsed: %s", name), nil
|
||||
case "boom":
|
||||
panic("this command is broken")
|
||||
case "err":
|
||||
return commands.Result{}, errors.New("an internal detail")
|
||||
case "silent":
|
||||
return commands.Result{}, nil
|
||||
case "done":
|
||||
return commands.Nothing(), nil
|
||||
default:
|
||||
return commands.Value(map[string]any{"name": name}), nil
|
||||
}
|
||||
},
|
||||
})
|
||||
reg.Register(echoCommand())
|
||||
return reg
|
||||
}
|
||||
|
||||
func serveInfo(t *testing.T, reg *commands.Registry, mode os.FileMode) (*InfoServer, string) {
|
||||
t.Helper()
|
||||
|
||||
path := testSocket(t)
|
||||
s := NewInfoServer(test.NewLogger(), reg)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: mode}))
|
||||
t.Cleanup(s.Stop)
|
||||
return s, path
|
||||
}
|
||||
|
||||
// httpDo sends one request over the socket at path and returns the status, body and
|
||||
// headers. The host in the URL is a placeholder: the dialer ignores it.
|
||||
func TestInfoServesIdentityCommands(t *testing.T) {
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
status, body, hdr := test.HTTPDo(t, path, http.MethodGet, "/v1/whoami?name=alice")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.JSONEq(t, `{"name":"alice"}`, body)
|
||||
assert.Equal(t, "application/json", hdr.Get("Content-Type"))
|
||||
|
||||
status, body = test.HTTPGet(t, path, "/v1/whoami")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.JSONEq(t, `{"name":"me","groups":[]}`, body, "a parameter left out is the command's default")
|
||||
}
|
||||
|
||||
// TestInfoWithholdsTheRest checks the filter at the wire: a command that exists but is
|
||||
// not an identity command is refused with the reason, and a name nothing is registered
|
||||
// under is unknown, so a caller can tell a typo from a closed door.
|
||||
func TestInfoWithholdsTheRest(t *testing.T) {
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
status, body := test.HTTPGet(t, path, "/v1/echo?x=1")
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
assert.Contains(t, body, "echo is not available on this surface")
|
||||
assert.Contains(t, body, "identity lookups only")
|
||||
|
||||
status, body = test.HTTPGet(t, path, "/v1/nope")
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
assert.Contains(t, body, `unknown command \"nope\"`)
|
||||
|
||||
for _, target := range []string{"/", "/v2/whoami", "/v1/", "/v1/whoami/extra", "//v1/whoami", "/v1/x/../whoami", "/v1/../v1/whoami"} {
|
||||
status, body = test.HTTPGet(t, path, target)
|
||||
assert.Equal(t, http.StatusNotFound, status, target)
|
||||
assert.Contains(t, body, `"error"`, "%s: misses are JSON too", target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInfoStatusCodes(t *testing.T) {
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
for _, tc := range []struct {
|
||||
target string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"/v1/whoami?name=nobody", http.StatusNotFound, `{"error":"No active tunnel for vpn addr: nobody"}`},
|
||||
{"/v1/whoami?name=bad", http.StatusBadRequest, `{"error":"The provided vpn addr could not be parsed: bad"}`},
|
||||
{"/v1/whoami?nope=1", http.StatusBadRequest, `{"error":"whoami has no parameter \"nope\""}`},
|
||||
{"/v1/whoami?name=a&name=b", http.StatusBadRequest, `{"error":"parameter \"name\" was given more than once"}`},
|
||||
{"/v1/whoami?pretty=maybe", http.StatusBadRequest, `{"error":"pretty: expected a boolean, got \"maybe\""}`},
|
||||
// A pair that does not decode is a malformed request, not a request without
|
||||
// the pair: the lenient parser would drop it and keep the rest.
|
||||
{"/v1/whoami?name=%zz", http.StatusBadRequest, `{"error":"malformed query string: invalid URL escape \"%zz\""}`},
|
||||
{"/v1/whoami?name=a;shout", http.StatusBadRequest, `{"error":"malformed query string: invalid semicolon separator in query"}`},
|
||||
// A boolean parameter with no value is set, as -shout is on a command line.
|
||||
{"/v1/whoami?name=alice&shout", http.StatusOK, `{"name":"ALICE"}`},
|
||||
{"/v1/whoami?name=alice&shout=false", http.StatusOK, `{"name":"alice"}`},
|
||||
// Run failed: the caller hears that it did and no more; the detail is for the log.
|
||||
{"/v1/whoami?name=err", http.StatusInternalServerError, `{"error":"command failed"}`},
|
||||
// A refusal with no reason, the zero Result, fails the same way rather than
|
||||
// passing as a success with nothing to say.
|
||||
{"/v1/whoami?name=silent", http.StatusInternalServerError, `{"error":"command failed"}`},
|
||||
} {
|
||||
status, body := test.HTTPGet(t, path, tc.target)
|
||||
assert.Equal(t, tc.status, status, tc.target)
|
||||
assert.JSONEq(t, tc.body, body, tc.target)
|
||||
}
|
||||
|
||||
// A success with nothing to say is the one empty reply.
|
||||
status, body := test.HTTPGet(t, path, "/v1/whoami?name=done")
|
||||
assert.Equal(t, http.StatusNoContent, status)
|
||||
assert.Empty(t, body)
|
||||
|
||||
status, body, hdr := test.HTTPDo(t, path, http.MethodPost, "/v1/whoami?name=alice")
|
||||
assert.Equal(t, http.StatusMethodNotAllowed, status)
|
||||
assert.Equal(t, http.MethodGet, hdr.Get("Allow"))
|
||||
assert.Contains(t, body, "read only")
|
||||
|
||||
status, _, _ = test.HTTPDo(t, path, http.MethodDelete, "/v1")
|
||||
assert.Equal(t, http.StatusMethodNotAllowed, status)
|
||||
}
|
||||
|
||||
// TestInfoPanicDoesNotKillTheDaemon: a broken command costs a request, not the overlay.
|
||||
// This surface may be open to anyone on the host, so that holds against them too.
|
||||
func TestInfoPanicDoesNotKillTheDaemon(t *testing.T) {
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
status, body := test.HTTPGet(t, path, "/v1/whoami?name=boom")
|
||||
assert.Equal(t, http.StatusInternalServerError, status)
|
||||
assert.JSONEq(t, `{"error":"command failed"}`, body)
|
||||
|
||||
status, body = test.HTTPGet(t, path, "/v1/whoami?name=alice")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.JSONEq(t, `{"name":"alice"}`, body)
|
||||
}
|
||||
|
||||
func TestInfoDescribe(t *testing.T) {
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
status, body := test.HTTPGet(t, path, "/v1")
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
|
||||
var schema []commands.CommandSchema
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &schema))
|
||||
|
||||
var names []commands.Name
|
||||
flags := map[commands.Name][]string{}
|
||||
for _, c := range schema {
|
||||
names = append(names, c.Name)
|
||||
for _, f := range c.Flags {
|
||||
flags[c.Name] = append(flags[c.Name], f.Name)
|
||||
}
|
||||
}
|
||||
assert.ElementsMatch(t, []commands.Name{"help", "whoami"}, names, "only what is served is described")
|
||||
assert.Equal(t, []string{"name", "shout", commands.FlagJSON, commands.FlagPretty}, flags["whoami"])
|
||||
}
|
||||
|
||||
// TestInfoPresentationFlags: the query string takes -json and -pretty as a command line
|
||||
// would. The answer is JSON either way; pretty indents it.
|
||||
func TestInfoPresentationFlags(t *testing.T) {
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
_, compact := test.HTTPGet(t, path, "/v1/whoami?name=alice&json=true")
|
||||
//nolint:testifylint // the exact bytes, newline included, are what is under test
|
||||
assert.Equal(t, "{\"name\":\"alice\"}\n", compact)
|
||||
|
||||
_, pretty := test.HTTPGet(t, path, "/v1/whoami?name=alice&pretty")
|
||||
//nolint:testifylint // the layout is what is under test
|
||||
assert.Equal(t, "{\n \"name\": \"alice\"\n}\n", pretty)
|
||||
|
||||
_, off := test.HTTPGet(t, path, "/v1/whoami?name=alice&pretty=false")
|
||||
assert.Equal(t, compact, off)
|
||||
}
|
||||
|
||||
// TestInfoModeChangeRefusesASwappedSocket: whoever can write the directory can replace
|
||||
// the node with a link to a file of their choosing; the daemon must not set the
|
||||
// operator's mode on that file. The node is seen to be gone, the link is refused by the
|
||||
// stale check, the file is untouched, and the endpoint reports itself down, since
|
||||
// nothing of ours is reachable at the path.
|
||||
func TestInfoModeChangeRefusesASwappedSocket(t *testing.T) {
|
||||
s, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
target := filepath.Join(filepath.Dir(path), "target")
|
||||
require.NoError(t, os.WriteFile(target, nil, 0600))
|
||||
require.NoError(t, os.Remove(path))
|
||||
require.NoError(t, os.Symlink(target, path))
|
||||
|
||||
err := s.Rebind(context.Background(), path, Access{Mode: 0666})
|
||||
require.ErrorContains(t, err, "is not a socket")
|
||||
fi, err := os.Stat(target)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0600), fi.Mode().Perm(), "the file behind the link keeps its mode")
|
||||
assert.Empty(t, s.Path(), "nothing of ours answers at the path, so nothing is served")
|
||||
}
|
||||
|
||||
func TestInfoConfig(t *testing.T) {
|
||||
load := func(t *testing.T, yaml string) (infoConfig, error) {
|
||||
t.Helper()
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(yaml))
|
||||
return infoConfigFrom(c)
|
||||
}
|
||||
|
||||
cfg, err := load(t, "local_api: {}\n")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, cfg.Enabled)
|
||||
|
||||
cfg, err = load(t, "local_api:\n info:\n socket: /run/nebula/info.sock\n")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, cfg.Enabled, "a socket alone does not enable it")
|
||||
|
||||
_, err = load(t, "local_api:\n info:\n enabled: true\n")
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "needs a socket path")
|
||||
|
||||
cfg, err = load(t, "local_api:\n info:\n enabled: true\n socket: /run/nebula/info.sock\n")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, infoConfig{Enabled: true, Path: "/run/nebula/info.sock", Access: Access{Mode: 0600}}, cfg)
|
||||
|
||||
cfg, err = load(t, "local_api:\n info:\n enabled: true\n socket: /run/nebula/info.sock\n socket_mode: \"0660\"\n")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, infoConfig{Enabled: true, Path: "/run/nebula/info.sock", Access: Access{Mode: 0660}}, cfg)
|
||||
|
||||
_, err = load(t, "local_api:\n info:\n enabled: true\n socket: run/info.sock\n")
|
||||
require.Error(t, err, "a relative socket path is refused rather than resolved against anything")
|
||||
require.ErrorContains(t, err, "must be an absolute path")
|
||||
require.ErrorContains(t, err, InfoSocketKey)
|
||||
|
||||
_, err = load(t, "local_api:\n info:\n enabled: true\n socket: /run/nebula/info.sock\n socket_mode: 0660\n")
|
||||
require.Error(t, err, "a bare number is whichever integer the yaml parser made of it")
|
||||
require.ErrorContains(t, err, "quoted octal string")
|
||||
|
||||
for _, bad := range []string{`"abc"`, `"1777"`, `"08"`} {
|
||||
_, err = load(t, "local_api:\n info:\n enabled: true\n socket: /run/nebula/info.sock\n socket_mode: "+bad+"\n")
|
||||
require.Error(t, err, bad)
|
||||
require.ErrorContains(t, err, "not an octal file mode", bad)
|
||||
}
|
||||
|
||||
_, err = load(t, fmt.Sprintf("local_api:\n info:\n enabled: true\n socket: /%s\n", strings.Repeat("x", sunPathMax)))
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "too long")
|
||||
}
|
||||
|
||||
// TestWireInfoFollowsConfig: off by default, up when enabled, down when disabled, and
|
||||
// never on the control socket's path.
|
||||
func TestWireInfoFollowsConfig(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
ctlPath := testSocket(t)
|
||||
infoPath := testSocket(t)
|
||||
section := func(enabled bool, socket string) string {
|
||||
return fmt.Sprintf("local_api:\n control:\n socket: %s\n info:\n enabled: %t\n socket: %s\n", ctlPath, enabled, socket)
|
||||
}
|
||||
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(section(false, infoPath)))
|
||||
|
||||
var logs lockedBuffer
|
||||
eps := Wire(ctx, test.NewLoggerWithOutput(&logs), c, infoRegistry())
|
||||
t.Cleanup(eps.Stop)
|
||||
assert.Equal(t, ctlPath, eps.Control.Path())
|
||||
assert.Empty(t, eps.Info.Path(), "off until enabled")
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(section(true, infoPath)).Err)
|
||||
assert.Equal(t, infoPath, eps.Info.Path())
|
||||
status, body := test.HTTPGet(t, infoPath, "/v1/whoami?name=alice")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.JSONEq(t, `{"name":"alice"}`, body)
|
||||
|
||||
// A reload that changes nothing leaves it where it is.
|
||||
require.NoError(t, c.ReloadConfigString(section(true, infoPath)).Err)
|
||||
assert.Equal(t, infoPath, eps.Info.Path())
|
||||
|
||||
// A reload that moves the socket moves it, and removes the old one.
|
||||
moved := testSocket(t)
|
||||
require.NoError(t, c.ReloadConfigString(section(true, moved)).Err)
|
||||
assert.Equal(t, moved, eps.Info.Path())
|
||||
_, err := os.Stat(infoPath)
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
status, body = test.HTTPGet(t, moved, "/v1/whoami?name=bob")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.JSONEq(t, `{"name":"bob"}`, body)
|
||||
require.NoError(t, c.ReloadConfigString(section(true, infoPath)).Err)
|
||||
require.Equal(t, infoPath, eps.Info.Path())
|
||||
|
||||
// The control socket's path is refused, and the running endpoint is kept, which is
|
||||
// what the log says.
|
||||
require.NoError(t, c.ReloadConfigString(section(true, ctlPath)).Err)
|
||||
assert.Equal(t, infoPath, eps.Info.Path())
|
||||
assert.Equal(t, ctlPath, eps.Control.Path())
|
||||
assert.Contains(t, logs.String(), "keeping the current endpoint")
|
||||
assert.NotContains(t, logs.String(), "Local info API is not available")
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(section(false, infoPath)).Err)
|
||||
assert.Empty(t, eps.Info.Path())
|
||||
_, err = os.Stat(infoPath)
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
|
||||
// One Stop takes both down.
|
||||
require.NoError(t, c.ReloadConfigString(section(true, infoPath)).Err)
|
||||
eps.Stop()
|
||||
assert.Empty(t, eps.Info.Path())
|
||||
assert.Empty(t, eps.Control.Path())
|
||||
}
|
||||
|
||||
// TestWireInfoKeepsRunningOnABadReload: a typo in the section must not cut off the
|
||||
// programs relying on the endpoint; the operator is told and the endpoint stays.
|
||||
func TestWireInfoKeepsRunningOnABadReload(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
infoPath := testSocket(t)
|
||||
good := fmt.Sprintf("local_api:\n info:\n enabled: true\n socket: %s\n", infoPath)
|
||||
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(good))
|
||||
|
||||
srv := wireInfo(ctx, test.NewLogger(), c, infoRegistry())
|
||||
t.Cleanup(srv.Stop)
|
||||
require.Equal(t, infoPath, srv.Path())
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(good+" socket_mode: 0660\n").Err)
|
||||
assert.Equal(t, infoPath, srv.Path())
|
||||
status, _ := test.HTTPGet(t, infoPath, "/v1/whoami")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
}
|
||||
|
||||
// rawInfoRequest opens the socket and writes req as it is, so a test can send what an
|
||||
// HTTP client would not: a body that never arrives. It returns the connection.
|
||||
func rawInfoRequest(t *testing.T, path, req string) net.Conn {
|
||||
t.Helper()
|
||||
conn, err := net.DialTimeout("unix", path, time.Second)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
_, err = conn.Write([]byte(req))
|
||||
require.NoError(t, err)
|
||||
return conn
|
||||
}
|
||||
|
||||
// TestInfoRefusesARequestBody: a request that announces a body is answered 400 at once,
|
||||
// before the body arrives, and the connection is closed once the read deadline has ended
|
||||
// the wait for it, so a client that never sends the body holds its slot for the deadline
|
||||
// and no longer.
|
||||
func TestInfoRefusesARequestBody(t *testing.T) {
|
||||
oldHeader, oldRead := infoReadHeaderTimeout, infoReadTimeout
|
||||
infoReadHeaderTimeout, infoReadTimeout = 200*time.Millisecond, 300*time.Millisecond
|
||||
t.Cleanup(func() { infoReadHeaderTimeout, infoReadTimeout = oldHeader, oldRead })
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
start := time.Now()
|
||||
conn := rawInfoRequest(t, path, "GET /v1/whoami HTTP/1.1\r\nHost: nebula\r\nContent-Length: 10\r\n\r\n")
|
||||
require.NoError(t, conn.SetReadDeadline(time.Now().Add(2*time.Second)))
|
||||
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
require.NoError(t, err)
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
assert.Equal(t, http.StatusBadRequest, res.StatusCode)
|
||||
assert.Contains(t, string(body), "takes no request body")
|
||||
assert.True(t, res.Close, "the connection is not kept for another request")
|
||||
assert.Less(t, time.Since(start), 200*time.Millisecond, "answered before the body, which never comes")
|
||||
|
||||
_, err = conn.Read(make([]byte, 1))
|
||||
require.ErrorIs(t, err, io.EOF, "the server closed the connection")
|
||||
assert.Less(t, time.Since(start), time.Second, "and did so at the read deadline, not later")
|
||||
}
|
||||
|
||||
// TestInfoDropsASlowClient: a client that sends its headers and then nothing loses its
|
||||
// connection at the read timeout rather than holding a slot for as long as it likes.
|
||||
func TestInfoDropsASlowClient(t *testing.T) {
|
||||
oldHeader, oldRead := infoReadHeaderTimeout, infoReadTimeout
|
||||
infoReadHeaderTimeout, infoReadTimeout = 200*time.Millisecond, 300*time.Millisecond
|
||||
t.Cleanup(func() { infoReadHeaderTimeout, infoReadTimeout = oldHeader, oldRead })
|
||||
_, path := serveInfo(t, infoRegistry(), 0600)
|
||||
|
||||
// Half a request line, then silence: the header deadline ends it.
|
||||
conn := rawInfoRequest(t, path, "GET /v1/whoami HTTP/1.1\r\nHost: neb")
|
||||
require.NoError(t, conn.SetReadDeadline(time.Now().Add(2*time.Second)))
|
||||
start := time.Now()
|
||||
_, err := conn.Read(make([]byte, 1))
|
||||
require.Error(t, err, "the server closed the connection")
|
||||
assert.Less(t, time.Since(start), time.Second)
|
||||
|
||||
// And the server still answers the next client.
|
||||
status, _ := test.HTTPGet(t, path, "/v1/whoami")
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Microsoft/go-winio"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// TestInfoIsServedOnAPipe: the info API serves HTTP on a named pipe, whose security
|
||||
// descriptor is its access control the way a socket's mode is on unix; a group named
|
||||
// in the config is admitted by it.
|
||||
func TestInfoIsServedOnAPipe(t *testing.T) {
|
||||
users, err := windows.CreateWellKnownSid(windows.WinBuiltinUsersSid)
|
||||
require.NoError(t, err)
|
||||
group := Group{Name: "Users", ID: users.String()}
|
||||
|
||||
s := NewInfoServer(test.NewLogger(), commands.New())
|
||||
path := pipePrefix + "nebula-info-test"
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: groupSocketMode, Group: group}))
|
||||
t.Cleanup(s.Stop)
|
||||
assert.Equal(t, path, s.Path())
|
||||
|
||||
client := &http.Client{Transport: &http.Transport{
|
||||
// What a program on the host has to do: ask for the data rights alone, since the
|
||||
// group is granted no more; see pipeClientAccess.
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
return winio.DialPipeAccess(ctx, path, pipeClientAccess)
|
||||
},
|
||||
}}
|
||||
res, err := client.Get("http://nebula/v1")
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(res.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, res.StatusCode)
|
||||
assert.Contains(t, string(body), `"help"`)
|
||||
|
||||
// A change of group means a new pipe under the same name, still serving.
|
||||
require.NoError(t, s.Rebind(context.Background(), path, Access{Mode: groupSocketMode}))
|
||||
res, err = client.Get("http://nebula/v1")
|
||||
require.NoError(t, err)
|
||||
res.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, res.StatusCode)
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package localapi
|
||||
|
||||
// DirName is the directory under /var/run that holds nebula's sockets by default.
|
||||
const DirName = "nebula"
|
||||
|
||||
// CtlEnabledKey is the optional config key that turns the control socket off. It is on
|
||||
// unless the config says false, and reloadable: a reload that turns it off removes the
|
||||
// socket, and one that turns it back on brings it up again.
|
||||
const CtlEnabledKey = "local_api.control.enabled"
|
||||
|
||||
// ControlEnabled reports whether a config leaves the control socket on. nebula ctl reads
|
||||
// it too, so a client pointed at a config that turned the socket off says so rather than
|
||||
// failing to dial.
|
||||
func ControlEnabled(c interface{ GetBool(string, bool) bool }) bool {
|
||||
return c.GetBool(CtlEnabledKey, true)
|
||||
}
|
||||
|
||||
// CtlSocketKey is the optional config key naming the control socket. Unset, the socket
|
||||
// is DefaultSocketPath, one fixed path per platform that both the daemon and nebula ctl
|
||||
// know, which is what lets the endpoint work with no configuration on either side. It
|
||||
// suits a daemon running as root, which is what the tun device needs anyway. A daemon run as another user, or a second daemon on
|
||||
// one host, names its own. The CLI reads the same key, so when both sides see the same
|
||||
// config file they agree on the socket with nothing more said.
|
||||
const CtlSocketKey = "local_api.control.socket"
|
||||
|
||||
// CtlGroupKey is the optional config key naming a group that shares the control socket.
|
||||
// Unset, the socket admits the account nebula runs as and nobody else. Set, the socket
|
||||
// is handed to the group, 0660 on unix and an entry in the pipe's security descriptor on
|
||||
// windows; see Access and Server.trustSocket.
|
||||
const CtlGroupKey = "local_api.control.group"
|
||||
|
||||
// controlAccessFrom returns the control socket's access a config implies: the group
|
||||
// CtlGroupKey names, if any, and the mode that goes with having one or not.
|
||||
func controlAccessFrom(c interface{ GetString(string, string) string }) (Access, error) {
|
||||
group, err := groupFromConfig(c, CtlGroupKey)
|
||||
if err != nil {
|
||||
return Access{}, err
|
||||
}
|
||||
if group.ID == "" {
|
||||
return ownerOnly(), nil
|
||||
}
|
||||
return Access{Mode: groupSocketMode, Group: group}, nil
|
||||
}
|
||||
|
||||
// SocketPathFromConfig returns the control socket path a config implies: CtlSocketKey
|
||||
// when it is set, else DefaultSocketPath. A configured path must be absolute, so that
|
||||
// the daemon and nebula ctl, started from wherever the operator happens to be, name the
|
||||
// same socket from one config, and one this platform can bind; see checkSocketPath.
|
||||
func SocketPathFromConfig(c interface{ GetString(string, string) string }) (string, error) {
|
||||
override := c.GetString(CtlSocketKey, "")
|
||||
if override == "" {
|
||||
return DefaultSocketPath, nil
|
||||
}
|
||||
if err := checkSocketPath(CtlSocketKey, override); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return override, nil
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fakeConfig map[string]string
|
||||
|
||||
func (f fakeConfig) GetString(k, d string) string {
|
||||
if v, ok := f[k]; ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// TestSocketPathFromConfigUsesTheDefault is what makes the endpoint work with no
|
||||
// configuration: the daemon and the CLI both land on the one fixed path.
|
||||
func TestSocketPathFromConfigUsesTheDefault(t *testing.T) {
|
||||
p, err := SocketPathFromConfig(fakeConfig{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/var/run/nebula/ctl.sock", p)
|
||||
assert.Equal(t, DefaultSocketPath, p)
|
||||
}
|
||||
|
||||
func TestSocketPathFromConfigHonoursOverride(t *testing.T) {
|
||||
p, err := SocketPathFromConfig(fakeConfig{CtlSocketKey: "/tmp/custom.sock"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/tmp/custom.sock", p, "the path is used as given")
|
||||
}
|
||||
|
||||
// TestSocketPathFromConfigRefusesARelativeOverride: the daemon and the CLI are started
|
||||
// from different directories, so a relative path would name two sockets from one config.
|
||||
// It is refused rather than resolved against anything.
|
||||
func TestSocketPathFromConfigRefusesARelativeOverride(t *testing.T) {
|
||||
for _, rel := range []string{"run/ctl.sock", "./ctl.sock", "ctl.sock", "../ctl.sock"} {
|
||||
_, err := SocketPathFromConfig(fakeConfig{CtlSocketKey: rel})
|
||||
require.Error(t, err, rel)
|
||||
require.ErrorContains(t, err, "must be an absolute path", rel)
|
||||
assert.ErrorContains(t, err, CtlSocketKey, rel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocketPathFromConfigRejectsOverlongOverride(t *testing.T) {
|
||||
_, err := SocketPathFromConfig(fakeConfig{CtlSocketKey: "/" + strings.Repeat("x", sunPathMax)})
|
||||
assert.ErrorContains(t, err, "too long for this platform")
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
//go:build darwin || freebsd
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// peerCheckSupported reports that this platform can identify a connecting process.
|
||||
const peerCheckSupported = true
|
||||
|
||||
// peerUID returns the uid of the process on the other end of conn.
|
||||
func peerUID(conn net.Conn) (uid uint32, err error) {
|
||||
err = withPeerFD(conn, func(fd int) error {
|
||||
xu, credErr := unix.GetsockoptXucred(fd, unix.SOL_LOCAL, unix.LOCAL_PEERCRED)
|
||||
if credErr != nil {
|
||||
return credErr
|
||||
}
|
||||
uid = xu.Uid
|
||||
return nil
|
||||
})
|
||||
return uid, err
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// peerCheckSupported reports that this platform can identify a connecting process.
|
||||
const peerCheckSupported = true
|
||||
|
||||
// peerUID returns the uid of the process on the other end of conn.
|
||||
func peerUID(conn net.Conn) (uid uint32, err error) {
|
||||
err = withPeerFD(conn, func(fd int) error {
|
||||
cred, credErr := unix.GetsockoptUcred(fd, unix.SOL_SOCKET, unix.SO_PEERCRED)
|
||||
if credErr != nil {
|
||||
return credErr
|
||||
}
|
||||
uid = cred.Uid
|
||||
return nil
|
||||
})
|
||||
return uid, err
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
//go:build netbsd
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const peerCheckSupported = true
|
||||
|
||||
// NetBSD reports the peer's identity through LOCAL_PEEREID at the SOL_LOCAL level,
|
||||
// filling a `struct unpcbid { pid_t unp_pid; uid_t unp_euid; gid_t unp_egid; }`.
|
||||
// golang.org/x/sys/unix has no typed wrapper for it, so the getsockopt goes out by hand
|
||||
// exactly the way that package's own generated wrappers do on this platform.
|
||||
const (
|
||||
solLocal = 0
|
||||
localPeerEID = 0x0003
|
||||
|
||||
unpcbidSize = 12
|
||||
unpcbidEUIDOffs = 4
|
||||
)
|
||||
|
||||
// peerUID returns the uid of the process on the other end of conn.
|
||||
//
|
||||
// Anything unexpected here is an error rather than a default, so a wrong constant or an
|
||||
// unsupported kernel refuses connections instead of silently admitting them.
|
||||
func peerUID(conn net.Conn) (uid uint32, err error) {
|
||||
err = withPeerFD(conn, func(fd int) error {
|
||||
var (
|
||||
buf [unpcbidSize]byte
|
||||
size = uint32(unpcbidSize)
|
||||
)
|
||||
|
||||
_, _, errno := unix.Syscall6(
|
||||
unix.SYS_GETSOCKOPT,
|
||||
uintptr(fd),
|
||||
uintptr(solLocal),
|
||||
uintptr(localPeerEID),
|
||||
uintptr(unsafe.Pointer(&buf[0])),
|
||||
uintptr(unsafe.Pointer(&size)),
|
||||
0,
|
||||
)
|
||||
if errno != 0 {
|
||||
return errno
|
||||
}
|
||||
|
||||
if size != unpcbidSize {
|
||||
return fmt.Errorf("LOCAL_PEEREID returned %d bytes, expected %d", size, unpcbidSize)
|
||||
}
|
||||
|
||||
// Read, not cast: the buffer is bytes, and a cast would fault on an
|
||||
// architecture that wants the uint32 aligned.
|
||||
uid = binary.NativeEndian.Uint32(buf[unpcbidEUIDOffs:])
|
||||
return nil
|
||||
})
|
||||
return uid, err
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
//go:build openbsd
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// peerCheckSupported reports that this platform can identify a connecting process.
|
||||
const peerCheckSupported = true
|
||||
|
||||
// peerUID returns the uid of the process on the other end of conn.
|
||||
//
|
||||
// OpenBSD reports the peer through SO_PEERCRED at SOL_SOCKET, filling a
|
||||
// `struct sockpeercred { uid_t uid; gid_t gid; pid_t pid; }`. System calls here have to
|
||||
// go through libc, so the raw getsockopt netbsd uses is not an option, and
|
||||
// golang.org/x/sys/unix has no typed wrapper for this struct. It does export
|
||||
// GetsockoptInt, which goes through its libc trampoline with a 4 byte buffer, and the
|
||||
// kernel copies out min(caller's length, option length): the first four bytes, which are
|
||||
// the uid. That is a dependence on the field order, the same one netbsd's offset carries.
|
||||
func peerUID(conn net.Conn) (uid uint32, err error) {
|
||||
err = withPeerFD(conn, func(fd int) error {
|
||||
v, credErr := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_PEERCRED)
|
||||
if credErr != nil {
|
||||
return credErr
|
||||
}
|
||||
// A uid_t is 32 bits; GetsockoptInt read exactly that many and widened it.
|
||||
uid = uint32(v)
|
||||
return nil
|
||||
})
|
||||
return uid, err
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
// peerCheckSupported is false where the connecting process is not identified separately.
|
||||
//
|
||||
// On windows there is nothing to add: the pipe's security descriptor already admits
|
||||
// only the account nebula runs as, which is the check, not a second opinion on it.
|
||||
const peerCheckSupported = false
|
||||
|
||||
var errNoPeerCheck = errors.New("peer credentials are not available on this platform")
|
||||
|
||||
func peerUID(conn net.Conn) (uint32, error) {
|
||||
return 0, errNoPeerCheck
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const network = "unix"
|
||||
|
||||
// withPeerFD runs f on the descriptor behind conn, which must be a unix socket, and
|
||||
// returns whichever error came first: not a unix socket, no raw access to it, or f's
|
||||
// own. It is the scaffolding every platform's peerUID shares; only the getsockopt inside
|
||||
// differs.
|
||||
func withPeerFD(conn net.Conn, f func(fd int) error) error {
|
||||
uc, ok := conn.(*net.UnixConn)
|
||||
if !ok {
|
||||
return fmt.Errorf("not a unix connection")
|
||||
}
|
||||
|
||||
raw, err := uc.SyscallConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var inner error
|
||||
if err := raw.Control(func(fd uintptr) { inner = f(int(fd)) }); err != nil {
|
||||
return err
|
||||
}
|
||||
return inner
|
||||
}
|
||||
|
||||
// currentUID is the user the owner checks are made for. A variable so a test can stand
|
||||
// in for root, or for a stranger, without owning a second account on the host.
|
||||
var currentUID = func() uint32 { return uint32(os.Geteuid()) }
|
||||
|
||||
// listen binds the socket at path with the given access.
|
||||
//
|
||||
// Access control is the socket's own mode and group, which the node is created no
|
||||
// looser than and which are set after bind: connect(2) needs write permission on the
|
||||
// socket file on every unix we build for. The control socket is 0600 and adds the peer
|
||||
// check the server applies on accept, unless a group shares it, in which case it is
|
||||
// 0660 with that group and the kernel's check is the whole of it; the info socket is
|
||||
// whatever the operator configured, since opening it to others is its purpose.
|
||||
//
|
||||
// The directory is not part of that, and is never chmoded: a directory a service manager made for us is served from at whatever mode it
|
||||
// came with (systemd's RuntimeDirectoryMode= is 0755 by default), and one an operator
|
||||
// pointed us into keeps whatever else it holds readable. The one we make ourselves is
|
||||
// 0755, searchable by everyone, so that a nebula ctl run as another user reaches the
|
||||
// socket and gets the kernel's answer, which for a member of the configured group is
|
||||
// a connection and for anyone else is permission denied.
|
||||
func listen(path string, acc Access) (net.Listener, error) {
|
||||
// The kernel silently truncates an over long sun_path and bind then fails with
|
||||
// "invalid argument", which tells an operator nothing. Say what is actually wrong.
|
||||
if pathTooLong(path) {
|
||||
return nil, fmt.Errorf("socket path is %d bytes, over the %d byte limit for a unix socket: %s", len(path), maxSocketPath, path)
|
||||
}
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
|
||||
// One level only. Every directory defaultPathFor offers sits directly under one that
|
||||
// exists, and an operator who names a deeper path creates it; a missing parent is a
|
||||
// mistake to report, not a tree to build. A directory made here stays when the
|
||||
// socket goes: an empty one costs nothing, and the next start wants it again.
|
||||
//
|
||||
// The mode comes from the umask around the call, never from a chmod afterwards: a
|
||||
// chmod by path could land on whatever somebody who can write the parent swapped in
|
||||
// between the two calls, and a chmod through a descriptor on a root-owned directory
|
||||
// they moved there, since root owns both. Born 0755 there is nothing to fix up.
|
||||
// The umask is process wide and the window is one syscall; see umaskMu.
|
||||
umaskMu.Lock()
|
||||
old := syscall.Umask(0022)
|
||||
err := os.Mkdir(dir, 0755)
|
||||
syscall.Umask(old)
|
||||
umaskMu.Unlock()
|
||||
if err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return nil, fmt.Errorf("could not create %s: %w", dir, err)
|
||||
}
|
||||
|
||||
// Whether it was made here or came with the environment, the directory has to be
|
||||
// one nobody else could change; see checkSocketDir.
|
||||
if err := checkSocketDir(dir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := clearStale(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// bind creates the socket node at the process umask, and a connect(2) between that
|
||||
// and a later chmod would be queued for accept. Tighten the umask around the bind so
|
||||
// the node is never looser than 0600, however briefly, whatever mode it ends up at;
|
||||
// see umaskMu.
|
||||
umaskMu.Lock()
|
||||
old = syscall.Umask(0077)
|
||||
ln, err := net.Listen(network, path)
|
||||
syscall.Umask(old)
|
||||
umaskMu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// What was just bound, so that a failure below gives up that node and not whatever
|
||||
// has been put at the path since.
|
||||
id, _ := identifySocket(path)
|
||||
|
||||
// The node at path is given up by release, which unlinks it before the listener
|
||||
// closes; see there for why the order matters. Go's listener would unlink on Close
|
||||
// as well, and an unlink after the close could only be of whatever bound the path
|
||||
// next, so that is turned off and release is the one place the node is removed.
|
||||
if ul, ok := ln.(*net.UnixListener); ok {
|
||||
ul.SetUnlinkOnClose(false)
|
||||
}
|
||||
|
||||
// The umask only promises no looser than 0600; this pins the mode and the group
|
||||
// exactly, and is the one place a failure to secure the socket is reported.
|
||||
if err := applyAccess(path, acc); err != nil {
|
||||
release(ln, path, id)
|
||||
return nil, fmt.Errorf("could not secure %s: %w", path, err)
|
||||
}
|
||||
|
||||
return ln, nil
|
||||
}
|
||||
|
||||
// checkOwnSocket refuses what fi found at path unless it is a socket owned by the user
|
||||
// this process runs as. fi comes from a look that does not follow links, so a symlink is
|
||||
// seen as one, and the mode is only ever applied to a socket of ours. checkSocketDir
|
||||
// vouched for the directory at bind, but that was then: a directory loosened since, or a
|
||||
// reload that moves the socket, is a chance for whoever can write it to replace the node
|
||||
// with a link, or a hard link to a file of their choosing, and have a root daemon set the
|
||||
// configured mode, 0660 or 0666 for an info socket, on that file. A link, another type
|
||||
// of file, or somebody else's socket is reported and left as it is. applyAccess, per
|
||||
// platform, is what makes the look and the change land on the same node.
|
||||
func checkOwnSocket(path string, fi os.FileInfo) error {
|
||||
if !isSocket(fi) {
|
||||
return fmt.Errorf("%s is not a socket but %s, refusing to change its mode", path, describeNode(fi))
|
||||
}
|
||||
|
||||
if uid, ok := owner(fi); ok && uid != currentUID() {
|
||||
return fmt.Errorf("%s is owned by %s, not by us, refusing to change its mode", path, describeUID(uid))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// describeNode names what kind of file fi describes, for a message about something found
|
||||
// where a socket was expected.
|
||||
func describeNode(fi os.FileInfo) string {
|
||||
switch m := fi.Mode(); {
|
||||
case m&os.ModeSymlink != 0:
|
||||
return "a symlink"
|
||||
case m.IsDir():
|
||||
return "a directory"
|
||||
case m.IsRegular():
|
||||
return "a regular file"
|
||||
default:
|
||||
return "a " + m.Type().String() + " file"
|
||||
}
|
||||
}
|
||||
|
||||
// checkSocketDir refuses to serve from a directory that somebody other than the user
|
||||
// nebula runs as, or root, could change. The socket's mode and group say who may connect
|
||||
// to it; what makes the path they connect to the daemon's is the directory, since
|
||||
// whoever can write it can put a socket of their own at the path and answer the clients
|
||||
// in the daemon's place. So the directory must be owned by the daemon's user or by root
|
||||
// and writable by its owner alone; a sticky bit is not an exception. A runtime directory
|
||||
// a service manager made for another user, or /var/run/nebula created ahead of a root
|
||||
// daemon by a member of group daemon, where darwin lets that group write /var/run, are
|
||||
// both refused with the owner named.
|
||||
//
|
||||
// A link where the directory should be is judged twice: whoever owns the link decides
|
||||
// where the path leads, so the link must be ours or root's too, and the directory it
|
||||
// resolves to is then held to the rule above. /var/run is such a link on linux, root's,
|
||||
// to /run, and a socket named directly under it is served; a link somebody else planted
|
||||
// is refused as theirs.
|
||||
//
|
||||
// Only this directory is checked, not the ones above it. /var/run itself is group
|
||||
// writable on darwin by design, and the parents are the operator's to trust, as they are
|
||||
// for every file nebula reads. The check is made at bind, so a directory loosened while
|
||||
// the daemon runs is noticed at the next reload.
|
||||
func checkSocketDir(dir string) error {
|
||||
fi, err := os.Lstat(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fi.Mode()&os.ModeSymlink != 0 {
|
||||
if uid, ok := owner(fi); ok && uid != currentUID() && uid != 0 {
|
||||
return fmt.Errorf("%s is a symlink owned by %s, not by the user nebula runs as or by root, and its owner decides where the path leads; name a socket path that does not go through it", dir, describeUID(uid))
|
||||
}
|
||||
if fi, err = os.Stat(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !fi.IsDir() {
|
||||
return fmt.Errorf("%s is not a directory", dir)
|
||||
}
|
||||
|
||||
if uid, ok := owner(fi); ok && uid != currentUID() && uid != 0 {
|
||||
return fmt.Errorf("%s is owned by %s, not by the user nebula runs as or by root, and its owner could replace the socket; make it ours or root's, or name a socket path in a directory that is", dir, describeUID(uid))
|
||||
}
|
||||
|
||||
if perm := fi.Mode().Perm(); perm&0022 != 0 {
|
||||
who := "its group"
|
||||
if perm&0002 != 0 {
|
||||
who = "everyone"
|
||||
}
|
||||
return fmt.Errorf("%s is writable by %s (mode %04o), who could replace the socket; make it writable by its owner alone, or name a socket path in a directory that is", dir, who, perm)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// owner returns the uid that owns the file fi describes.
|
||||
func owner(fi os.FileInfo) (uint32, bool) {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return uint32(st.Uid), true
|
||||
}
|
||||
|
||||
// describeUID renders a uid with its account name when the host can say what it is, so
|
||||
// a message about somebody else's socket tells the operator who that is.
|
||||
func describeUID(uid uint32) string {
|
||||
id := strconv.FormatUint(uint64(uid), 10)
|
||||
if u, err := user.LookupId(id); err == nil && u.Username != "" {
|
||||
return "uid " + id + " (" + u.Username + ")"
|
||||
}
|
||||
|
||||
return "uid " + id
|
||||
}
|
||||
|
||||
// clearStale removes a leftover socket file, but only after proving nothing is
|
||||
// listening on it. An unclean restart leaves one behind every time, so this is a
|
||||
// routine path; blindly unlinking would let a second daemon steal a live endpoint.
|
||||
//
|
||||
// Liveness is a plain connect. Only a refused connect proves there is nothing behind
|
||||
// the file. Anything else, a timeout or a permission error, is a socket we cannot vouch
|
||||
// for, and it is left alone with the reason in the error.
|
||||
//
|
||||
// The look is an Lstat: a symlink at path is refused as not a socket, whether or not it
|
||||
// resolves. Stat would report a dangling one as nothing there, and bind(2) on darwin
|
||||
// and the BSDs follows a dangling link and creates the socket node at its target.
|
||||
func clearStale(path string) error {
|
||||
fi, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !isSocket(fi) {
|
||||
return fmt.Errorf("%s exists and is not a socket", path)
|
||||
}
|
||||
|
||||
conn, err := dial(path, 250*time.Millisecond)
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
return fmt.Errorf("%s is already in use by another nebula instance", path)
|
||||
}
|
||||
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
// Gone between the stat and the connect; nothing to clear.
|
||||
return nil
|
||||
}
|
||||
|
||||
if !errors.Is(err, syscall.ECONNREFUSED) {
|
||||
return fmt.Errorf("%s exists and could not be shown to be stale, refusing to remove it: %w", path, err)
|
||||
}
|
||||
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
// removeSocket unlinks the socket node. Its directory stays, whoever made it; see
|
||||
// listen.
|
||||
//
|
||||
// Only the node id names is removed. One that replaced it is another daemon's, bound
|
||||
// after ours was taken from under us, and is left where it is. A zero id, a node that
|
||||
// could not be identified when it was bound, is removed.
|
||||
func removeSocket(path string, id socketID) {
|
||||
if cur, ok := identifySocket(path); ok && id != (socketID{}) && cur != id {
|
||||
return
|
||||
}
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
|
||||
// identifySocket returns the identity of the node at path, looked at without following
|
||||
// links, and false when there is nothing there or it cannot be read.
|
||||
func identifySocket(path string) (socketID, bool) {
|
||||
fi, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return socketID{}, false
|
||||
}
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return socketID{}, false
|
||||
}
|
||||
return socketID{dev: uint64(st.Dev), ino: uint64(st.Ino)}, true
|
||||
}
|
||||
|
||||
func dial(path string, timeout time.Duration) (net.Conn, error) {
|
||||
return net.DialTimeout(network, path, timeout)
|
||||
}
|
||||
|
||||
// sunPathMax is the smallest sun_path any platform we build for offers (104 on darwin,
|
||||
// 108 on linux). Overrunning it truncates the path rather than failing cleanly, so we
|
||||
// check against the tighter bound everywhere.
|
||||
const sunPathMax = 104
|
||||
|
||||
// maxSocketPath is the longest path that actually binds. sun_path holds the trailing
|
||||
// NUL as well, and Go's syscall package refuses a path that fills the whole buffer
|
||||
// with a bare EINVAL, so the usable limit is one byte short of the buffer.
|
||||
const maxSocketPath = sunPathMax - 1
|
||||
|
||||
// umaskMu serialises the two places the process umask is set around one syscall: the
|
||||
// umask is process wide, and two endpoints binding at once, a reload landing during
|
||||
// startup, would otherwise interleave their save and restore and leave the daemon's
|
||||
// umask at one of ours. It is held for the syscall alone. Another goroutine creating a
|
||||
// file in that moment gets the umask of the window, 0022 or 0077, rather than the
|
||||
// process's own; nothing creates files on a hot path.
|
||||
var umaskMu sync.Mutex
|
||||
|
||||
func pathTooLong(path string) bool { return len(path) > maxSocketPath }
|
||||
|
||||
// DefaultSocketPath is the control socket when the config names none. It is root's to
|
||||
// create, as the tun device is root's to open; a daemon run as anyone else names a path
|
||||
// of its own with CtlSocketKey.
|
||||
const DefaultSocketPath = "/var/run/" + DirName + "/ctl.sock"
|
||||
|
||||
// unprotectedNameWarning is for windows pipe names; a unix socket's directory is
|
||||
// checked instead.
|
||||
func unprotectedNameWarning(string) string { return "" }
|
||||
|
||||
// checkSocketPath refuses a configured socket path that is relative, or too long to
|
||||
// bind. A relative path would mean a different socket to the daemon and to nebula ctl,
|
||||
// each resolving it against the directory it happened to be started from.
|
||||
func checkSocketPath(key, value string) error {
|
||||
if !filepath.IsAbs(value) {
|
||||
return fmt.Errorf("%s must be an absolute path, got %q", key, value)
|
||||
}
|
||||
if pathTooLong(value) {
|
||||
return fmt.Errorf("%s is %d bytes, too long for this platform: %s", key, len(value), value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isSocket(fi os.FileInfo) bool { return fi.Mode()&os.ModeSocket != 0 }
|
||||
@@ -1,462 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// privateBase returns a short directory of our own, 0700, for tests to lay sockets out
|
||||
// under, short enough that a path under it fits sun_path.
|
||||
func privateBase(t *testing.T) string {
|
||||
t.Helper()
|
||||
return test.ShortTempDir(t)
|
||||
}
|
||||
|
||||
// openDir returns a world writable directory under base, the shape of /tmp.
|
||||
func openDir(t *testing.T, base string) string {
|
||||
t.Helper()
|
||||
|
||||
open := filepath.Join(base, "open")
|
||||
require.NoError(t, os.Mkdir(open, 0777))
|
||||
require.NoError(t, os.Chmod(open, 0777|os.ModeSticky))
|
||||
return open
|
||||
}
|
||||
|
||||
// TestListenLeavesAServiceManagersDirectoryAlone covers the directory a service manager
|
||||
// pre-creates: systemd's RuntimeDirectory is 0755 by default. The socket is 0600, which
|
||||
// is what refuses other users, so the directory is served from as it came and nothing
|
||||
// is chmoded that the operator did not set.
|
||||
func TestListenLeavesAServiceManagersDirectoryAlone(t *testing.T) {
|
||||
base := privateBase(t)
|
||||
dir := filepath.Join(base, DirName)
|
||||
require.NoError(t, os.Mkdir(dir, 0755))
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), filepath.Join(dir, "s.sock"), ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
fi, err := os.Stat(dir)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0755), fi.Mode().Perm(), "the directory is left exactly as it was")
|
||||
|
||||
fi, err = os.Stat(s.Path())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0600), fi.Mode().Perm(), "the socket is what is private")
|
||||
_, err = (&Client{Path: s.Path()}).Describe()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// TestListenCreatesOneLevelOnly: the socket directory is created when it is missing,
|
||||
// but nothing above it is. A runtime directory that does not exist is the operator's to
|
||||
// provide, and the failure says which directory could not be created.
|
||||
func TestListenCreatesOneLevelOnly(t *testing.T) {
|
||||
base := privateBase(t)
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), filepath.Join(base, DirName, "s.sock"), ownerOnly()))
|
||||
s.Stop()
|
||||
|
||||
dir := filepath.Join(base, "missing", DirName)
|
||||
err := s.Rebind(context.Background(), filepath.Join(dir, "s.sock"), ownerOnly())
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "could not create "+dir)
|
||||
assert.NoDirExists(t, filepath.Join(base, "missing"))
|
||||
}
|
||||
|
||||
// TestListenRestoresTheUmask: listen tightens the process umask around bind so the socket
|
||||
// node is never created looser than 0600. That is process wide state, so it must come
|
||||
// back exactly as it was, on success and on failure alike.
|
||||
func TestListenRestoresTheUmask(t *testing.T) {
|
||||
old := syscall.Umask(0022)
|
||||
t.Cleanup(func() { syscall.Umask(old) })
|
||||
|
||||
base := privateBase(t)
|
||||
ln, err := listen(filepath.Join(base, DirName, "s.sock"), ownerOnly())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { ln.Close() })
|
||||
assert.Equal(t, 0022, syscall.Umask(0022), "umask after a successful listen")
|
||||
|
||||
_, err = listen(filepath.Join(base, DirName, "s.sock"), ownerOnly())
|
||||
require.Error(t, err, "the path is already bound")
|
||||
assert.Equal(t, 0022, syscall.Umask(0022), "umask after a failed listen")
|
||||
}
|
||||
|
||||
// TestListenServesFromASharedDirectory: an operator who points local_api.control.socket
|
||||
// into a directory holding other files, /etc/nebula say, gets a socket there and keeps
|
||||
// the config and certs readable by everyone who could read them before.
|
||||
func TestListenServesFromASharedDirectory(t *testing.T) {
|
||||
base := privateBase(t)
|
||||
dir := filepath.Join(base, "etc-nebula")
|
||||
require.NoError(t, os.Mkdir(dir, 0755))
|
||||
cfg := filepath.Join(dir, "config.yml")
|
||||
require.NoError(t, os.WriteFile(cfg, []byte("{}\n"), 0644))
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), filepath.Join(dir, "ctl.sock"), ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
fi, err := os.Stat(dir)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0755), fi.Mode().Perm())
|
||||
fi, err = os.Stat(cfg)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0644), fi.Mode().Perm())
|
||||
}
|
||||
|
||||
func TestOverlongPathIsDiagnosed(t *testing.T) {
|
||||
long := filepath.Join(os.TempDir(), string(make([]byte, 0)))
|
||||
for len(long) <= sunPathMax {
|
||||
long = filepath.Join(long, "abcdefghij")
|
||||
}
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
err := s.Rebind(context.Background(), filepath.Join(long, "s.sock"), ownerOnly())
|
||||
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "byte limit for a unix socket")
|
||||
}
|
||||
|
||||
// TestPathLimitIsExact pins the boundary: sun_path has room for the NUL as well, and Go
|
||||
// refuses a path that fills the whole buffer, so the last usable length is one short.
|
||||
func TestPathLimitIsExact(t *testing.T) {
|
||||
assert.False(t, pathTooLong(strings.Repeat("a", maxSocketPath)))
|
||||
assert.True(t, pathTooLong(strings.Repeat("a", maxSocketPath+1)))
|
||||
assert.True(t, pathTooLong(strings.Repeat("a", sunPathMax)))
|
||||
}
|
||||
|
||||
// TestNamedPathIsUsedAsGiven: a path the operator named is served from, and dialed,
|
||||
// wherever it is, a directory other users can write to included; the socket's own mode
|
||||
// is what keeps them out.
|
||||
func TestNamedPathIsUsedAsGiven(t *testing.T) {
|
||||
base := privateBase(t)
|
||||
path := filepath.Join(openDir(t, base), DirName, "s.sock")
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
_, err := (&Client{Path: path}).Describe()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// TestStaleSocketIsCleared: a dead socket in a good directory is the routine leftover of
|
||||
// a hard kill, and the daemon's stale check must see it as free to replace.
|
||||
func TestStaleSocketIsCleared(t *testing.T) {
|
||||
path := testSocket(t)
|
||||
require.NoError(t, os.Mkdir(filepath.Dir(path), 0700))
|
||||
ln, err := net.Listen(network, path)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chmod(path, 0600))
|
||||
// Close the listener but keep the file, the way a hard kill does.
|
||||
ln.(*net.UnixListener).SetUnlinkOnClose(false)
|
||||
require.NoError(t, ln.Close())
|
||||
_, statErr := os.Stat(path)
|
||||
require.NoError(t, statErr, "the socket file is still there")
|
||||
|
||||
require.NoError(t, clearStale(path), "a stale socket is cleared, not reported as in use")
|
||||
_, statErr = os.Stat(path)
|
||||
assert.True(t, os.IsNotExist(statErr))
|
||||
}
|
||||
|
||||
// TestClientSaysWhenTheReplyCannotBeRead: something answered on the socket, but not
|
||||
// with a response. That is reported as a reply that could not be read, which is what
|
||||
// it is, and not as a failure to reach the daemon, whether the other side read the
|
||||
// request first or hung up on it: a daemon that is not nebula may do either.
|
||||
func TestClientSaysWhenTheReplyCannotBeRead(t *testing.T) {
|
||||
for _, readsFirst := range []bool{true, false} {
|
||||
path := testSocket(t)
|
||||
require.NoError(t, os.Mkdir(filepath.Dir(path), 0700))
|
||||
ln, err := net.Listen(network, path)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chmod(path, 0600))
|
||||
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if readsFirst {
|
||||
_, _ = bufio.NewReader(c).ReadBytes('\n')
|
||||
}
|
||||
_, _ = c.Write([]byte("this is not a response\n"))
|
||||
c.Close()
|
||||
}()
|
||||
|
||||
_, err = (&Client{Path: path}).Describe()
|
||||
var unread *ReplyError
|
||||
require.ErrorAs(t, err, &unread, "reads first: %v", readsFirst)
|
||||
assert.Contains(t, err.Error(), "the daemon's reply could not be read")
|
||||
ln.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientGivesUpOnASilentDaemon: a daemon that accepts and then never answers must
|
||||
// not hang the client for good. A script wrapping nebula ctl has no other way out.
|
||||
func TestClientGivesUpOnASilentDaemon(t *testing.T) {
|
||||
path := testSocket(t)
|
||||
require.NoError(t, os.Mkdir(filepath.Dir(path), 0700))
|
||||
ln, err := net.Listen(network, path)
|
||||
require.NoError(t, err)
|
||||
defer ln.Close()
|
||||
require.NoError(t, os.Chmod(path, 0600))
|
||||
|
||||
accepted := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err == nil {
|
||||
accepted <- c // held open, never written to
|
||||
}
|
||||
}()
|
||||
|
||||
start := time.Now()
|
||||
_, err = (&Client{Path: path, Timeout: 200 * time.Millisecond}).Describe()
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "did not answer within")
|
||||
assert.Less(t, time.Since(start), 5*time.Second)
|
||||
|
||||
select {
|
||||
case c := <-accepted:
|
||||
_ = c.Close()
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// asUID makes the owner checks run as uid for the rest of the test. The socket the test
|
||||
// serves is still owned by the real user, so from uid's point of view it belongs to
|
||||
// somebody else: the shape of a service account's daemon, and of an impostor's.
|
||||
func asUID(t *testing.T, uid uint32) {
|
||||
t.Helper()
|
||||
real := currentUID
|
||||
currentUID = func() uint32 { return uid }
|
||||
t.Cleanup(func() { currentUID = real })
|
||||
}
|
||||
|
||||
// TestPeerCheckRefusesAnotherUser: a server built as one user and serving as another
|
||||
// refuses the real user at the peer check, and the refusal reaches the client as the
|
||||
// daemon's answer rather than as a failure to reach it.
|
||||
func TestPeerCheckRefusesAnotherUser(t *testing.T) {
|
||||
if !peerCheckSupported {
|
||||
t.Skip("no peer credentials on this platform")
|
||||
}
|
||||
|
||||
me := currentUID()
|
||||
asUID(t, me+1)
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
asUID(t, me)
|
||||
|
||||
path := testSocket(t)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
defer s.Stop()
|
||||
|
||||
_, err := (&Client{Path: path}).Describe()
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "not permitted")
|
||||
var refused *DaemonError
|
||||
assert.ErrorAs(t, err, &refused, "the daemon answered; this is not a reachability failure")
|
||||
}
|
||||
|
||||
// TestListenerDoesNotUnlinkOnClose: the server unlinks its socket node itself, before
|
||||
// the listener closes, and the listener must not unlink again afterwards. By the time a
|
||||
// close happens the path may belong to a newer daemon that found the node stale and
|
||||
// bound its own, and a second unlink would take that daemon's socket from under it.
|
||||
func TestListenerDoesNotUnlinkOnClose(t *testing.T) {
|
||||
path := filepath.Join(privateBase(t), DirName, "s.sock")
|
||||
old, err := listen(path, ownerOnly())
|
||||
require.NoError(t, err)
|
||||
|
||||
// A newer daemon's start, with the old node gone and the path bound afresh.
|
||||
require.NoError(t, os.Remove(path))
|
||||
next, err := net.Listen(network, path)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { next.Close() })
|
||||
|
||||
require.NoError(t, old.Close())
|
||||
_, err = os.Stat(path)
|
||||
assert.NoError(t, err, "closing the old listener left the newer daemon's socket in place")
|
||||
}
|
||||
|
||||
// TestRebindRecreatesASocketRemovedFromUnderIt: logind clearing /run/user/<uid> on
|
||||
// logout, or a unit cleaning a RuntimeDirectory= it shares, takes the node away while
|
||||
// the listener stays open and unreachable. The next reload, which Rebinds onto the same
|
||||
// path, has to notice and bind the socket again rather than return early because the
|
||||
// path has not changed.
|
||||
func TestRebindRecreatesASocketRemovedFromUnderIt(t *testing.T) {
|
||||
path := testSocket(t)
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
require.NoError(t, os.Remove(path))
|
||||
_, err := (&Client{Path: path}).Describe()
|
||||
require.Error(t, err, "nothing can reach the daemon with its node gone")
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
assert.Equal(t, path, s.Path())
|
||||
_, err = (&Client{Path: path}).Describe()
|
||||
require.NoError(t, err, "the plain reload brought the socket back")
|
||||
|
||||
// And a Rebind with the socket in place is still a no-op.
|
||||
before, ok := identifySocket(path)
|
||||
require.True(t, ok)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
after, _ := identifySocket(path)
|
||||
assert.Equal(t, before, after, "the node was left alone")
|
||||
}
|
||||
|
||||
// TestStopLeavesAStrangersSocketAlone: once our node has been taken from under us and
|
||||
// another daemon has bound the path, the node there is that daemon's, and our Stop must
|
||||
// not unlink it by path.
|
||||
func TestStopLeavesAStrangersSocketAlone(t *testing.T) {
|
||||
path := testSocket(t)
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
|
||||
require.NoError(t, os.Remove(path))
|
||||
other, err := net.Listen(network, path)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { other.Close() })
|
||||
|
||||
s.Stop()
|
||||
_, err = os.Stat(path)
|
||||
assert.NoError(t, err, "the newer daemon's socket is still in place")
|
||||
}
|
||||
|
||||
// TestListenRefusesADirectoryOthersCanWrite: whoever can write the socket's directory
|
||||
// can put a socket of their own at the path and answer the clients, who trust the path;
|
||||
// so a directory writable by its group or by everyone is refused, and nothing is bound.
|
||||
func TestListenRefusesADirectoryOthersCanWrite(t *testing.T) {
|
||||
for _, mode := range []os.FileMode{0775, 0757, 0777, 01777} {
|
||||
dir := filepath.Join(privateBase(t), "loose")
|
||||
require.NoError(t, os.Mkdir(dir, mode))
|
||||
require.NoError(t, os.Chmod(dir, mode))
|
||||
|
||||
_, err := listen(filepath.Join(dir, "s.sock"), ownerOnly())
|
||||
require.ErrorContains(t, err, "writable by", "mode %04o", mode)
|
||||
assert.NoFileExists(t, filepath.Join(dir, "s.sock"))
|
||||
}
|
||||
}
|
||||
|
||||
// TestListenRefusesADirectoryOwnedBySomebodyElse: a directory that is neither ours nor
|
||||
// root's is refused, since its owner could replace the socket. The test's own directory
|
||||
// stands in for somebody else's by the process pretending to be another user.
|
||||
func TestListenRefusesADirectoryOwnedBySomebodyElse(t *testing.T) {
|
||||
me := currentUID()
|
||||
if me == 0 {
|
||||
t.Skip("root's directories are accepted whoever is asking")
|
||||
}
|
||||
dir := filepath.Join(privateBase(t), "theirs")
|
||||
require.NoError(t, os.Mkdir(dir, 0755))
|
||||
|
||||
asUID(t, me+1)
|
||||
_, err := listen(filepath.Join(dir, "s.sock"), ownerOnly())
|
||||
require.ErrorContains(t, err, "is owned by")
|
||||
assert.NoFileExists(t, filepath.Join(dir, "s.sock"))
|
||||
|
||||
asUID(t, me)
|
||||
ln, err := listen(filepath.Join(dir, "s.sock"), ownerOnly())
|
||||
require.NoError(t, err, "the same directory, seen as our own, serves")
|
||||
release(ln, filepath.Join(dir, "s.sock"), socketID{})
|
||||
}
|
||||
|
||||
// TestListenThroughASymlinkedDirectory: a link where the directory should be is judged
|
||||
// by who owns it, since they decide where the path leads, and then by the directory it
|
||||
// resolves to. Our own link to a proper directory serves, as /var/run on linux is root's
|
||||
// link to /run; somebody else's link is refused, and so is a link of ours to a directory
|
||||
// others can write.
|
||||
func TestListenThroughASymlinkedDirectory(t *testing.T) {
|
||||
me := currentUID()
|
||||
if me == 0 {
|
||||
t.Skip("root's links are accepted whoever is asking")
|
||||
}
|
||||
base := privateBase(t)
|
||||
real := filepath.Join(base, "real")
|
||||
require.NoError(t, os.Mkdir(real, 0755))
|
||||
link := filepath.Join(base, "link")
|
||||
require.NoError(t, os.Symlink(real, link))
|
||||
path := filepath.Join(link, "s.sock")
|
||||
|
||||
ln, err := listen(path, ownerOnly())
|
||||
require.NoError(t, err, "our link to our directory")
|
||||
release(ln, path, socketID{})
|
||||
assert.NoFileExists(t, filepath.Join(real, "s.sock"))
|
||||
|
||||
asUID(t, me+1)
|
||||
_, err = listen(path, ownerOnly())
|
||||
require.ErrorContains(t, err, "is a symlink owned by")
|
||||
asUID(t, me)
|
||||
|
||||
require.NoError(t, os.Chmod(real, 0777))
|
||||
_, err = listen(path, ownerOnly())
|
||||
require.ErrorContains(t, err, "writable by everyone")
|
||||
}
|
||||
|
||||
// TestListenRefusesASymlinkAtThePath: a link where the socket should be is somebody
|
||||
// else's doing, and it is refused before bind rather than followed. bind(2) on darwin
|
||||
// follows a dangling link and creates the socket at its target, and the chmod after it
|
||||
// would follow a link to anything, so neither the target nor the link is touched.
|
||||
func TestListenRefusesASymlinkAtThePath(t *testing.T) {
|
||||
path := testSocket(t)
|
||||
require.NoError(t, os.Mkdir(filepath.Dir(path), 0700))
|
||||
target := filepath.Join(filepath.Dir(path), "target")
|
||||
|
||||
require.NoError(t, os.Symlink(target, path))
|
||||
_, err := listen(path, Access{Mode: 0666})
|
||||
require.ErrorContains(t, err, "is not a socket")
|
||||
_, statErr := os.Lstat(target)
|
||||
assert.True(t, os.IsNotExist(statErr), "a dangling link's target is not created")
|
||||
|
||||
require.NoError(t, os.WriteFile(target, nil, 0600))
|
||||
_, err = listen(path, Access{Mode: 0666})
|
||||
require.ErrorContains(t, err, "is not a socket")
|
||||
fi, err := os.Stat(target)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0600), fi.Mode().Perm(), "the file the link names keeps its mode")
|
||||
assert.True(t, fi.Mode().IsRegular())
|
||||
}
|
||||
|
||||
// TestChmodSocketRefusesWhatIsNotOurSocket: the mode is set through a look that does not
|
||||
// follow links, so a link, a plain file, or a socket of another user's at the path is
|
||||
// reported instead of chmoded. The last is seen as another user by changing who we are.
|
||||
func TestChmodSocketRefusesWhatIsNotOurSocket(t *testing.T) {
|
||||
dir := filepath.Join(privateBase(t), "n")
|
||||
require.NoError(t, os.Mkdir(dir, 0700))
|
||||
|
||||
file := filepath.Join(dir, "file")
|
||||
require.NoError(t, os.WriteFile(file, nil, 0600))
|
||||
link := filepath.Join(dir, "link")
|
||||
require.NoError(t, os.Symlink(file, link))
|
||||
|
||||
require.ErrorContains(t, applyAccess(link, Access{Mode: 0666}), "a symlink")
|
||||
require.ErrorContains(t, applyAccess(file, Access{Mode: 0666}), "a regular file")
|
||||
fi, err := os.Stat(file)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0600), fi.Mode().Perm())
|
||||
|
||||
sock := filepath.Join(dir, "s.sock")
|
||||
ln, err := net.Listen(network, sock)
|
||||
require.NoError(t, err)
|
||||
defer ln.Close()
|
||||
require.NoError(t, applyAccess(sock, Access{Mode: 0660}))
|
||||
fi, err = os.Stat(sock)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0660), fi.Mode().Perm())
|
||||
|
||||
asUID(t, currentUID()+1)
|
||||
require.ErrorContains(t, applyAccess(sock, Access{Mode: 0666}), "not by us")
|
||||
fi, err = os.Stat(sock)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0660), fi.Mode().Perm())
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Microsoft/go-winio"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// pipePrefix is where windows named pipes live. The pipe's own security descriptor
|
||||
// carries the access control that the socket's mode carries on unix.
|
||||
const pipePrefix = `\\.\pipe\`
|
||||
|
||||
// protectedPrefix is the pipe namespace that only administrators and SYSTEM may create
|
||||
// names under; the kernel refuses everyone else. The default name lives there, so the
|
||||
// name itself says who could have created the pipe answering it: no ordinary user can
|
||||
// have put anything under it ahead of the daemon. Tailscale, WireGuard and NetBird keep
|
||||
// their daemon pipes there for the same reason. nebula on windows is already an
|
||||
// administrator, since creating the tun adapter requires it.
|
||||
const protectedPrefix = pipePrefix + `ProtectedPrefix\Administrators\`
|
||||
|
||||
const network = "pipe"
|
||||
|
||||
// currentUID is the identity the unix owner checks are made for. There is no uid here
|
||||
// and no per-connection check that would read one, so the value is never consulted; it
|
||||
// exists so a Server is built the same way on every platform.
|
||||
var currentUID = func() uint32 { return 0 }
|
||||
|
||||
// listen creates the named pipe at path with a security descriptor that admits the user
|
||||
// nebula runs as, SYSTEM and Administrators, and the group acc names, if any, for
|
||||
// reading and writing, which is what connecting to a pipe takes. acc's mode means
|
||||
// nothing to a pipe.
|
||||
//
|
||||
// The first instance is created, never opened, so a name some other process already
|
||||
// holds is refused rather than joined: that process would otherwise answer clients in
|
||||
// nebula's place. Under protectedPrefix only an administrator could hold it; anywhere
|
||||
// else any account could. Either way the refusal is reported as errEndpointHeld for the
|
||||
// caller to log as the event it is, except when the refusal is the namespace's own: a
|
||||
// daemon that is not an administrator cannot create under protectedPrefix at all, and
|
||||
// that is told apart so the operator is sent to elevate or to name a pipe elsewhere
|
||||
// rather than to look for a process that is not there.
|
||||
func listen(path string, acc Access) (net.Listener, error) {
|
||||
sddl, err := sddlFor(acc)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not build a security descriptor for %s: %w", path, err)
|
||||
}
|
||||
|
||||
ln, err := winio.ListenPipe(path, &winio.PipeConfig{
|
||||
SecurityDescriptor: sddl,
|
||||
InputBufferSize: int32(MaxRequestBytes),
|
||||
OutputBufferSize: 64 * 1024,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, listenRefused(path, isAdministrator(), err)
|
||||
}
|
||||
|
||||
return ln, nil
|
||||
}
|
||||
|
||||
// listenRefused turns a failure to create the pipe at path into the error the caller
|
||||
// logs. admin says whether this process may create under protectedPrefix.
|
||||
//
|
||||
// ERROR_ACCESS_DENIED is ambiguous: it is what the kernel says to a non-administrator
|
||||
// creating under protectedPrefix, and also what an existing instance whose DACL does
|
||||
// not admit us says to a second create. A process that is an administrator cannot be
|
||||
// getting the first, so for it, and for every name outside the prefix, access denied
|
||||
// means held.
|
||||
func listenRefused(path string, admin bool, err error) error {
|
||||
if errors.Is(err, windows.ERROR_ACCESS_DENIED) && isProtectedPath(path) && !admin {
|
||||
return fmt.Errorf("creating %s requires an administrator, as only administrators may create pipes under %s; run nebula elevated, or set %s to a pipe name outside it: %w", path, protectedPrefix, CtlSocketKey, err)
|
||||
}
|
||||
if errors.Is(err, windows.ERROR_ALREADY_EXISTS) || errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
||||
return fmt.Errorf("%w: %s: %w", errEndpointHeld, path, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// isProtectedPath says whether path is a name under protectedPrefix. Pipe names are
|
||||
// case insensitive, so the comparison is too.
|
||||
func isProtectedPath(path string) bool {
|
||||
return len(path) > len(protectedPrefix) && strings.EqualFold(path[:len(protectedPrefix)], protectedPrefix)
|
||||
}
|
||||
|
||||
// isAdministrator says whether this process holds Administrators as an enabled group,
|
||||
// which is what creating under protectedPrefix takes. SYSTEM holds it; an elevated
|
||||
// administrator holds it; an administrator's unelevated token carries it deny-only,
|
||||
// which the membership check correctly reads as no. The membership is checked against
|
||||
// the thread's own token: CheckTokenMembership wants an impersonation token and makes
|
||||
// one from the primary token when handed none. A check that cannot be made is read as
|
||||
// not an administrator, which only changes the wording of a failure that has already
|
||||
// happened.
|
||||
func isAdministrator() bool {
|
||||
admins, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
member, err := windows.Token(0).IsMember(admins)
|
||||
return err == nil && member
|
||||
}
|
||||
|
||||
// sddlFor grants full access to the account nebula is running as, to SYSTEM and to
|
||||
// Administrators, and pipeClientAccess to the group acc names, if any; nobody else. P
|
||||
// makes the DACL protected, so it does not inherit entries that would widen it. It is
|
||||
// dockerd's descriptor for its pipe, with its -G group in the same place, except for
|
||||
// the group's mask; see pipeClientAccess.
|
||||
//
|
||||
// Administrators is the counterpart of the uid 0 allowance in the unix peer check. The
|
||||
// service normally runs as LocalSystem, so without it an operator in an elevated shell
|
||||
// could not reach the daemon at all; and an administrator can already stop the service,
|
||||
// so this grants no authority they did not have.
|
||||
func sddlFor(acc Access) (string, error) {
|
||||
token := windows.GetCurrentProcessToken()
|
||||
|
||||
user, err := token.GetTokenUser()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
sddl := fmt.Sprintf("D:P(A;;GA;;;%s)(A;;GA;;;SY)(A;;GA;;;BA)", user.User.Sid.String())
|
||||
if acc.shared() {
|
||||
sddl += fmt.Sprintf("(A;;0x%x;;;%s)", pipeClientAccess, acc.Group.ID)
|
||||
}
|
||||
return sddl, nil
|
||||
}
|
||||
|
||||
// pipeClientAccess is what a client needs on the pipe to talk to the daemon, and all a
|
||||
// configured group is granted: read and write the data, read the pipe's attributes
|
||||
// and its security descriptor, which the owner check needs, and wait on it. Not the
|
||||
// generic rights. On a named pipe GENERIC_WRITE carries FILE_CREATE_PIPE_INSTANCE, the
|
||||
// right to put a second instance under the same name, and a group member with that
|
||||
// could sit on the name and answer other clients in the daemon's place; the client's
|
||||
// owner check would not catch it, since the instance it reached would be the
|
||||
// member's. A client therefore has to ask for exactly this, as dial does, and a
|
||||
// program that opens the info pipe with generic read and write is refused.
|
||||
const pipeClientAccess uint32 = windows.FILE_READ_DATA | windows.FILE_WRITE_DATA |
|
||||
windows.FILE_READ_ATTRIBUTES | windows.READ_CONTROL | windows.SYNCHRONIZE
|
||||
|
||||
// removeSocket is a no-op: a named pipe disappears when its last handle closes, so
|
||||
// there is nothing to unlink and no stale instance to clean up.
|
||||
func removeSocket(path string, id socketID) {}
|
||||
|
||||
// identifySocket has no node to identify: a pipe is its handle, and it cannot be
|
||||
// removed from under the daemon, so an endpoint on its path is always still there.
|
||||
func identifySocket(path string) (socketID, bool) { return socketID{}, true }
|
||||
|
||||
// applyAccess cannot change a pipe's access in place: its security descriptor is fixed
|
||||
// when it is created, so a change means creating it again, which the caller does.
|
||||
func applyAccess(path string, acc Access) error { return errReopenForAccess }
|
||||
|
||||
// dial connects to the pipe and, before the connection carries anything, checks who
|
||||
// serves it. The request names a command and its arguments, so it must not reach a
|
||||
// pipe that some other account put under nebula's name. For the default name the
|
||||
// namespace already promises that, since only an administrator could have created it;
|
||||
// the check is what covers a CtlSocketKey override outside protectedPrefix, and costs
|
||||
// nothing to make on every name.
|
||||
func dial(path string, timeout time.Duration) (net.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
conn, err := winio.DialPipeAccess(ctx, path, pipeClientAccess)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := checkPipeOwner(conn, path); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// checkPipeOwner refuses a pipe whose owner is not an account that could be running
|
||||
// nebula. It is the unix owner check made from the other side: the handle winio dialed
|
||||
// exposes the pipe object, and the object's owner is whoever created it.
|
||||
//
|
||||
// The owner is what makes this sound. An account can only create an object owned by
|
||||
// itself, or by a SID it holds with the owner flag, unless it has SeRestorePrivilege,
|
||||
// which ordinary users do not; so a pipe owned by SYSTEM, Administrators or a service
|
||||
// account was put there by one of them, and never by a user squatting the name. winio
|
||||
// dials with SECURITY_ANONYMOUS, so the impostor could not have impersonated the client
|
||||
// either, but it could have read the command and answered it with whatever it liked.
|
||||
func checkPipeOwner(conn net.Conn, path string) error {
|
||||
h, ok := conn.(interface{ Fd() uintptr })
|
||||
if !ok {
|
||||
return fmt.Errorf("%s: cannot identify who serves the pipe", path)
|
||||
}
|
||||
|
||||
sd, err := windows.GetSecurityInfo(windows.Handle(h.Fd()), windows.SE_KERNEL_OBJECT, windows.OWNER_SECURITY_INFORMATION)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: could not read the pipe's owner: %w", path, err)
|
||||
}
|
||||
|
||||
owner, _, err := sd.Owner()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: could not read the pipe's owner: %w", path, err)
|
||||
}
|
||||
if owner == nil {
|
||||
return fmt.Errorf("%s has no owner; refusing to send to it", path)
|
||||
}
|
||||
|
||||
me, err := windows.GetCurrentProcessToken().GetTokenUser()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: could not read own identity: %w", path, err)
|
||||
}
|
||||
|
||||
if ownerAccepted(owner, me.User.Sid) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s is served by %s, not by nebula; run nebula ctl as that user, or pass -config or -socket to name the daemon's pipe", path, describeSID(owner))
|
||||
}
|
||||
|
||||
// ownerAccepted says whether a pipe owned by owner may be sent a request by a client
|
||||
// running as me: the client's own account, and the two accounts a daemon runs under
|
||||
// that no ordinary user can create an object as, SYSTEM and Administrators. Another
|
||||
// account is refused, whoever the client is; the daemon's DACL decides who may connect,
|
||||
// and this decides who may answer.
|
||||
func ownerAccepted(owner, me *windows.SID) bool {
|
||||
return owner.Equals(me) ||
|
||||
owner.IsWellKnown(windows.WinLocalSystemSid) ||
|
||||
owner.IsWellKnown(windows.WinBuiltinAdministratorsSid)
|
||||
}
|
||||
|
||||
// describeSID renders a SID with its account name when the host can say what it is, so
|
||||
// a message about somebody else's pipe tells the operator who that is.
|
||||
func describeSID(sid *windows.SID) string {
|
||||
account, domain, _, err := sid.LookupAccount("")
|
||||
if err != nil || account == "" {
|
||||
return sid.String()
|
||||
}
|
||||
if domain == "" {
|
||||
return account
|
||||
}
|
||||
return domain + `\` + account
|
||||
}
|
||||
|
||||
// DefaultSocketPath is the control pipe when the config names none. It is under
|
||||
// protectedPrefix, so whatever answers it was created by an administrator or SYSTEM; see
|
||||
// there.
|
||||
const DefaultSocketPath = protectedPrefix + "nebula-ctl"
|
||||
|
||||
// checkSocketPath refuses a configured name that is not a full pipe name. A pipe lives
|
||||
// under pipePrefix and nowhere else, so a bare name has no meaning here, and one under
|
||||
// pipePrefix is used as given. An override outside protectedPrefix is a name any
|
||||
// account could have created first; the owner check in dial is what protects a client
|
||||
// of one.
|
||||
// unprotectedNameWarning says what a pipe name outside protectedPrefix costs, or "" for
|
||||
// one under it. A program reading the info API opens the pipe by name and has no owner
|
||||
// check of its own, so for a name any local user could create first, whoever did
|
||||
// would be answering its queries; the daemon refuses to serve a held name and logs it,
|
||||
// but the program cannot tell. The default control pipe is under the prefix; an info
|
||||
// pipe is wherever the operator put it.
|
||||
func unprotectedNameWarning(path string) string {
|
||||
if len(path) >= len(protectedPrefix) && strings.EqualFold(path[:len(protectedPrefix)], protectedPrefix) {
|
||||
return ""
|
||||
}
|
||||
return "any local user can create a pipe by this name ahead of the daemon and answer in its place; name it under " + protectedPrefix
|
||||
}
|
||||
|
||||
func checkSocketPath(key, value string) error {
|
||||
if len(value) <= len(pipePrefix) || !strings.EqualFold(value[:len(pipePrefix)], pipePrefix) {
|
||||
return fmt.Errorf(`%s must be a full pipe name under %s, got %q`, key, pipePrefix, value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// TestOwnerAccepted pins which accounts may answer a nebula ctl request: the client's
|
||||
// own, and the accounts a daemon runs as that an ordinary user cannot create an object
|
||||
// owned by. Any other user is refused, since any user can create any pipe name.
|
||||
func TestOwnerAccepted(t *testing.T) {
|
||||
me, err := windows.GetCurrentProcessToken().GetTokenUser()
|
||||
require.NoError(t, err)
|
||||
|
||||
wellKnown := func(typ windows.WELL_KNOWN_SID_TYPE) *windows.SID {
|
||||
sid, err := windows.CreateWellKnownSid(typ)
|
||||
require.NoError(t, err)
|
||||
return sid
|
||||
}
|
||||
parse := func(s string) *windows.SID {
|
||||
sid, err := windows.StringToSid(s)
|
||||
require.NoError(t, err)
|
||||
return sid
|
||||
}
|
||||
|
||||
accepted := map[string]*windows.SID{
|
||||
"self": me.User.Sid,
|
||||
"SYSTEM": wellKnown(windows.WinLocalSystemSid),
|
||||
"Administrators": wellKnown(windows.WinBuiltinAdministratorsSid),
|
||||
}
|
||||
for name, sid := range accepted {
|
||||
assert.True(t, ownerAccepted(sid, me.User.Sid), name)
|
||||
}
|
||||
|
||||
refused := map[string]*windows.SID{
|
||||
"Everyone": wellKnown(windows.WinWorldSid),
|
||||
"Users": wellKnown(windows.WinBuiltinUsersSid),
|
||||
"another user": parse("S-1-5-21-1-2-3-1001"),
|
||||
"a service's own account": parse("S-1-5-80-1-2-3-4-5"),
|
||||
"LocalService": wellKnown(windows.WinLocalServiceSid),
|
||||
}
|
||||
for name, sid := range refused {
|
||||
assert.False(t, ownerAccepted(sid, me.User.Sid), name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultPathIsProtected pins the default name to the namespace only administrators
|
||||
// and SYSTEM can create under, which is what lets nebula ctl trust the default name
|
||||
// from its spelling alone.
|
||||
func TestDefaultPathIsProtected(t *testing.T) {
|
||||
p := DefaultSocketPath
|
||||
assert.True(t, isProtectedPath(p), p)
|
||||
assert.Equal(t, `\\.\pipe\ProtectedPrefix\Administrators\nebula-ctl`, p)
|
||||
}
|
||||
|
||||
// TestConfiguredPipeNameMustBeFull: a configured name is used as given, and only a full
|
||||
// pipe name means anything here.
|
||||
func TestConfiguredPipeNameMustBeFull(t *testing.T) {
|
||||
p, err := SocketPathFromConfig(fakeWinConfig{CtlSocketKey: `\\.\pipe\nebula-ctl`})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `\\.\pipe\nebula-ctl`, p)
|
||||
|
||||
for _, bad := range []string{"nebula-ctl", `C:\nebula\ctl.sock`, `\\.\pipe\`} {
|
||||
_, err := SocketPathFromConfig(fakeWinConfig{CtlSocketKey: bad})
|
||||
require.Error(t, err, bad)
|
||||
assert.ErrorContains(t, err, "full pipe name", bad)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeWinConfig map[string]string
|
||||
|
||||
func (f fakeWinConfig) GetString(k, d string) string {
|
||||
if v, ok := f[k]; ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func TestIsProtectedPath(t *testing.T) {
|
||||
assert.True(t, isProtectedPath(`\\.\pipe\ProtectedPrefix\Administrators\nebula-1`))
|
||||
assert.True(t, isProtectedPath(`\\.\pipe\protectedprefix\administrators\nebula-1`), "pipe names are case insensitive")
|
||||
assert.False(t, isProtectedPath(`\\.\pipe\ProtectedPrefix\Administrators\`), "the prefix alone names nothing")
|
||||
assert.False(t, isProtectedPath(`\\.\pipe\nebula-1`))
|
||||
assert.False(t, isProtectedPath(`\\.\pipe\ProtectedPrefix\Users\nebula-1`))
|
||||
}
|
||||
|
||||
// TestListenRefused pins how a failed create is reported. Access denied under the
|
||||
// protected prefix is the namespace refusing a non-administrator, and says so; the same
|
||||
// error for an administrator, or for any name outside the prefix, is a name some other
|
||||
// process holds, and is errEndpointHeld so the daemon logs it as an error.
|
||||
func TestListenRefused(t *testing.T) {
|
||||
protected := `\\.\pipe\ProtectedPrefix\Administrators\nebula-1`
|
||||
plain := `\\.\pipe\nebula-1`
|
||||
|
||||
err := listenRefused(protected, false, windows.ERROR_ACCESS_DENIED)
|
||||
assert.NotErrorIs(t, err, errEndpointHeld)
|
||||
assert.ErrorIs(t, err, windows.ERROR_ACCESS_DENIED)
|
||||
assert.Contains(t, err.Error(), "requires an administrator")
|
||||
assert.Contains(t, err.Error(), CtlSocketKey)
|
||||
|
||||
assert.ErrorIs(t, listenRefused(protected, true, windows.ERROR_ACCESS_DENIED), errEndpointHeld)
|
||||
assert.ErrorIs(t, listenRefused(plain, false, windows.ERROR_ACCESS_DENIED), errEndpointHeld)
|
||||
assert.ErrorIs(t, listenRefused(protected, false, windows.ERROR_ALREADY_EXISTS), errEndpointHeld)
|
||||
assert.ErrorIs(t, listenRefused(plain, true, windows.ERROR_ALREADY_EXISTS), errEndpointHeld)
|
||||
|
||||
other := errors.New("something else")
|
||||
assert.Same(t, other, listenRefused(protected, false, other))
|
||||
}
|
||||
|
||||
// TestListenProtectedName creates and dials a name under the protected prefix. It needs
|
||||
// an administrator, and otherwise checks only that the refusal is the one listen
|
||||
// promises a non-administrator.
|
||||
func TestListenProtectedName(t *testing.T) {
|
||||
path := protectedPrefix + "nebula-test-" + t.Name()
|
||||
ln, err := listen(path, ownerOnly())
|
||||
if !isAdministrator() {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "requires an administrator")
|
||||
t.Skip("not an administrator; the protected namespace refused the create as it should")
|
||||
}
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { ln.Close() })
|
||||
|
||||
accepted := make(chan error, 1)
|
||||
go func() {
|
||||
conn, err := ln.Accept()
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
}
|
||||
accepted <- err
|
||||
}()
|
||||
|
||||
conn, err := dial(path, time.Second)
|
||||
require.NoError(t, err)
|
||||
conn.Close()
|
||||
require.NoError(t, <-accepted)
|
||||
}
|
||||
|
||||
// TestDialAcceptsOwnPipe dials a pipe this process created outside the protected
|
||||
// prefix, as an override might name, which the owner check must pass: the pipe's owner
|
||||
// is this account, or Administrators when the test is elevated.
|
||||
func TestDialAcceptsOwnPipe(t *testing.T) {
|
||||
path := pipePrefix + "nebula-test-" + t.Name()
|
||||
ln, err := listen(path, ownerOnly())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { ln.Close() })
|
||||
|
||||
accepted := make(chan error, 1)
|
||||
go func() {
|
||||
conn, err := ln.Accept()
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
}
|
||||
accepted <- err
|
||||
}()
|
||||
|
||||
conn, err := dial(path, time.Second)
|
||||
require.NoError(t, err)
|
||||
conn.Close()
|
||||
require.NoError(t, <-accepted)
|
||||
}
|
||||
|
||||
// TestListenRefusesHeldName pins that a name another listener already holds is refused
|
||||
// with errEndpointHeld rather than joined, which is what keeps an impostor from being
|
||||
// served alongside, or in place of, the daemon.
|
||||
func TestListenRefusesHeldName(t *testing.T) {
|
||||
path := pipePrefix + "nebula-test-" + t.Name()
|
||||
first, err := listen(path, ownerOnly())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { first.Close() })
|
||||
|
||||
var second net.Listener
|
||||
second, err = listen(path, ownerOnly())
|
||||
if second != nil {
|
||||
second.Close()
|
||||
}
|
||||
require.ErrorIs(t, err, errEndpointHeld)
|
||||
}
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user