mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 04:36:52 +01:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92c67a52b2 | ||
|
|
0f767ce529 | ||
|
|
9a5bdb508e | ||
|
|
48ba879198 | ||
|
|
fb2c153dfa | ||
|
|
f552cebc51 | ||
|
|
b04d71d96a | ||
|
|
cacfa8fac4 | ||
|
|
8a4bd8b10f | ||
|
|
b426843f88 | ||
|
|
cda3710d5a | ||
|
|
c26871fe08 | ||
|
|
7daacc6a48 | ||
|
|
428dad94b3 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Goldens are compared byte for byte, so they must come out of git the way they went in.
|
||||
*.golden -text
|
||||
@@ -7,6 +7,11 @@ 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.
|
||||
|
||||
### Removed
|
||||
|
||||
- The SSH debug server's `start-cpu-profile`, `stop-cpu-profile`, `save-heap-profile`, `save-mutex-profile`, and
|
||||
@@ -14,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Fixed
|
||||
|
||||
- Signing a v2 certificate with an empty name, a name longer than 253 bytes, or an empty group now fails.
|
||||
These certificates were signed successfully but could not be loaded.
|
||||
- `create-tunnel -address <ip:port>` panicked on a nil RemoteList and, over the ssh debug server, took nebula
|
||||
down with it. A hostinfo returned by StartHandshake had no RemoteList until the handshake loop's first
|
||||
pass attached one, and `create-tunnel -address` set the remote before that. The list is now attached when
|
||||
|
||||
+10
-1
@@ -389,7 +389,16 @@ func (c *certificateV2) fromTBSCertificate(t *TBSCertificate) error {
|
||||
}
|
||||
|
||||
func (c *certificateV2) validate() error {
|
||||
// Empty names are allowed
|
||||
// Mirror the name and group rules in unmarshalDetails so signing fails instead of producing an unparseable certificate
|
||||
if c.details.name == "" || len(c.details.name) > MaxNameLength {
|
||||
return NewErrInvalidCertificateProperties("name must be between 1 and %d bytes", MaxNameLength)
|
||||
}
|
||||
|
||||
for _, group := range c.details.groups {
|
||||
if group == "" {
|
||||
return NewErrInvalidCertificateProperties("groups may not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
if len(c.publicKey) == 0 {
|
||||
return ErrInvalidPublicKey
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -135,3 +136,47 @@ 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)
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//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,7 +8,9 @@ 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"
|
||||
)
|
||||
@@ -32,6 +34,11 @@ 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")
|
||||
@@ -40,6 +47,12 @@ 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)
|
||||
@@ -104,9 +117,17 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctl := localapi.Wire(ctrl.Context(), l, c, ctrl.Commands())
|
||||
|
||||
go ctrl.ShutdownBlock()
|
||||
|
||||
if err := ctrl.Wait(); err != nil {
|
||||
err := ctrl.Wait()
|
||||
|
||||
// os.Exit skips deferred calls, so the socket is removed here, before either exit
|
||||
// below, rather than left to a deferred Stop that would never run.
|
||||
ctl.Stop()
|
||||
|
||||
if err != nil {
|
||||
l.Error("Nebula stopped due to fatal error", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/kardianos/service"
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/localapi"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
)
|
||||
|
||||
@@ -17,6 +18,7 @@ type program struct {
|
||||
configPath *string
|
||||
build string
|
||||
control *nebula.Control
|
||||
ctl *localapi.Server
|
||||
}
|
||||
|
||||
func (p *program) Start(s service.Service) error {
|
||||
@@ -50,10 +52,16 @@ func (p *program) Start(s service.Service) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Now that we're started, stand up the local control socket.
|
||||
p.ctl = 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 socket's own context watcher,
|
||||
// so the socket is removed here, as cmd/nebula does.
|
||||
p.ctl.Stop()
|
||||
os.Exit(2)
|
||||
}
|
||||
}()
|
||||
@@ -63,6 +71,11 @@ func (p *program) Start(s service.Service) error {
|
||||
|
||||
func (p *program) Stop(s service.Service) error {
|
||||
logger.Info("Nebula service stopping.")
|
||||
|
||||
if p.ctl != nil {
|
||||
p.ctl.Stop()
|
||||
}
|
||||
|
||||
if p.control == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
+22
-1
@@ -8,7 +8,9 @@ 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"
|
||||
)
|
||||
@@ -32,6 +34,11 @@ 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")
|
||||
@@ -39,6 +46,12 @@ 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)
|
||||
@@ -90,10 +103,18 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctl := localapi.Wire(ctrl.Context(), l, c, ctrl.Commands())
|
||||
|
||||
go ctrl.ShutdownBlock()
|
||||
notifyReady(l)
|
||||
|
||||
if err := ctrl.Wait(); err != nil {
|
||||
err := ctrl.Wait()
|
||||
|
||||
// os.Exit skips deferred calls, so the socket is removed here, before either exit
|
||||
// below, rather than left to a deferred Stop that would never run.
|
||||
ctl.Stop()
|
||||
|
||||
if err != nil {
|
||||
l.Error("Nebula stopped due to fatal error", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
+624
@@ -0,0 +1,624 @@
|
||||
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
|
||||
}
|
||||
|
||||
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",
|
||||
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")
|
||||
}, func(s *printCertFlags, a []string) (commands.Result, error) {
|
||||
return runPrintCert(f, s, a)
|
||||
}))
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func runPrintCert(ifce *Interface, args *printCertFlags, a []string) (commands.Result, error) {
|
||||
|
||||
c := ifce.pki.getCertState().GetDefaultCertificate()
|
||||
if len(a) > 0 {
|
||||
hostInfo, res, ok := tunnelOperand(ifce, a, "vpn addr")
|
||||
if !ok {
|
||||
return res, nil
|
||||
}
|
||||
// A tunnel still handshaking, or one being torn down, has no certificate.
|
||||
cc := hostInfo.GetCert()
|
||||
if cc == nil {
|
||||
return commands.Failed("Could not find tunnel for vpn addr: %v", a[0]), nil
|
||||
}
|
||||
c = cc.Certificate
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
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
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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")))
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package commands
|
||||
|
||||
// Name identifies a command. Every command nebula serves is a constant here, so a
|
||||
// surface, a client and a test spell it the same way and are told at compile time when
|
||||
// they do not. It is a string rather than an integer so a test can register a throwaway
|
||||
// command without adding it here, and so the wire carries the name as the string it has
|
||||
// always been.
|
||||
type Name string
|
||||
|
||||
const (
|
||||
ChangeRemote Name = "change-remote"
|
||||
CloseTunnel Name = "close-tunnel"
|
||||
CreateTunnel Name = "create-tunnel"
|
||||
DeviceInfo Name = "device-info"
|
||||
Help Name = "help"
|
||||
ListHostmap Name = "list-hostmap"
|
||||
ListLighthouseAddrmap Name = "list-lighthouse-addrmap"
|
||||
ListPendingHostmap Name = "list-pending-hostmap"
|
||||
LogFormat Name = "log-format"
|
||||
LogLevel Name = "log-level"
|
||||
Logout Name = "logout"
|
||||
PrintCert Name = "print-cert"
|
||||
PrintRelays Name = "print-relays"
|
||||
PrintTunnel Name = "print-tunnel"
|
||||
QueryLighthouse Name = "query-lighthouse"
|
||||
Reload Name = "reload"
|
||||
Version Name = "version"
|
||||
)
|
||||
@@ -0,0 +1,428 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/anmitsu/go-shlex"
|
||||
)
|
||||
|
||||
// Registry holds a set of commands.
|
||||
//
|
||||
// It is safe for concurrent use. Commands may be registered while surfaces are serving
|
||||
// from the registry: the ssh server clones it per session and the control socket filters
|
||||
// it per request, and either may overlap a Register.
|
||||
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
|
||||
}
|
||||
|
||||
if c := r.Get(Name(args[0])); c != nil {
|
||||
return Value(r.schemaFor(c)), nil
|
||||
}
|
||||
|
||||
if err := r.unavailable(Name(args[0])); err != nil {
|
||||
return Failed("%s", err), nil
|
||||
}
|
||||
|
||||
return Failed("Command not available %s", args[0]), 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 := r.Get(Name(args[0]))
|
||||
if c == nil {
|
||||
if err := r.unavailable(Name(args[0])); err != nil {
|
||||
// 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 fmt.Errorf("%s is not available on this surface: %s", c.Name, reason)
|
||||
}
|
||||
|
||||
// Resolve returns the command registered under name, or says why there is none: the
|
||||
// filter's reason for one this surface withholds, 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)
|
||||
}
|
||||
|
||||
// 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 fmt.Errorf("%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 fmt.Errorf("%s takes no parameters", name)
|
||||
}
|
||||
return fmt.Errorf("%s has no parameter %q", name, k)
|
||||
}
|
||||
|
||||
v := params[k]
|
||||
if err := fl.Set(k, v); err != nil {
|
||||
if IsBoolFlag(f) {
|
||||
// The flag package's own words for this are "parse error".
|
||||
return fmt.Errorf("%s: expected a boolean, got %q", k, v)
|
||||
}
|
||||
return fmt.Errorf("%s: %w", k, 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"`
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
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")
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
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
|
||||
}
|
||||
|
||||
// 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...)}}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
names := slices.Sorted(maps.Keys(req.Params))
|
||||
|
||||
fl, fs, own := commandFlags(c)
|
||||
if err := setParams(fl, string(c.Name), names, req.Params, own); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
return c.Run(fs, req.Args)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
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])
|
||||
}
|
||||
|
||||
// TestResolveTellsUnknownFromWithheld: the two cases read differently to an operator,
|
||||
// and Resolve is the edge that decides which one a name from the wire is.
|
||||
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")
|
||||
require.ErrorContains(t, err, "withheld is not available on this surface")
|
||||
|
||||
_, err = r.Resolve("no-such-command")
|
||||
require.ErrorContains(t, err, `unknown command "no-such-command"`)
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
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"`)
|
||||
}
|
||||
|
||||
// tunnelFixture is an Interface with our own certificate loaded, one peer behind an
|
||||
// established tunnel and one still handshaking, which has no certificate yet.
|
||||
func tunnelFixture(t *testing.T) *Interface {
|
||||
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}, nil, []string{"web", "db"})
|
||||
|
||||
hm := newHostMap(l)
|
||||
hm.Hosts[peer.Addr()] = &HostInfo{
|
||||
vpnAddrs: []netip.Addr{peer.Addr()},
|
||||
ConnectionState: &ConnectionState{peerCert: &cert.CachedCertificate{Certificate: peerCert}},
|
||||
}
|
||||
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}
|
||||
}
|
||||
|
||||
// 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 := tunnelFixture(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")
|
||||
}
|
||||
+34
-1
@@ -32,6 +32,11 @@ type C struct {
|
||||
|
||||
// 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 {
|
||||
@@ -78,14 +83,42 @@ func (c *C) LoadString(raw string) error {
|
||||
// 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()
|
||||
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.
|
||||
@@ -189,7 +222,7 @@ func (c *C) ReloadConfigString(raw string) ReloadResult {
|
||||
|
||||
func (c *C) runCallbacks() ReloadResult {
|
||||
r := &Reload{c: c}
|
||||
for _, v := range c.callbacks {
|
||||
for _, v := range c.reloadCallbacks() {
|
||||
v(c, r)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package config
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -220,3 +221,41 @@ 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
-10
@@ -14,9 +14,6 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// ReplayWindow is the build-time receive window and the assumed peer window
|
||||
// for TX reservation credit. Use a power of two; peers must match or have a
|
||||
// larger receive window. The bitmap costs ReplayWindow/8 bytes per tunnel.
|
||||
ReplayWindow = 8192
|
||||
|
||||
// RehandshakeAfterMessages rolls keys inside the AES-GCM data-volume margin (~2^-36 advantage at 64KB frames).
|
||||
@@ -44,7 +41,6 @@ type ConnectionState struct {
|
||||
peerCert *cert.CachedCertificate
|
||||
initiator bool
|
||||
messageCounter atomic.Uint64
|
||||
txBudget txBudget
|
||||
window *Bits
|
||||
decryptLock sync.Mutex
|
||||
writeLock sync.Mutex
|
||||
@@ -108,7 +104,7 @@ func (cs *ConnectionState) Decrypt(l *slog.Logger, messageCounter uint64, packet
|
||||
return nil, ErrAlreadySeen
|
||||
}
|
||||
|
||||
out, err := cs.decryptPacket(messageCounter, packet, nb)
|
||||
out, err := cs.dKey.DecryptDanger(packet[header.Len:header.Len], packet[:header.Len], packet[header.Len:], messageCounter, nb)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -122,11 +118,6 @@ func (cs *ConnectionState) Decrypt(l *slog.Logger, messageCounter uint64, packet
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// decryptPacket authenticates and decrypts packet in place, leaving the replay window to the caller.
|
||||
func (cs *ConnectionState) decryptPacket(messageCounter uint64, packet, nb []byte) ([]byte, error) {
|
||||
return cs.dKey.DecryptDanger(packet[header.Len:header.Len], packet[:header.Len], packet[header.Len:], messageCounter, nb)
|
||||
}
|
||||
|
||||
func (cs *ConnectionState) VerifyRelay(l *slog.Logger, messageCounter uint64, packet []byte, nb []byte) error {
|
||||
cs.decryptLock.Lock()
|
||||
result := cs.window.Check(l, messageCounter)
|
||||
|
||||
@@ -23,20 +23,11 @@ import (
|
||||
// runTestHandshake runs a complete IX handshake between two freshly-built
|
||||
// peers and returns the initiator and responder Results. Used to produce
|
||||
// real cipher states for tests that need to exercise post-handshake glue.
|
||||
func runTestHandshake(t testing.TB) (initR, respR *handshake.Result) {
|
||||
t.Helper()
|
||||
return runTestHandshakeWith(t, noise.CipherChaChaPoly)
|
||||
}
|
||||
|
||||
// runTestHandshakeWith is runTestHandshake with the data plane cipher picked by the caller.
|
||||
func runTestHandshakeWith(t testing.TB, cipher noise.CipherFunc) (initR, respR *handshake.Result) {
|
||||
func runTestHandshake(t *testing.T) (initR, respR *handshake.Result) {
|
||||
t.Helper()
|
||||
|
||||
// Valid around now rather than the cert_test default, which is fixed at process start and lapses a minute
|
||||
// later, inside a long -count run
|
||||
now := time.Now()
|
||||
ca, _, caKey, _ := ct.NewTestCaCert(
|
||||
cert.Version2, cert.Curve_CURVE25519, now.Add(-time.Minute), now.Add(time.Hour), nil, nil, nil,
|
||||
cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil,
|
||||
)
|
||||
caPool := ct.NewTestCAPool(ca)
|
||||
|
||||
@@ -49,7 +40,7 @@ func runTestHandshakeWith(t testing.TB, cipher noise.CipherFunc) (initR, respR *
|
||||
require.NoError(t, err)
|
||||
hsBytes, err := c.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
ncs := noise.NewCipherSuite(noise.DH25519, cipher, noise.HashSHA256)
|
||||
ncs := noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashSHA256)
|
||||
cred := handshake.NewCredential(c, hsBytes, priv, ncs)
|
||||
return func(v cert.Version) *handshake.Credential {
|
||||
if v == cert.Version2 {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/overlay"
|
||||
)
|
||||
@@ -47,6 +48,7 @@ type Control struct {
|
||||
|
||||
f *Interface
|
||||
l *slog.Logger
|
||||
commands *commands.Registry
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
sshStart func()
|
||||
@@ -372,6 +374,13 @@ 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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//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"}},
|
||||
{"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())
|
||||
}
|
||||
Vendored
+1110
File diff suppressed because it is too large.
Load diff
@@ -5,11 +5,9 @@ package e2e
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/e2e/router"
|
||||
@@ -572,30 +570,3 @@ func TestCloseTunnelAuthenticated(t *testing.T) {
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestStagedTunnel completes a handshake and traffic both ways with staged receive. The test tun cannot hand off
|
||||
// batches, so transmit stays inline; every received packet, handshakes included, uses the receive pipeline on Linux.
|
||||
// Other platforms must do the same over the inline fallback.
|
||||
func TestStagedTunnel(t *testing.T) {
|
||||
t.Parallel()
|
||||
received := metrics.GetOrRegisterCounter("flow.rx.inline", nil)
|
||||
before := received.Count()
|
||||
staged := m{"tun": m{"staged": m{"workers": 2}}}
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
myControl, myVpnIpNet, myUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "me", "10.128.0.1/24", staged)
|
||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "them", "10.128.0.2/24", staged)
|
||||
myControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||
theirControl.InjectLightHouseAddr(myVpnIpNet[0].Addr(), myUdpAddr)
|
||||
myControl.Start()
|
||||
theirControl.Start()
|
||||
r := router.NewR(t, myControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
assertTunnel(t, myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), myControl, theirControl, r)
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
if runtime.GOOS != "linux" {
|
||||
assert.Zero(t, received.Count()-before)
|
||||
return
|
||||
}
|
||||
assert.GreaterOrEqual(t, received.Count()-before, int64(2))
|
||||
}
|
||||
+24
-36
@@ -234,6 +234,26 @@ punchy:
|
||||
#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
|
||||
|
||||
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
||||
relay:
|
||||
# Relays are a list of Nebula IP's that peers can use to relay packets to me.
|
||||
@@ -275,42 +295,9 @@ tun:
|
||||
# the use_offloads setting controls if Nebula will attempt to enable GSO and GRO for the tun device. Linux only, not reloadable.
|
||||
#use_offloads: false
|
||||
|
||||
# Linux only. staged.workers enables staged packet processing: each routine hands its batches to this many crypto
|
||||
# workers per direction, then sends or writes them in order. 0, the default, keeps processing inline. Not reloadable.
|
||||
# Transmit needs use_offloads; BoringCrypto and FIPS builds keep it inline because AES-GCM there needs ordered nonces.
|
||||
# Receive needs a listener that can hand off its batches, which Linux has.
|
||||
# IMPORTANT: staged senders require peers with at least the 8192-entry replay window of this release. Released
|
||||
# v1.11.x peers use 1024 and are incompatible. The window is not negotiated.
|
||||
# Staged reservations may use half the window, the other half absorbs inline and control traffic, relay forwarding
|
||||
# and network reordering; unlimited forwarding or delay can still exceed it. Waiting for credit on a busy tunnel
|
||||
# also delays the other tunnels of the same read, and readers are not guaranteed fairness.
|
||||
# Small batches, below inline_below TX segments or RX packets (default 256), can skip the workers. On transmit each
|
||||
# routine holds one mode, inline on the reader or fanout to the workers and the ordered sender, and switches only
|
||||
# after gate_hold (default 64) reads in a row want the other one. Before going inline it waits for every batch in
|
||||
# flight to be submitted to the socket; flow.tx.gate_switches counts the switches. This does not drain NIC queues.
|
||||
# Relay data always stays on the reader, so gate switches and oversized reads cannot move it between NIC queues.
|
||||
# Direct data retains the adaptive gate and independent sender placement.
|
||||
# On receive a listener with nothing in flight writes a small batch itself. With multiple routines, inline sends
|
||||
# still take tunnel reservation credit. 0 hands direct TX and all RX batches to the workers and ordered stages;
|
||||
# relayed TX and reads too large for a tunnel's whole credit are still sent by the reader.
|
||||
# tx: false keeps transmit inline and stages only receive.
|
||||
# tx_slots and rx_slots bound the batches each routine has in flight per direction, minimum 2. A TX slot holds one
|
||||
# tun read and its ciphertext, about 1.1 MiB; the default is 8, or workers + 2 if more. An RX slot holds one
|
||||
# recvmmsg batch, listen.batch * 64 KiB with udp_offloads or * 9 KiB without; the default keeps up to 384 receive
|
||||
# entries in flight in 4 to 6 slots: 6 slots or 24 MiB at the default listen.batch of 64. Lower them to save memory.
|
||||
#staged:
|
||||
# workers: 0
|
||||
# tx: true
|
||||
# inline_below: 256
|
||||
# gate_hold: 64
|
||||
# tx_slots: 8
|
||||
# rx_slots: 6
|
||||
|
||||
# Linux only. pin_threads pins each tun reader/encrypt OS thread to a single CPU. This keeps every goroutine's
|
||||
# batched sends flowing through one XPS-selected NIC TX ring, so packets within a flow stay ordered on the wire
|
||||
# instead of being sprayed across multiple TX rings and reordered. Not reloadable. Coerced to false if routines <= 1.
|
||||
# Staged senders are only pinned with an explicit cpu_affinity, see below; otherwise the scheduler places them.
|
||||
# Small batches a reader sends itself can use a different TX ring than its sender.
|
||||
#pin_threads: true
|
||||
|
||||
# pin_threads_key helps the CPU-auto-selector shuffle which CPUs are chosen for pinning.
|
||||
@@ -320,9 +307,7 @@ tun:
|
||||
|
||||
# Linux only. cpu_affinity overrides which CPUs the tun reader threads pin to: a list of CPU IDs, one per routine
|
||||
# (see the top-level `routines` setting). Lists shorter than `routines` are modulo-cycled across the queues; extra
|
||||
# entries are ignored. Staged sender i pins to entry i+1, modulo-cycled the same way, unless that is its reader's
|
||||
# CPU, as with a one-entry list: a sender never shares its reader's CPU and stays unpinned instead.
|
||||
# IDs must be within the process's allowed CPU set, so this respects taskset / cgroup cpusets;
|
||||
# entries are ignored. IDs must be within the process's allowed CPU set, so this respects taskset / cgroup cpusets;
|
||||
# a non-integer or not-allowed entry disables the override, leaving the default pin selection described below.
|
||||
# Only meaningful while pin_threads is true. Not reloadable.
|
||||
# When unset (or rejected), the default spread prefers performance cores on heterogeneous CPUs (ARM big.LITTLE,
|
||||
@@ -366,6 +351,9 @@ 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
|
||||
|
||||
+21
-3
@@ -66,6 +66,9 @@ type Firewall struct {
|
||||
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
|
||||
@@ -203,11 +206,25 @@ 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,
|
||||
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),
|
||||
tcpTimeout,
|
||||
udpTimeout,
|
||||
defaultTimeout,
|
||||
certificate,
|
||||
//TODO: max_connections
|
||||
)
|
||||
@@ -246,6 +263,7 @@ func NewFirewallFromConfig(l *slog.Logger, cs *CertState, c *config.C) (*Firewal
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fw.source = c.Render("firewall")
|
||||
return fw, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,31 @@ 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)
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
)
|
||||
|
||||
// Staged processing (tun.staged.workers) moves crypto off each tun reader and udp listener onto worker goroutines,
|
||||
// behind which an ordered stage sends or writes every batch in read order. It reuses the inline packet handlers:
|
||||
// staging changes ownership and scheduling, not policy. Each routine has its own workers and ordered stages, so order
|
||||
// is per routine. Full queues block the reader. A read error drains the batches in flight, while shutdown waits for
|
||||
// the crypto and then drops packets whose destination has closed. A TX slot holds one tun read and its ciphertext,
|
||||
// about 1.1 MiB; there are eight, or two more than the workers. An RX slot holds one recvmmsg batch, listen.batch
|
||||
// times 64 KiB with GRO, and the count keeps up to 384 entries in flight in four to six slots: six and 24 MiB at
|
||||
// listen.batch=64.
|
||||
// tun.staged.tx_slots and rx_slots override the counts. Small-MSS TX arenas can grow.
|
||||
// Relay data stays on the tun reader, regardless of the TX gate, so it never switches between reader and sender
|
||||
// NIC queues. Direct data keeps its adaptive placement; relay and direct batches both share tunnel counter credit.
|
||||
//
|
||||
// Metrics are registered only for active pipelines. flow.{tx,rx}.batches counts reads handed to the ordered stage and
|
||||
// flow.{tx,rx}.inline those the reader handled itself (TX inline also counts oversized reads); their rates show
|
||||
// whether staging is used. flow.tx.gate_switches counts transmit switches between inline and fanout mode.
|
||||
|
||||
// stagedConfig is tun.staged. workers is per routine and direction; zero keeps processing inline.
|
||||
type stagedConfig struct {
|
||||
workers int
|
||||
tx bool
|
||||
rx bool
|
||||
// inlineBelow is the TX segment or RX packet count below which a read may skip the worker handoff, 0 never: a TX
|
||||
// read in inline mode, an RX read with nothing in flight
|
||||
inlineBelow int
|
||||
// txSlots and rxSlots are how many batches each routine can have in flight per direction
|
||||
txSlots, rxSlots int
|
||||
// gateHold is how many TX reads in a row must want the other mode before a routine switches between inline and
|
||||
// fanout transmit
|
||||
gateHold int
|
||||
}
|
||||
|
||||
// stagedGateHold is the default tun.staged.gate_hold
|
||||
const stagedGateHold = 64
|
||||
|
||||
const (
|
||||
// stagedTxSlots is the default TX slot count, unless the workers need more
|
||||
stagedTxSlots = 8
|
||||
// stagedRxEntries is how many recvmmsg entries the RX slots hold in flight by default
|
||||
stagedRxEntries = 6 * 64
|
||||
// stagedMinSlots lets the reader fill one batch while another is in flight
|
||||
stagedMinSlots = 2
|
||||
// stagedMinRxSlots keeps the default RX pipeline deep enough for large listen.batch values
|
||||
stagedMinRxSlots = 4
|
||||
// stagedMaxRxSlots is the measured default, a smaller listen.batch does not take more slots
|
||||
stagedMaxRxSlots = 6
|
||||
)
|
||||
|
||||
// stagedSlots sizes the TX and RX slots. TX reads are bounded by the tun queue, so one slot per worker plus the one
|
||||
// being read and the one being sent, and at least the eight measured. RX slots keep stagedRxEntries in flight, four
|
||||
// to six, so a larger listen.batch means fewer slots and RX memory never exceeds the six measured. A positive override replaces either, down to stagedMinSlots.
|
||||
func stagedSlots(workers, batch, txOverride, rxOverride int) (tx, rx int) {
|
||||
tx = max(stagedTxSlots, workers+2)
|
||||
rx = min(max(stagedMinRxSlots, (stagedRxEntries+batch-1)/max(batch, 1)), stagedMaxRxSlots)
|
||||
if txOverride > 0 {
|
||||
tx = max(txOverride, stagedMinSlots)
|
||||
}
|
||||
if rxOverride > 0 {
|
||||
rx = max(rxOverride, stagedMinSlots)
|
||||
}
|
||||
return tx, rx
|
||||
}
|
||||
|
||||
// parseStagedConfig enables staging on Linux only; queues and conns that cannot hand off batches also stay inline.
|
||||
func parseStagedConfig(c *config.C, l *slog.Logger) stagedConfig {
|
||||
sc := stagedConfig{workers: c.GetInt("tun.staged.workers", 0)}
|
||||
if sc.workers <= 0 {
|
||||
return stagedConfig{}
|
||||
}
|
||||
if runtime.GOOS != "linux" {
|
||||
l.Warn("tun.staged is only supported on Linux; packet processing stays inline")
|
||||
return stagedConfig{}
|
||||
}
|
||||
sc.tx, sc.rx = c.GetBool("tun.staged.tx", true), true
|
||||
// 256 is the measured crossover, 0 hands every batch to the workers
|
||||
sc.inlineBelow = max(c.GetInt("tun.staged.inline_below", 256), 0)
|
||||
if sc.tx && noiseutil.EncryptLockNeeded {
|
||||
l.Warn("tun.staged cannot encrypt in parallel with boringcrypto or fips140; transmit stays inline")
|
||||
sc.tx = false
|
||||
}
|
||||
sc.gateHold = max(c.GetInt("tun.staged.gate_hold", stagedGateHold), 1)
|
||||
sc.txSlots, sc.rxSlots = stagedSlots(sc.workers, c.GetInt("listen.batch", 64),
|
||||
c.GetInt("tun.staged.tx_slots", 0), c.GetInt("tun.staged.rx_slots", 0))
|
||||
l.Info("Staged packet processing enabled", "workers", sc.workers, "tx", sc.tx, "rx", sc.rx,
|
||||
"inlineBelow", sc.inlineBelow, "gateHold", sc.gateHold,
|
||||
"txSlots", sc.txSlots, "rxSlots", sc.rxSlots)
|
||||
return sc
|
||||
}
|
||||
|
||||
// flowJob is one batch of crypto work. It owns its packet buffers until run returns; jobs and queues are reused.
|
||||
type flowJob interface{ run(nb []byte) }
|
||||
|
||||
// flowPool runs one reader's crypto jobs. The reader is the only producer and closes the pool once its ordered stage
|
||||
// has drained.
|
||||
type flowPool struct {
|
||||
jobs chan flowJob
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func newFlowPool(workers, queueLen int) *flowPool {
|
||||
p := &flowPool{jobs: make(chan flowJob, queueLen)}
|
||||
for range workers {
|
||||
p.wg.Go(func() {
|
||||
nb := make([]byte, 12)
|
||||
for job := range p.jobs {
|
||||
job.run(nb)
|
||||
}
|
||||
})
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *flowPool) close() { close(p.jobs); p.wg.Wait() }
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
)
|
||||
|
||||
// txBudget is the reservation credit of one tunnel, shared by every staged reader sending on it. The low 24 bits of
|
||||
// state are outstanding counters, the next 24 spent credit, and the top 16 the sole ordered reader (q+1); owner zero
|
||||
// means shared. Readers beyond the owner field's range always take the conservative shared path.
|
||||
//
|
||||
// A cap on outstanding counters alone is not enough: a fast reader could repeatedly send and reacquire credit,
|
||||
// overtaking a paused reader by arbitrarily far. So once readers overlap, or another reader is blocked, spent credit
|
||||
// is only recycled when ALL reservations have drained. A sole reader instead gets each ordered completion refunded,
|
||||
// its later batches cannot overtake its earlier ones. All transitions are one CAS, without locks.
|
||||
//
|
||||
// The credit is half the peer's replay window. The other half is left for uncredited sends and transport reordering:
|
||||
// inline and control traffic, and relay forwarding through SendVia, which takes counters on the relay tunnel without
|
||||
// credit. Unlimited bypass traffic or network delay can still exceed it. The window is not negotiated, so
|
||||
// ci.window.length, from the build-time ReplayWindow, is also the assumed peer window.
|
||||
type txBudget struct{ state atomic.Uint64 }
|
||||
|
||||
const txBudgetMask = uint64(1<<24 - 1)
|
||||
|
||||
// Fail compilation for unsupported build-time windows: a power of two, at least 8192, fitting the credit fields (up
|
||||
// to 16777216).
|
||||
const (
|
||||
_ = uint64(txBudgetMask) - ReplayWindow/2
|
||||
_ = uint64(ReplayWindow) - 8192
|
||||
_ = uint64(0) - (ReplayWindow & (ReplayWindow - 1))
|
||||
)
|
||||
|
||||
func txBudgetOwner(q int) uint64 {
|
||||
if q < 0 || q >= 65535 {
|
||||
return 0
|
||||
}
|
||||
return uint64(q + 1)
|
||||
}
|
||||
|
||||
func (b *txBudget) acquire(n, limit, owner uint64) bool {
|
||||
for {
|
||||
old := b.state.Load()
|
||||
pending, spent, who := old&txBudgetMask, (old>>24)&txBudgetMask, old>>48
|
||||
if n > limit || spent > limit-n {
|
||||
// A blocked reader ends sole ownership so ordered completions stop refunding credit. Otherwise a busy
|
||||
// owner could keep a larger waiter blocked forever without ever sharing a reservation.
|
||||
if who != 0 && who != owner && !b.state.CompareAndSwap(old, old&^(uint64(0xffff)<<48)) {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
if pending == 0 {
|
||||
who = owner
|
||||
} else if who != owner {
|
||||
who = 0
|
||||
}
|
||||
next := who<<48 | (spent+n)<<24 | (pending + n)
|
||||
if b.state.CompareAndSwap(old, next) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// release runs only after the socket flush or an explicit drop. A rollback returns credit before any message counter
|
||||
// was allocated, as when a later tunnel of a relay or multi-tunnel batch could not acquire its own.
|
||||
func (b *txBudget) release(n uint64, rollback bool) {
|
||||
for {
|
||||
old := b.state.Load()
|
||||
pending, spent, owner := old&txBudgetMask, (old>>24)&txBudgetMask, old>>48
|
||||
pending -= n
|
||||
if rollback || owner != 0 {
|
||||
spent -= n
|
||||
}
|
||||
next := owner<<48 | spent<<24 | pending
|
||||
if pending == 0 {
|
||||
next = 0
|
||||
}
|
||||
if b.state.CompareAndSwap(old, next) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ci *ConnectionState) txBudgetLimit() uint64 { return ci.window.length / 2 }
|
||||
|
||||
func (r *txReserver) oversized() bool {
|
||||
for _, t := range r.tunnels {
|
||||
if t.n > t.ci.txBudgetLimit() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *txReserver) tryBudget() bool {
|
||||
for i, t := range r.tunnels {
|
||||
if !t.ci.txBudget.acquire(t.n, t.ci.txBudgetLimit(), r.owner) {
|
||||
for _, acquired := range r.tunnels[:i] {
|
||||
acquired.ci.txBudget.release(acquired.n, true)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// waitBudget acquires credit for every tunnel of the batch, never holding a partial acquisition while it waits. Each
|
||||
// reader first flushes its own oldest batch, flushes need no credit; with none, another reader holds all outstanding
|
||||
// work and can flush it independently. So there is no circular wait, even with relay tunnels acquired in opposite
|
||||
// orders. The sleep is only for readers with no local work, not the uncontended hot path. Acquisition is
|
||||
// all-or-nothing within each direct or relay batch, so pressure on one tunnel also delays packets for idle tunnels
|
||||
// in that batch. Reader fairness is not guaranteed.
|
||||
func (p *stagedTx) waitBudget(r *txReserver) bool {
|
||||
if r.tryBudget() {
|
||||
return true
|
||||
}
|
||||
for {
|
||||
if p.f.closed.Load() {
|
||||
return false
|
||||
}
|
||||
if !p.flushOldest() {
|
||||
time.Sleep(50 * time.Microsecond)
|
||||
}
|
||||
if r.tryBudget() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *txSlot) releaseBudget() {
|
||||
for _, t := range s.reservations {
|
||||
t.ci.txBudget.release(t.n, false)
|
||||
}
|
||||
clear(s.reservations)
|
||||
s.reservations = s.reservations[:0]
|
||||
}
|
||||
|
||||
// sendLarge handles the unusual reads that exceed a whole tunnel's credit, such as tiny-MSS superpackets. It drains
|
||||
// the pipeline, then segments and sends them synchronously with credit for each segment, never exceeding the cap and
|
||||
// never filtering or running connection manager side effects twice. This deliberately slow path avoids a lone-batch
|
||||
// exception to the shared invariant.
|
||||
func (p *stagedTx) sendLarge(r *txReserver, items []txItem) {
|
||||
for p.flushOldest() {
|
||||
}
|
||||
for _, it := range items {
|
||||
err := tio.SegmentSuperpacket(it.pkt, func(seg []byte) error {
|
||||
if p.f.closed.Load() {
|
||||
return nil
|
||||
}
|
||||
part := it
|
||||
part.pkt, part.segs = tio.Packet{Bytes: seg}, 1
|
||||
r.tunnels = r.tunnels[:0]
|
||||
part.counter = r.need(part.hostinfo, part.ci, 1)
|
||||
if part.relayHI != nil {
|
||||
part.relayCounter = r.need(part.relayHI, part.relayHI.ConnectionState, 1)
|
||||
}
|
||||
if !p.waitBudget(r) {
|
||||
return nil
|
||||
}
|
||||
one := [1]txItem{part}
|
||||
if reserved := r.reserve(one[:]); len(reserved) != 0 {
|
||||
p.f.encryptTxItem(&reserved[0], p.nb, p.sb)
|
||||
p.f.flushSendBatch(p.sb, p.q)
|
||||
}
|
||||
for _, t := range r.tunnels {
|
||||
t.ci.txBudget.release(t.n, false)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
it.hostinfo.logger(p.f.l).Error("Failed to segment superpacket for send", "error", err)
|
||||
}
|
||||
}
|
||||
clear(items)
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var budgetWindows = []uint64{8192, 65536}
|
||||
|
||||
// TestTXBudgetOvertaking: a fast sender must not recycle credit around a stalled older reservation. A pure in-flight
|
||||
// count passes the cap assertion but fails this replay test.
|
||||
func TestTXBudgetOvertaking(t *testing.T) {
|
||||
for _, window := range budgetWindows {
|
||||
t.Run(fmt.Sprint(window), func(t *testing.T) {
|
||||
var b txBudget
|
||||
limit := window / 2
|
||||
w := NewBits(window)
|
||||
l := test.NewLogger()
|
||||
require.True(t, b.acquire(1, limit, 1)) // counter 1 stalls
|
||||
for counter := uint64(2); counter <= limit; counter++ {
|
||||
require.True(t, b.acquire(1, limit, 2))
|
||||
require.True(t, w.Update(l, counter))
|
||||
b.release(1, false)
|
||||
}
|
||||
require.Equal(t, uint64(1), b.state.Load()&txBudgetMask)
|
||||
require.False(t, b.acquire(1, limit, 2), "spent credit cannot be recycled while the oldest sender stalls")
|
||||
// The other half of the window allows this many unreserved sends.
|
||||
for counter := limit + 1; counter <= window; counter++ {
|
||||
require.True(t, w.Update(l, counter))
|
||||
}
|
||||
require.True(t, w.Update(l, 1), "oldest reservation must still fit after using the whole margin")
|
||||
b.release(1, false)
|
||||
require.Zero(t, b.state.Load())
|
||||
require.True(t, b.acquire(limit, limit, 2))
|
||||
require.False(t, b.acquire(1, limit, 2))
|
||||
b.release(limit, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTXBudgetBlockedReader models eight 512-segment reads of a busy owner and a 568-segment waiter, without socket
|
||||
// timing. Alone, the owner gets each completion refunded, so it keeps eight batches in flight forever, even across its
|
||||
// own failed acquisitions. But even when the owner always retries first, its completions must stop refunding credit
|
||||
// once the waiter is blocked, and let the budget drain. Waiter 0 is the conservative ID of readers beyond the owner
|
||||
// field's range.
|
||||
func TestTXBudgetBlockedReader(t *testing.T) {
|
||||
for _, waiter := range []uint64{1, 0} {
|
||||
t.Run(fmt.Sprintf("waiter=%d", waiter), func(t *testing.T) {
|
||||
var b txBudget
|
||||
const limit, n, want = uint64(4096), uint64(512), uint64(568)
|
||||
for range 8 {
|
||||
require.True(t, b.acquire(n, limit, 2))
|
||||
}
|
||||
for range 100 {
|
||||
require.False(t, b.acquire(n, limit, 2))
|
||||
b.release(n, false) // the sole sender flushes its oldest batch
|
||||
require.True(t, b.acquire(n, limit, 2))
|
||||
require.Equal(t, 8*n, b.state.Load()&txBudgetMask)
|
||||
}
|
||||
require.False(t, b.acquire(want, limit, waiter))
|
||||
for range 7 {
|
||||
b.release(n, false)
|
||||
require.False(t, b.acquire(n, limit, 2), "blocked reader must stop the owner's credit recycling")
|
||||
require.False(t, b.acquire(want, limit, waiter))
|
||||
}
|
||||
b.release(n, false)
|
||||
require.Zero(t, b.state.Load())
|
||||
// Even if the former owner wins the next acquisition, both now fit.
|
||||
require.True(t, b.acquire(n, limit, 2))
|
||||
require.True(t, b.acquire(want, limit, waiter))
|
||||
b.release(n, false)
|
||||
b.release(want, false)
|
||||
require.Zero(t, b.state.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTXBudgetRelayRollback: when a later tunnel of a batch cannot acquire, the earlier ones give their credit back,
|
||||
// spent credit included.
|
||||
func TestTXBudgetRelayRollback(t *testing.T) {
|
||||
for _, window := range budgetWindows {
|
||||
inner := &ConnectionState{window: NewBits(window)}
|
||||
outer := &ConnectionState{window: NewBits(window)}
|
||||
limit := inner.txBudgetLimit()
|
||||
require.True(t, inner.txBudget.acquire(10, limit, 1))
|
||||
require.True(t, outer.txBudget.acquire(limit, limit, 1))
|
||||
r := txReserver{owner: 2, tunnels: []txTunnel{{ci: inner, n: 20}, {ci: outer, n: 20}}}
|
||||
for range 100 {
|
||||
require.False(t, r.tryBudget())
|
||||
require.Equal(t, uint64(10), inner.txBudget.state.Load()&txBudgetMask)
|
||||
require.Equal(t, uint64(10), (inner.txBudget.state.Load()>>24)&txBudgetMask, "rollback must refund spent credit too")
|
||||
}
|
||||
outer.txBudget.release(limit, false)
|
||||
require.True(t, r.tryBudget())
|
||||
inner.txBudget.release(20, false)
|
||||
outer.txBudget.release(20, false)
|
||||
inner.txBudget.release(10, false)
|
||||
require.Zero(t, inner.txBudget.state.Load())
|
||||
require.Zero(t, outer.txBudget.state.Load())
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
//go:build linux && !android && !e2e_testing
|
||||
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/goleak"
|
||||
)
|
||||
|
||||
// gated is staging with an inline threshold of 4 segments and the given gate hold.
|
||||
func gated(hold int) stagedConfig {
|
||||
sc := adaptive(2)
|
||||
sc.inlineBelow, sc.gateHold = 4, hold
|
||||
return sc
|
||||
}
|
||||
|
||||
// gateCounters snapshots the transmit counters a gate test checks.
|
||||
type gateCounters struct{ inline, batches, switches int64 }
|
||||
|
||||
func readGateCounters() gateCounters {
|
||||
return gateCounters{
|
||||
inline: metrics.GetOrRegisterCounter("flow.tx.inline", nil).Count(),
|
||||
batches: metrics.GetOrRegisterCounter("flow.tx.batches", nil).Count(),
|
||||
switches: metrics.GetOrRegisterCounter("flow.tx.gate_switches", nil).Count(),
|
||||
}
|
||||
}
|
||||
|
||||
func (c gateCounters) since(c0 gateCounters) gateCounters {
|
||||
return gateCounters{c.inline - c0.inline, c.batches - c0.batches, c.switches - c0.switches}
|
||||
}
|
||||
|
||||
// gateReads builds reads of small (3 segments, below the threshold) or large (2 superpackets of 9) shape, in order,
|
||||
// for one flow, and the segments they carry.
|
||||
func gateReads(large ...bool) ([][]tio.Packet, []decodedSeg) {
|
||||
var reads [][]tio.Packet
|
||||
var want []decodedSeg
|
||||
seq := uint32(0)
|
||||
for _, l := range large {
|
||||
per, segs := 1, 3
|
||||
if l {
|
||||
per, segs = 2, 9
|
||||
}
|
||||
var b []tio.Packet
|
||||
for range per {
|
||||
b = append(b, flowTCPSuperpacket(0, seq, segs))
|
||||
for s := range segs {
|
||||
want = append(want, decodedSeg{seq: seq, idx: uint16(s)})
|
||||
}
|
||||
seq++
|
||||
}
|
||||
reads = append(reads, b)
|
||||
}
|
||||
return reads, want
|
||||
}
|
||||
|
||||
func repeatBool(v bool, n int) []bool {
|
||||
out := make([]bool, n)
|
||||
for i := range out {
|
||||
out[i] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestFlowStagedTXGateSwitch forces the gate from inline to fanout and back, with a slow socket and slow
|
||||
// workers so the fanout batches are still in flight when the small reads arrive: wire order is read order, counters
|
||||
// are contiguous, and each switch happens on exactly the gate_hold-th read that wants it.
|
||||
func TestFlowStagedTXGateSwitch(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
const hold = 3
|
||||
for _, routines := range []int{1, 2} {
|
||||
t.Run(fmt.Sprintf("routines=%d", routines), func(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, gated(hold))
|
||||
sender.f.routines = routines
|
||||
sender.f.writers = []udp.Conn{sender.conn, sender.conn}
|
||||
delayCrypto(sender, func(n uint64) {
|
||||
if n%7 == 0 {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
})
|
||||
sender.conn.delay = 4 * time.Millisecond
|
||||
// 4 small inline, 2 large held inline, 6 large fanout from the switch on, 2 small held in fanout, then
|
||||
// the switch back drains and 3 small go inline
|
||||
shape := append(repeatBool(false, 4), repeatBool(true, 8)...)
|
||||
shape = append(shape, repeatBool(false, 5)...)
|
||||
reads, want := gateReads(shape...)
|
||||
ci := sender.hostinfo.ConnectionState
|
||||
start := ci.messageCounter.Load()
|
||||
c0 := readGateCounters()
|
||||
p := newStagedTx(sender.f, newFlowBatchQueue(nil), 0)
|
||||
for i, r := range reads {
|
||||
p.send(r)
|
||||
if i == 13 {
|
||||
require.Positive(t, p.inFlight, "fanout batches must still be in flight when the small reads start")
|
||||
}
|
||||
if i == 14 {
|
||||
require.Zero(t, p.inFlight, "switching to inline drains the pipeline")
|
||||
}
|
||||
}
|
||||
p.close()
|
||||
require.Equal(t, want, decryptWire(t, receiver, sender.conn.captured()), "wire order must match read order")
|
||||
require.Equal(t, start+uint64(len(want)), ci.messageCounter.Load(), "every reserved counter is used once")
|
||||
require.Equal(t, gateCounters{inline: 4 + 2 + 3, batches: 6 + 2, switches: 2}, readGateCounters().since(c0))
|
||||
require.Zero(t, ci.txBudget.state.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedTXGateHold: the gate never switches before gate_hold consecutive reads want the other mode, and
|
||||
// a read that wants the current mode restarts the count.
|
||||
func TestFlowStagedTXGateHold(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
const hold = 5
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, gated(hold))
|
||||
shape := append(repeatBool(true, hold-1), false)
|
||||
shape = append(shape, repeatBool(true, hold-1)...)
|
||||
reads, want := gateReads(append(shape, true)...)
|
||||
c0 := readGateCounters()
|
||||
p := newStagedTx(sender.f, newFlowBatchQueue(nil), 0)
|
||||
for _, r := range reads[:len(reads)-1] {
|
||||
p.send(r)
|
||||
}
|
||||
require.Equal(t, gateCounters{inline: 2*hold - 1}, readGateCounters().since(c0), "no switch before gate_hold")
|
||||
p.send(reads[len(reads)-1])
|
||||
require.Equal(t, gateCounters{inline: 2*hold - 1, batches: 1, switches: 1}, readGateCounters().since(c0))
|
||||
p.close()
|
||||
require.Equal(t, want, decryptWire(t, receiver, sender.conn.captured()))
|
||||
}
|
||||
-371
@@ -1,371 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net/netip"
|
||||
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
)
|
||||
|
||||
// handoffConn is a udp conn that can hand each received batch over. The callback returns replacement buffers with
|
||||
// the same count and at least the same lengths.
|
||||
type handoffConn interface {
|
||||
ListenOutHandoff(udp.EncReader, func([][]byte) [][]byte) error
|
||||
}
|
||||
|
||||
const rxChunkMin = 16
|
||||
|
||||
// rxItem is one received packet. A data packet for an established tunnel has ci set; out and err are written by
|
||||
// whoever decrypts it.
|
||||
type rxItem struct {
|
||||
packet []byte
|
||||
hostinfo *HostInfo
|
||||
ci *ConnectionState
|
||||
counter uint64
|
||||
via netip.AddrPort
|
||||
out []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// rxChunk is a contiguous run of a batch's items for one worker to decrypt.
|
||||
type rxChunk struct {
|
||||
items []rxItem
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func (c *rxChunk) run(nb []byte) {
|
||||
decryptRxItems(c.items, nb)
|
||||
c.done <- struct{}{}
|
||||
}
|
||||
|
||||
// decryptRxItems decrypts the data packets among items in place. The replay window is left to the ordered stage, as
|
||||
// are packets without a tunnel and the known replays precheck marked.
|
||||
func decryptRxItems(items []rxItem, nb []byte) {
|
||||
for i := range items {
|
||||
it := &items[i]
|
||||
if it.ci == nil || it.err != nil {
|
||||
continue
|
||||
}
|
||||
it.out, it.err = it.ci.decryptPacket(it.counter, it.packet, nb)
|
||||
}
|
||||
}
|
||||
|
||||
// rxBatch is one recvmmsg batch moving through the staged receive pipeline.
|
||||
type rxBatch struct {
|
||||
// items is every packet of the batch in arrival order. Data packets are decrypted by a worker; anything else is
|
||||
// handled whole by the writer, in its place.
|
||||
items []rxItem
|
||||
data int
|
||||
// bufs is the set of recvmmsg buffers the items point into, owned by the batch from handoff until it is reused.
|
||||
bufs [][]byte
|
||||
// chunks are the decrypt jobs, nChunks of them in use. With none the writer decrypts the batch itself.
|
||||
chunks []rxChunk
|
||||
nChunks int
|
||||
}
|
||||
|
||||
func (b *rxBatch) reset() {
|
||||
clear(b.items)
|
||||
b.items = b.items[:0]
|
||||
b.data = 0
|
||||
for i := range b.nChunks {
|
||||
b.chunks[i].items = nil
|
||||
}
|
||||
b.nChunks = 0
|
||||
}
|
||||
|
||||
// stagedRx is the staged receive pipeline of one udp listener. deliver and handoff run on the listener goroutine.
|
||||
type stagedRx struct {
|
||||
f *Interface
|
||||
q int
|
||||
pool *flowPool
|
||||
// h and hostmapCache are the listener's own. wrxc is the commit context: the writer's, or the listener's while
|
||||
// nothing is in flight.
|
||||
h *header.H
|
||||
hostmapCache map[uint32]*HostInfo
|
||||
wrxc *rxContext
|
||||
|
||||
cur *rxBatch
|
||||
free []*rxBatch
|
||||
ordered chan *rxBatch
|
||||
returned chan *rxBatch
|
||||
inFlight int
|
||||
writerDone chan struct{}
|
||||
|
||||
metricBatches metrics.Counter
|
||||
metricInline metrics.Counter
|
||||
}
|
||||
|
||||
func newStagedRx(f *Interface, q int, wrxc *rxContext) *stagedRx {
|
||||
p := &stagedRx{
|
||||
f: f,
|
||||
q: q,
|
||||
h: &header.H{},
|
||||
hostmapCache: map[uint32]*HostInfo{},
|
||||
wrxc: wrxc,
|
||||
ordered: make(chan *rxBatch, f.staged.rxSlots),
|
||||
returned: make(chan *rxBatch, f.staged.rxSlots),
|
||||
writerDone: make(chan struct{}),
|
||||
metricBatches: metrics.GetOrRegisterCounter("flow.rx.batches", nil),
|
||||
metricInline: metrics.GetOrRegisterCounter("flow.rx.inline", nil),
|
||||
}
|
||||
workers := f.staged.workers
|
||||
p.pool = newFlowPool(workers, f.staged.rxSlots*2*workers)
|
||||
for range f.staged.rxSlots {
|
||||
// Two chunks per worker, so the writer can start committing while the workers are still on the rest
|
||||
b := &rxBatch{items: make([]rxItem, 0, 256), chunks: make([]rxChunk, 2*workers)}
|
||||
for i := range b.chunks {
|
||||
b.chunks[i].done = make(chan struct{}, 1)
|
||||
}
|
||||
p.free = append(p.free, b)
|
||||
}
|
||||
p.cur = p.free[len(p.free)-1]
|
||||
p.free = p.free[:len(p.free)-1]
|
||||
go p.writer()
|
||||
return p
|
||||
}
|
||||
|
||||
// listen runs the conn's receive loop through the pipeline until it fails, then drains the pipeline. The conn hands
|
||||
// its buffers over, so a batch moves between stages without a copy.
|
||||
func (p *stagedRx) listen(li handoffConn) error {
|
||||
defer p.close()
|
||||
return li.ListenOutHandoff(p.deliver, p.handoff)
|
||||
}
|
||||
|
||||
// deliver is the listener's per-packet work: classify the packet and add it to the current batch. Nothing here
|
||||
// decrypts or touches the tun.
|
||||
func (p *stagedRx) deliver(via netip.AddrPort, packet []byte) {
|
||||
b := p.cur
|
||||
it := rxItem{packet: packet, via: via}
|
||||
p.classify(&it)
|
||||
if it.ci != nil {
|
||||
b.data++
|
||||
}
|
||||
b.items = append(b.items, it)
|
||||
}
|
||||
|
||||
// classify fills in the tunnel for a plain data packet of an established, non-relayed tunnel, leaving anything else
|
||||
// for the writer to handle whole. The replay pre-check waits for the end of the batch, see precheck.
|
||||
func (p *stagedRx) classify(it *rxItem) {
|
||||
f := p.f
|
||||
h := p.h
|
||||
packet := it.packet
|
||||
if h.Parse(packet) != nil || h.Version != header.Version || h.Type != header.Message || h.Subtype != header.MessageNone {
|
||||
return
|
||||
}
|
||||
if f.myVpnNetworksTable.Contains(it.via.Addr()) {
|
||||
return
|
||||
}
|
||||
hostinfo := f.hostMap.QueryIndexCached(h.RemoteIndex, p.hostmapCache)
|
||||
if hostinfo == nil || hostinfo.ConnectionState == nil {
|
||||
return
|
||||
}
|
||||
ci := hostinfo.ConnectionState
|
||||
if len(packet) < header.Len+ci.dKey.Overhead() {
|
||||
return
|
||||
}
|
||||
it.hostinfo, it.ci, it.counter = hostinfo, ci, h.MessageCounter
|
||||
}
|
||||
|
||||
// precheck marks obvious replays before anything decrypts them, like ConnectionState.Decrypt does, taking each
|
||||
// tunnel's lock once per run of its packets rather than once per packet: the writer takes the same lock for its
|
||||
// window updates, from another core. The writer checks again when it commits. The window only moves forward in
|
||||
// between, so a stale check here can only let a replay through to that second check. Marked packets keep their
|
||||
// place: an earlier RecvError may delete their tunnel, and inline receive then replies with a RecvError rather than
|
||||
// dropping a replay.
|
||||
func (p *stagedRx) precheck(b *rxBatch) {
|
||||
f := p.f
|
||||
items := b.items
|
||||
for i := 0; i < len(items); {
|
||||
ci := items[i].ci
|
||||
if ci == nil {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
ci.decryptLock.Lock()
|
||||
for ; i < len(items) && items[i].ci == ci; i++ {
|
||||
if ci.window.Check(f.l, items[i].counter) {
|
||||
continue
|
||||
}
|
||||
b.data--
|
||||
items[i].err = ErrAlreadySeen
|
||||
}
|
||||
ci.decryptLock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// handoff ends a batch: the batch takes bufs, and the conn reads the next batch into the buffers of the next free
|
||||
// batch.
|
||||
func (p *stagedRx) handoff(bufs [][]byte) [][]byte {
|
||||
p.cur.bufs = bufs
|
||||
p.endBatch()
|
||||
b := p.cur
|
||||
if len(b.bufs) != len(bufs) || len(b.bufs[0]) < len(bufs[0]) {
|
||||
b.bufs = make([][]byte, len(bufs))
|
||||
for i := range b.bufs {
|
||||
b.bufs[i] = make([]byte, len(bufs[0]))
|
||||
}
|
||||
}
|
||||
return b.bufs
|
||||
}
|
||||
|
||||
// endBatch hands the batch to the workers and the ordered writer, then takes a free batch.
|
||||
func (p *stagedRx) endBatch() {
|
||||
clear(p.hostmapCache)
|
||||
p.reap()
|
||||
b := p.cur
|
||||
p.precheck(b)
|
||||
n := len(b.items)
|
||||
if n == 0 {
|
||||
b.reset()
|
||||
return
|
||||
}
|
||||
|
||||
if p.inFlight == 0 && n < p.f.staged.inlineBelow {
|
||||
// The writer is idle with nothing in flight, so the listener may commit with its context and flush the tun
|
||||
p.metricInline.Inc(1)
|
||||
p.process(b, p.wrxc)
|
||||
b.reset()
|
||||
return
|
||||
}
|
||||
|
||||
parts := min(len(b.chunks), b.data/rxChunkMin)
|
||||
p.metricBatches.Inc(1)
|
||||
if parts > 0 {
|
||||
size := (n + parts - 1) / parts
|
||||
for off := 0; off < n; off += size {
|
||||
c := &b.chunks[b.nChunks]
|
||||
c.items = b.items[off:min(off+size, n)]
|
||||
b.nChunks++
|
||||
}
|
||||
}
|
||||
// The jobs go out before the batch does: once the writer has it, it may finish and reset it at any moment
|
||||
for i := range b.nChunks {
|
||||
p.pool.jobs <- &b.chunks[i]
|
||||
}
|
||||
p.inFlight++
|
||||
p.ordered <- b
|
||||
|
||||
if len(p.free) == 0 {
|
||||
// Every batch is in flight, wait for the writer: the socket buffer absorbs the backlog meanwhile.
|
||||
p.release(<-p.returned)
|
||||
}
|
||||
p.cur = p.free[len(p.free)-1]
|
||||
p.free = p.free[:len(p.free)-1]
|
||||
}
|
||||
|
||||
// reap takes back every batch the writer has finished with, without waiting.
|
||||
func (p *stagedRx) reap() {
|
||||
for {
|
||||
select {
|
||||
case b := <-p.returned:
|
||||
p.release(b)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *stagedRx) release(b *rxBatch) {
|
||||
p.inFlight--
|
||||
p.free = append(p.free, b)
|
||||
}
|
||||
|
||||
// process is the ordered stage for one batch: decrypt whatever no worker is decrypting, commit every item in arrival
|
||||
// order, and flush the tun batcher.
|
||||
func (p *stagedRx) process(b *rxBatch, rxc *rxContext) {
|
||||
if b.nChunks == 0 {
|
||||
decryptRxItems(b.items, rxc.nb)
|
||||
p.commit(b.items, rxc)
|
||||
} else {
|
||||
// Commit chunk by chunk, so the commit overlaps the workers still on later chunks
|
||||
for i := range b.nChunks {
|
||||
c := &b.chunks[i]
|
||||
<-c.done
|
||||
p.commit(c.items, rxc)
|
||||
}
|
||||
}
|
||||
p.f.flushOutside(rxc)
|
||||
}
|
||||
|
||||
// commit runs the ordered stage over items in arrival order. A non-data packet goes through readOutsidePackets in
|
||||
// its place, a run of data packets on one tunnel through commitRun.
|
||||
func (p *stagedRx) commit(items []rxItem, rxc *rxContext) {
|
||||
for i := 0; i < len(items); {
|
||||
ci := items[i].ci
|
||||
if ci == nil {
|
||||
p.f.readOutsidePackets(ViaSender{UdpAddr: items[i].via}, items[i].packet, rxc)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
j := i + 1
|
||||
for j < len(items) && items[j].ci == ci {
|
||||
j++
|
||||
}
|
||||
p.commitRun(items[i:j], rxc)
|
||||
i = j
|
||||
}
|
||||
}
|
||||
|
||||
// commitRun commits a run of decrypted data packets on one tunnel. The window updates go first, under one lock, then
|
||||
// the rest; handling a data packet never touches the window, so that is the same as one packet at a time.
|
||||
func (p *stagedRx) commitRun(run []rxItem, rxc *rxContext) {
|
||||
f := p.f
|
||||
ci := run[0].ci
|
||||
// Classification is speculative: earlier control packets may have removed this tunnel. Resolve it through the
|
||||
// writer's batch-local cache, exactly where inline processing would, before touching replay state.
|
||||
index := binary.BigEndian.Uint32(run[0].packet[4:8])
|
||||
hostinfo := f.hostMap.QueryIndexCached(index, rxc.hostmapCache)
|
||||
if hostinfo != run[0].hostinfo || hostinfo.ConnectionState != ci {
|
||||
if hostinfo == nil {
|
||||
for i := range run {
|
||||
f.maybeSendRecvError(run[i].via, index)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ci.decryptLock.Lock()
|
||||
for i := range run {
|
||||
// A packet that failed to decrypt does not touch the window, like ConnectionState.Decrypt
|
||||
if run[i].err == nil && !ci.window.Update(f.l, run[i].counter) {
|
||||
run[i].err = ErrAlreadySeen
|
||||
}
|
||||
}
|
||||
ci.decryptLock.Unlock()
|
||||
for i := range run {
|
||||
it := &run[i]
|
||||
if f.finishOutsideDecrypt(it.hostinfo, ViaSender{UdpAddr: it.via}, it.counter, it.err) {
|
||||
f.handleOutsideMessagePacket(it.hostinfo, it.counter, it.out, rxc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// writer is the ordered receive stage: window, firewall, coalescer and tun write, one batch at a time in arrival
|
||||
// order.
|
||||
func (p *stagedRx) writer() {
|
||||
defer close(p.writerDone)
|
||||
for b := range p.ordered {
|
||||
if p.f.closed.Load() {
|
||||
// The tun is going away, a write would only log errors. Still wait out the workers on the batch.
|
||||
for i := range b.nChunks {
|
||||
<-b.chunks[i].done
|
||||
}
|
||||
} else {
|
||||
p.process(b, p.wrxc)
|
||||
}
|
||||
b.reset()
|
||||
p.returned <- b
|
||||
}
|
||||
}
|
||||
|
||||
// close commits anything still in flight, in order, and stops the writer and the workers.
|
||||
func (p *stagedRx) close() {
|
||||
if len(p.cur.items) > 0 {
|
||||
p.endBatch()
|
||||
}
|
||||
close(p.ordered)
|
||||
<-p.writerDone
|
||||
p.pool.close()
|
||||
}
|
||||
-237
@@ -1,237 +0,0 @@
|
||||
//go:build linux && !android && !e2e_testing
|
||||
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/goleak"
|
||||
)
|
||||
|
||||
// TestFlowStagedRXOrderAndReplay feeds every packet behind a forgery of it, from another address, and a replay of
|
||||
// it, then a test packet that jumps the window and the whole stream again, with shuffled workers and a slow tun,
|
||||
// through small and large batches: the tun sees each segment once, in order, the window marks them all, the forgeries
|
||||
// neither consume a counter nor roam, and the jump does not get the earlier data packets of its batch rejected.
|
||||
func TestFlowStagedRXOrderAndReplay(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
for _, cipher := range []noise.CipherFunc{noiseutil.CipherAESGCM, noise.CipherChaChaPoly} {
|
||||
for _, batchLen := range []int{8, 1000} {
|
||||
t.Run(fmt.Sprintf("%s/batch=%d", cipher.CipherName(), batchLen), func(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, cipher, stagedOn(4))
|
||||
delayCrypto(receiver, func(n uint64) {
|
||||
if n%32 == 0 {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
})
|
||||
receiver.tun.delay = 100 * time.Microsecond
|
||||
batches, want := flowTestBatches(30, 4, 1, 10)
|
||||
wire := wireFor(t, sender, batches)
|
||||
var feed [][]byte
|
||||
for i, p := range wire {
|
||||
// Corrupt the tag or the payload
|
||||
bad := append([]byte(nil), p...)
|
||||
bad[[]int{len(p) - 1, header.Len + 3}[i%2]] ^= 1
|
||||
feed = append(feed, bad, p, p)
|
||||
}
|
||||
// The jump lands in a batch with fresh data before it, at batch=1000
|
||||
sender.hostinfo.ConnectionState.messageCounter.Add(2 * ReplayWindow)
|
||||
feed = append(append(feed, sendControl(sender, header.Test, header.TestReply)), wire...)
|
||||
forged := func(i int) netip.AddrPort {
|
||||
if i < 3*len(wire) && i%3 == 0 {
|
||||
return netip.MustParseAddrPort("198.51.100.9:4242")
|
||||
}
|
||||
return flowTestUnder
|
||||
}
|
||||
rx0 := rxBatches.Count()
|
||||
conn := &rxConn{wire: feed, batchLen: batchLen, from: forged}
|
||||
receiver.receive(conn)
|
||||
require.Positive(t, rxBatches.Count()-rx0)
|
||||
require.Equal(t, (len(feed)+batchLen-1)/batchLen, conn.swaps, "every batch is handed off")
|
||||
require.Equal(t, want, receiver.tun.segments(t), "every packet exactly once, in order")
|
||||
require.Equal(t, flowTestUnder, receiver.hostinfo.GetRemote())
|
||||
for _, p := range wire {
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(p))
|
||||
require.False(t, receiver.hostinfo.ConnectionState.window.Check(receiver.f.l, h.MessageCounter), "counter %d must be marked seen", h.MessageCounter)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedRXClose: a CloseTunnel in the middle of a batch is handled in its place, by the writer. The data after
|
||||
// it in the batch is still delivered from the batch's hostmap cache, as inline receive does.
|
||||
func TestFlowStagedRXClose(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
batches, want := flowTestBatches(4, 4, 1, 8)
|
||||
wire := wireFor(t, sender, batches)
|
||||
half := len(wire) / 2
|
||||
feed := append(append(append([][]byte{}, wire[:half]...), sendControl(sender, header.CloseTunnel, 0)), wire[half:]...)
|
||||
receiver.receive(&rxConn{wire: feed, batchLen: len(feed)})
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
require.Nil(t, receiver.f.hostMap.QueryIndex(receiver.hostinfo.localIndexId))
|
||||
}
|
||||
|
||||
// sendControl returns the wire packet of a control message from sender.
|
||||
func sendControl(sender *flowTestPeer, typ header.MessageType, st header.MessageSubType) []byte {
|
||||
sender.f.sendNoMetrics(typ, st, sender.hostinfo.ConnectionState, sender.hostinfo, flowTestUnder, nil, make([]byte, 12), make([]byte, mtu), 0)
|
||||
wire := sender.conn.captured()
|
||||
sender.conn.pkts, sender.conn.addrs = nil, nil
|
||||
return wire[len(wire)-1]
|
||||
}
|
||||
|
||||
// receivePaths is inline, staged and, with the threshold, adaptive receive.
|
||||
func receivePaths() []stagedConfig {
|
||||
return []stagedConfig{{}, stagedOn(2), adaptive(2)}
|
||||
}
|
||||
|
||||
// TestFlowStagedRXRecvError feeds a RecvError that deletes the tunnel, then a known replay and new data for it, in one
|
||||
// batch. Every receive path must drop the data through its own view of the hostmap, without touching the replay window,
|
||||
// and answer each packet with a RecvError, as inline receive does, without decrypting the replay again.
|
||||
func TestFlowStagedRXRecvError(t *testing.T) {
|
||||
for _, sc := range receivePaths() {
|
||||
t.Run(stagedName(sc), func(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
receiver.f.messageMetrics = newMessageMetrics()
|
||||
receiver.f.acceptRecvErrorConfig = recvErrorAlways
|
||||
receiver.f.sendRecvErrorConfig = recvErrorAlways
|
||||
batches, want := flowTestBatches(1, 1, 1, 33)
|
||||
wire := wireFor(t, sender, batches)
|
||||
rxc := newRxContext(receiver.f, 0)
|
||||
receiver.f.readOutsidePackets(ViaSender{UdpAddr: flowTestUnder}, append([]byte(nil), wire[0]...), rxc)
|
||||
receiver.f.flushOutside(rxc)
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(wire[0]))
|
||||
replay := h.MessageCounter
|
||||
var decrypts atomic.Int64
|
||||
delayCrypto(receiver, func(n uint64) {
|
||||
if n == replay {
|
||||
decrypts.Add(1)
|
||||
}
|
||||
})
|
||||
ctl := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, receiver.hostinfo.remoteIndexId, 0)
|
||||
conn := &rxConn{wire: append([][]byte{ctl}, wire...), batchLen: len(wire) + 1}
|
||||
receiver.receive(conn)
|
||||
require.Nil(t, receiver.f.hostMap.QueryIndex(receiver.hostinfo.localIndexId))
|
||||
require.Equal(t, want[:1], receiver.tun.segments(t))
|
||||
require.Zero(t, decrypts.Load(), "known replays must not be decrypted again")
|
||||
replies := conn.captured()
|
||||
require.Len(t, replies, len(wire))
|
||||
for i, reply := range replies {
|
||||
require.NoError(t, h.Parse(reply))
|
||||
require.Equal(t, header.RecvError, h.Type)
|
||||
require.NoError(t, h.Parse(wire[i]))
|
||||
require.True(t, i == 0 || receiver.hostinfo.ConnectionState.window.Check(nil, h.MessageCounter), "dropped data must not update replay state")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedRXReplacedTunnel classifies a data packet, then a close and a new handshake replace its tunnel at the
|
||||
// same index before the writer commits it, as when the listener runs ahead: it must be dropped untouched.
|
||||
func TestFlowStagedRXReplacedTunnel(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
receiver.f.messageMetrics = newMessageMetrics()
|
||||
batches, _ := flowTestBatches(1, 1, 1, 1)
|
||||
wire := wireFor(t, sender, batches)
|
||||
closePacket := sendControl(sender, header.CloseTunnel, 0)
|
||||
p := &stagedRx{f: receiver.f, h: &header.H{}, hostmapCache: map[uint32]*HostInfo{}}
|
||||
item := rxItem{packet: wire[0], via: flowTestUnder}
|
||||
p.classify(&item)
|
||||
require.NotNil(t, item.ci)
|
||||
rxc := newRxContext(receiver.f, 0)
|
||||
p.process(&rxBatch{items: []rxItem{{packet: closePacket, via: flowTestUnder}}}, rxc)
|
||||
require.Nil(t, receiver.f.hostMap.QueryIndex(receiver.hostinfo.localIndexId))
|
||||
_, replacement := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
receiver.f.hostMap.Lock()
|
||||
receiver.f.hostMap.unlockedAddHostInfo(replacement.hostinfo, receiver.f)
|
||||
receiver.f.hostMap.Unlock()
|
||||
p.process(&rxBatch{items: []rxItem{item}}, rxc)
|
||||
require.Empty(t, receiver.tun.writes)
|
||||
require.True(t, item.ci.window.Check(nil, item.counter))
|
||||
require.True(t, replacement.hostinfo.ConnectionState.window.Check(nil, item.counter))
|
||||
}
|
||||
|
||||
// TestFlowStagedRXRealSocket exercises buffer handoff through the real Linux UDP receive loop.
|
||||
func TestFlowStagedRXRealSocket(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(3))
|
||||
batches, want := flowTestBatches(60, 4, 1, 8)
|
||||
wire := wireFor(t, sender, batches)
|
||||
|
||||
l := receiver.f.l
|
||||
conn, err := udp.NewListener(l, udp.Settings{Listen: netip.MustParseAddrPort("127.0.0.1:0"), Batch: 16, Offloads: true})
|
||||
require.NoError(t, err)
|
||||
addr, err := conn.LocalAddr()
|
||||
require.NoError(t, err)
|
||||
out, err := udp.NewListener(l, udp.Settings{Listen: netip.MustParseAddrPort("127.0.0.1:0"), Batch: 16, Offloads: true})
|
||||
require.NoError(t, err)
|
||||
defer out.Close()
|
||||
// The sender's address is the tunnel's remote, so no roaming
|
||||
from, err := out.LocalAddr()
|
||||
require.NoError(t, err)
|
||||
receiver.hostinfo.remote.Store(&from)
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { receiver.receive(conn); close(done) }()
|
||||
// Send in bursts small enough for the default socket buffer
|
||||
for off := 0; off < len(wire); off += 32 {
|
||||
end := min(off+32, len(wire))
|
||||
addrs := make([]netip.AddrPort, end-off)
|
||||
for i := range addrs {
|
||||
addrs[i] = addr
|
||||
}
|
||||
_, err := out.WriteBatch(wire[off:end], addrs)
|
||||
require.NoError(t, err)
|
||||
require.Eventually(t, func() bool { return len(receiver.tun.segments(t)) >= end }, 5*time.Second, 100*time.Microsecond)
|
||||
}
|
||||
receiver.f.closed.Store(true)
|
||||
require.NoError(t, conn.Close())
|
||||
<-done
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
}
|
||||
|
||||
// TestFlowStagedRXCloseFlushesPartial: packets the listener holds in a batch it never got to end when the conn fails
|
||||
// are still committed, in order, on a live interface.
|
||||
func TestFlowStagedRXCloseFlushesPartial(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
batches, want := flowTestBatches(11, 4, 1, 8)
|
||||
wire := wireFor(t, sender, batches)
|
||||
p := newStagedRx(receiver.f, 0, newRxContext(receiver.f, 0))
|
||||
for i, packet := range wire {
|
||||
p.deliver(flowTestUnder, packet)
|
||||
if (i+1)%64 == 0 {
|
||||
p.endBatch()
|
||||
}
|
||||
}
|
||||
p.close()
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
}
|
||||
|
||||
// TestFlowStagedRXInlineBelow: small idle batches stay on the listener, larger batches still use the ordered writer.
|
||||
func TestFlowStagedRXInlineBelow(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sc := adaptive(3)
|
||||
sc.inlineBelow = 16
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
batches, want := flowTestBatches(40, 4, 1, 16)
|
||||
wire := wireFor(t, sender, batches)
|
||||
inline := metrics.GetOrRegisterCounter("flow.rx.inline", nil)
|
||||
inline0, rx0 := inline.Count(), rxBatches.Count()
|
||||
receiver.receive(&rxConn{wire: wire, sizes: []int{8, 8, 8, 128, 128, 8, 8, 128, 4, 128}})
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
require.Positive(t, inline.Count()-inline0)
|
||||
require.Positive(t, rxBatches.Count()-rx0)
|
||||
}
|
||||
-536
@@ -1,536 +0,0 @@
|
||||
//go:build linux && !android && !e2e_testing
|
||||
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/gaissmai/bart"
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/firewall"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/iputil"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/overlay/batch"
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/goleak"
|
||||
)
|
||||
|
||||
// flowTestMSS is the segment payload size of the synthetic TSO superpackets.
|
||||
const flowTestMSS = 1200
|
||||
|
||||
var (
|
||||
flowTestLocal = netip.MustParseAddr("10.0.0.1")
|
||||
flowTestRemote = netip.MustParseAddr("10.0.0.2")
|
||||
flowTestUnder = netip.MustParseAddrPort("192.0.2.2:4242")
|
||||
)
|
||||
|
||||
// flowTCPSuperpacket builds an IPv4/TCP TSO superpacket from local to remote carrying segs segments. Segment i's
|
||||
// payload starts with the flow id, the superpacket seq and i, so a receiver can check what it got and in which order.
|
||||
func flowTCPSuperpacket(flow uint16, seq uint32, segs int) tio.Packet {
|
||||
const hdr = 40
|
||||
pay := segs * flowTestMSS
|
||||
b := make([]byte, hdr+pay)
|
||||
b[0] = 0x45
|
||||
binary.BigEndian.PutUint16(b[2:4], uint16(min(hdr+pay, 65535)))
|
||||
b[8] = 64
|
||||
b[9] = iputil.IPProtocolTCP
|
||||
copy(b[12:16], flowTestLocal.AsSlice())
|
||||
copy(b[16:20], flowTestRemote.AsSlice())
|
||||
binary.BigEndian.PutUint16(b[20:22], 10000+flow)
|
||||
binary.BigEndian.PutUint16(b[22:24], 80)
|
||||
binary.BigEndian.PutUint32(b[24:28], seq*uint32(pay))
|
||||
b[32] = 0x50
|
||||
b[33] = 0x10 // ACK
|
||||
binary.BigEndian.PutUint16(b[34:36], 65535)
|
||||
for i := range segs {
|
||||
p := b[hdr+i*flowTestMSS:]
|
||||
binary.BigEndian.PutUint16(p[0:2], flow)
|
||||
binary.BigEndian.PutUint32(p[2:6], seq)
|
||||
binary.BigEndian.PutUint16(p[6:8], uint16(i))
|
||||
}
|
||||
if segs == 1 {
|
||||
return tio.Packet{Bytes: b}
|
||||
}
|
||||
return tio.Packet{Bytes: b, GSO: tio.GSOInfo{Size: flowTestMSS, HdrLen: hdr, CsumStart: 20, Proto: tio.GSOProtoTCP}}
|
||||
}
|
||||
|
||||
// decodedSeg identifies one segment by the marker flowTCPSuperpacket put in its payload.
|
||||
type decodedSeg struct {
|
||||
flow uint16
|
||||
seq uint32
|
||||
idx uint16
|
||||
}
|
||||
|
||||
func decodeSeg(p []byte) decodedSeg {
|
||||
return decodedSeg{flow: binary.BigEndian.Uint16(p[0:2]), seq: binary.BigEndian.Uint32(p[2:6]), idx: binary.BigEndian.Uint16(p[6:8])}
|
||||
}
|
||||
|
||||
// flowTestBatches builds n reads of per superpackets of segs segments, across flows interleaved flows, and the
|
||||
// segments they carry in order.
|
||||
func flowTestBatches(n, per, flows, segs int) ([][]tio.Packet, []decodedSeg) {
|
||||
var batches [][]tio.Packet
|
||||
var want []decodedSeg
|
||||
seq := make([]uint32, flows)
|
||||
for range n {
|
||||
var b []tio.Packet
|
||||
for j := range per {
|
||||
flow := uint16(j % flows)
|
||||
b = append(b, flowTCPSuperpacket(flow, seq[flow], segs))
|
||||
for s := range segs {
|
||||
want = append(want, decodedSeg{flow: flow, seq: seq[flow], idx: uint16(s)})
|
||||
}
|
||||
seq[flow]++
|
||||
}
|
||||
batches = append(batches, b)
|
||||
}
|
||||
return batches, want
|
||||
}
|
||||
|
||||
// flowTestPeer is one end of a tunnel: the interface, the hostinfo for the other end, and its capture points.
|
||||
type flowTestPeer struct {
|
||||
f *Interface
|
||||
hostinfo *HostInfo
|
||||
conn *flowCaptureConn
|
||||
tun *flowTunCapture
|
||||
}
|
||||
|
||||
// newFlowTestPair builds two interfaces joined by one real tunnel (keys from an actual handshake). sender sends from
|
||||
// flowTestLocal to flowTestRemote, receiver is the far side.
|
||||
func newFlowTestPair(t testing.TB, cipher noise.CipherFunc, sc stagedConfig) (sender, receiver *flowTestPeer) {
|
||||
t.Helper()
|
||||
initR, respR := runTestHandshakeWith(t, cipher)
|
||||
sci, err := newConnectionStateFromResult(initR)
|
||||
require.NoError(t, err)
|
||||
rci, err := newConnectionStateFromResult(respR)
|
||||
require.NoError(t, err)
|
||||
sender = newFlowTestPeer(t, flowTestLocal, flowTestRemote, sci, 100, 200)
|
||||
receiver = newFlowTestPeer(t, flowTestRemote, flowTestLocal, rci, 200, 100)
|
||||
sender.f.staged, receiver.f.staged = sc, sc
|
||||
return sender, receiver
|
||||
}
|
||||
|
||||
func newFlowTestPeer(t testing.TB, me, them netip.Addr, ci *ConnectionState, localIdx, remoteIdx uint32) *flowTestPeer {
|
||||
l := test.NewLogger()
|
||||
hm := newHostMap(l)
|
||||
hm.preferredRanges.Store(&[]netip.Prefix{})
|
||||
|
||||
myNets, myAddrs := &bart.Lite{}, &bart.Lite{}
|
||||
myNets.Insert(netip.PrefixFrom(me, 24))
|
||||
myAddrs.Insert(netip.PrefixFrom(me, 32))
|
||||
myCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(me, 24)}}
|
||||
theirCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(them, 24)}, name: "peer"}
|
||||
ci.peerCert = &cert.CachedCertificate{Certificate: theirCert, InvertedGroups: map[string]struct{}{}}
|
||||
|
||||
fw := NewFirewall(l, time.Minute, time.Minute, time.Minute, myCert)
|
||||
require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||
|
||||
conn, tun := &flowCaptureConn{}, &flowTunCapture{}
|
||||
lh := newTestLighthouse()
|
||||
lh.remoteAllowList.Store(&RemoteAllowList{})
|
||||
|
||||
f := &Interface{
|
||||
hostMap: hm,
|
||||
outside: conn,
|
||||
firewall: fw,
|
||||
lightHouse: lh,
|
||||
pki: &PKI{},
|
||||
myVpnNetworksTable: myNets,
|
||||
myVpnAddrsTable: myAddrs,
|
||||
routines: 1,
|
||||
writers: []udp.Conn{conn},
|
||||
messageMetrics: &MessageMetrics{txExhausted: metrics.NewCounter()},
|
||||
metricTxDropped: metrics.NilCounter{},
|
||||
l: l,
|
||||
}
|
||||
f.ctx = t.Context()
|
||||
f.pki.caPool.Store(cert.NewCAPool())
|
||||
// Never promote or requery, those would put extra test packets on the wire
|
||||
f.tryPromoteEvery.Store(math.MaxUint32)
|
||||
f.reQueryEvery.Store(math.MaxUint32)
|
||||
f.batchers = []*batch.MultiCoalescer{batch.NewMultiCoalescer(tun, l)}
|
||||
f.connectionManager = &connectionManager{
|
||||
intf: f,
|
||||
relayUsed: map[uint32]struct{}{},
|
||||
relayUsedLock: &sync.RWMutex{},
|
||||
trafficTimer: NewLockingTimerWheel[uint32](time.Second, time.Minute),
|
||||
}
|
||||
f.handshakeManager = NewHandshakeManager(l, hm, lh, conn, defaultHandshakeConfig)
|
||||
f.handshakeManager.f = f
|
||||
|
||||
hostinfo := &HostInfo{
|
||||
ConnectionState: ci,
|
||||
vpnAddrs: []netip.Addr{them},
|
||||
localIndexId: localIdx,
|
||||
remoteIndexId: remoteIdx,
|
||||
relayState: RelayState{relayForByAddr: map[netip.Addr]*Relay{}, relayForByIdx: map[uint32]*Relay{}},
|
||||
}
|
||||
hostinfo.remote.Store(&flowTestUnder)
|
||||
hostinfo.buildNetworks(myNets, theirCert)
|
||||
hm.unlockedAddHostInfo(hostinfo, f)
|
||||
|
||||
return &flowTestPeer{f: f, hostinfo: hostinfo, conn: conn, tun: tun}
|
||||
}
|
||||
|
||||
// flowCaptureConn records every packet sent, in order, as copies.
|
||||
type flowCaptureConn struct {
|
||||
udp.NoopConn
|
||||
mu sync.Mutex
|
||||
pkts [][]byte
|
||||
addrs []netip.AddrPort
|
||||
// delay, when set, slows every WriteBatch down so batches pile up in flight
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (c *flowCaptureConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error) {
|
||||
time.Sleep(c.delay)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
for i, b := range bufs {
|
||||
c.pkts = append(c.pkts, append([]byte(nil), b...))
|
||||
c.addrs = append(c.addrs, addrs[i])
|
||||
}
|
||||
return len(bufs), nil
|
||||
}
|
||||
|
||||
func (c *flowCaptureConn) WriteTo(b []byte, addr netip.AddrPort) error {
|
||||
_, err := c.WriteBatch([][]byte{b}, []netip.AddrPort{addr})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *flowCaptureConn) captured() [][]byte {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([][]byte(nil), c.pkts...)
|
||||
}
|
||||
|
||||
// flowTunCapture is a tun queue that records every plaintext write.
|
||||
type flowTunCapture struct {
|
||||
mu sync.Mutex
|
||||
writes [][]byte
|
||||
// delay, when set, slows every write down
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (c *flowTunCapture) Read() ([]tio.Packet, error) { return nil, io.EOF }
|
||||
func (c *flowTunCapture) Close() error { return nil }
|
||||
func (c *flowTunCapture) Write(b []byte) (int, error) {
|
||||
time.Sleep(c.delay)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.writes = append(c.writes, append([]byte(nil), b...))
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
// segments decodes what reached the tun. The coalescer may have merged segments back into superpackets, so this
|
||||
// walks each payload in MSS steps.
|
||||
func (c *flowTunCapture) segments(t testing.TB) []decodedSeg {
|
||||
t.Helper()
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
var out []decodedSeg
|
||||
for _, w := range c.writes {
|
||||
pay := w[40:]
|
||||
require.Zero(t, len(pay)%flowTestMSS, "tun write payload %d bytes", len(pay))
|
||||
for off := 0; off < len(pay); off += flowTestMSS {
|
||||
out = append(out, decodeSeg(pay[off:]))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// decryptWire checks every wire packet decrypts on the receiver, in order, with strictly increasing counters, and
|
||||
// returns what each one carried. It uses its own replay window and copies, so the wire can still be fed to the
|
||||
// receiver afterwards.
|
||||
func decryptWire(t testing.TB, receiver *flowTestPeer, wire [][]byte) []decodedSeg {
|
||||
t.Helper()
|
||||
peer := receiver.hostinfo.ConnectionState
|
||||
ci := &ConnectionState{dKey: peer.dKey, window: NewBits(peer.window.length)}
|
||||
nb := make([]byte, 12)
|
||||
var last uint64
|
||||
out := make([]decodedSeg, 0, len(wire))
|
||||
for i, pkt := range wire {
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(pkt))
|
||||
require.Equal(t, header.Message, h.Type)
|
||||
require.Equal(t, receiver.hostinfo.localIndexId, h.RemoteIndex)
|
||||
require.Greater(t, h.MessageCounter, last, "wire packet %d: counter %d after %d", i, h.MessageCounter, last)
|
||||
last = h.MessageCounter
|
||||
plain, err := ci.Decrypt(receiver.f.l, h.MessageCounter, append([]byte(nil), pkt...), nb)
|
||||
require.NoError(t, err, "wire packet %d", i)
|
||||
out = append(out, decodeSeg(plain[40:]))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// flowBatchQueue is a handoffQueue that hands out scripted Read batches, then fails with io.EOF. Every batch is copied
|
||||
// into the current receive buffer, so a test sees the buffer ownership the Offload queue has.
|
||||
type flowBatchQueue struct {
|
||||
batches [][]tio.Packet
|
||||
rxBuf []byte
|
||||
out []tio.Packet
|
||||
closed chan struct{}
|
||||
// reads counts the batches handed out
|
||||
reads atomic.Int64
|
||||
}
|
||||
|
||||
func newFlowBatchQueue(batches [][]tio.Packet) *flowBatchQueue {
|
||||
return &flowBatchQueue{batches: batches, rxBuf: make([]byte, 8*65536), closed: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (q *flowBatchQueue) Read() ([]tio.Packet, error) {
|
||||
select {
|
||||
case <-q.closed:
|
||||
return nil, os.ErrClosed
|
||||
default:
|
||||
}
|
||||
n := int(q.reads.Load())
|
||||
if n == len(q.batches) {
|
||||
return nil, io.EOF
|
||||
}
|
||||
q.out = q.out[:0]
|
||||
off := 0
|
||||
for _, p := range q.batches[n] {
|
||||
l := copy(q.rxBuf[off:], p.Bytes)
|
||||
q.out = append(q.out, tio.Packet{Bytes: q.rxBuf[off : off+l : off+l], GSO: p.GSO})
|
||||
off += l
|
||||
}
|
||||
q.reads.Add(1)
|
||||
return q.out, nil
|
||||
}
|
||||
|
||||
func (q *flowBatchQueue) SwapRxBuf(buf []byte) []byte {
|
||||
if buf == nil {
|
||||
buf = make([]byte, len(q.rxBuf))
|
||||
}
|
||||
old := q.rxBuf
|
||||
q.rxBuf = buf
|
||||
// Scribble over the buffer we are handed, a staged batch that still pointed into it would be corrupted
|
||||
for i := range buf {
|
||||
buf[i] = 0xa5
|
||||
}
|
||||
return old
|
||||
}
|
||||
|
||||
func (q *flowBatchQueue) Write(b []byte) (int, error) { return len(b), nil }
|
||||
|
||||
func (q *flowBatchQueue) Close() error { close(q.closed); return nil }
|
||||
|
||||
// delayedCipher changes scheduling through the real cipher interface, only in tests.
|
||||
type delayedCipher struct {
|
||||
noiseutil.CipherState
|
||||
before func(uint64)
|
||||
}
|
||||
|
||||
func (c delayedCipher) EncryptDanger(out, ad, plain []byte, n uint64, nb []byte) ([]byte, error) {
|
||||
c.before(n)
|
||||
return c.CipherState.EncryptDanger(out, ad, plain, n, nb)
|
||||
}
|
||||
|
||||
func (c delayedCipher) DecryptDanger(out, ad, ciphertext []byte, n uint64, nb []byte) ([]byte, error) {
|
||||
c.before(n)
|
||||
return c.CipherState.DecryptDanger(out, ad, ciphertext, n, nb)
|
||||
}
|
||||
|
||||
func delayCrypto(peer *flowTestPeer, before func(uint64)) {
|
||||
ci := peer.hostinfo.ConnectionState
|
||||
ci.eKey = delayedCipher{ci.eKey, before}
|
||||
ci.dKey = delayedCipher{ci.dKey, before}
|
||||
}
|
||||
|
||||
// stagedOn enables staging with n workers.
|
||||
func stagedOn(n int) stagedConfig {
|
||||
return stagedConfig{workers: n, tx: true, rx: true, txSlots: stagedTxSlots, rxSlots: 6}
|
||||
}
|
||||
|
||||
// adaptive is staging with the inline threshold and gate hold parseStagedConfig sets.
|
||||
func adaptive(n int) stagedConfig {
|
||||
return stagedConfig{workers: n, tx: true, rx: true, inlineBelow: 256, gateHold: stagedGateHold,
|
||||
txSlots: stagedTxSlots, rxSlots: 6}
|
||||
}
|
||||
|
||||
func stagedName(sc stagedConfig) string {
|
||||
switch {
|
||||
case sc.workers == 0:
|
||||
return "inline"
|
||||
case sc.inlineBelow > 0:
|
||||
return "adaptive"
|
||||
default:
|
||||
return "staged"
|
||||
}
|
||||
}
|
||||
|
||||
// send takes one read through the pipeline, as run does.
|
||||
func (p *stagedTx) send(pkts []tio.Packet) {
|
||||
p.handle(pkts, &firewall.ParsedPacket{}, make([]byte, mtu), nil)
|
||||
}
|
||||
|
||||
// drain waits until every batch p has in flight is on the wire.
|
||||
func (p *stagedTx) drain() {
|
||||
for p.inFlight > 0 {
|
||||
p.release(<-p.returned)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedFallback: a tun queue that cannot hand off its buffer, or a conn that cannot hand off its batches,
|
||||
// keeps that direction on the inline path.
|
||||
func TestFlowStagedFallback(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(3))
|
||||
batches, want := flowTestBatches(10, 2, 1, 4)
|
||||
tx := metrics.GetOrRegisterCounter("flow.tx.batches", nil)
|
||||
tx0, rx0 := tx.Count(), rxBatches.Count()
|
||||
sender.f.listenIn(plainQueue{newFlowBatchQueue(batches)}, 0)
|
||||
wire := sender.conn.captured()
|
||||
require.Equal(t, want, decryptWire(t, receiver, wire))
|
||||
require.Equal(t, tx0, tx.Count())
|
||||
receiver.receive(plainConn{&rxConn{wire: wire, batchLen: 16}})
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
require.Equal(t, rx0, rxBatches.Count())
|
||||
}
|
||||
|
||||
// plainQueue and plainConn hide SwapRxBuf and ListenOutHandoff, so they cannot hand off their batches.
|
||||
type plainQueue struct{ tio.Queue }
|
||||
|
||||
// wireFor produces the wire packets the sender emits for batches, inline.
|
||||
func wireFor(t testing.TB, sender *flowTestPeer, batches [][]tio.Packet) [][]byte {
|
||||
t.Helper()
|
||||
sc := sender.f.staged
|
||||
sender.f.staged = stagedConfig{}
|
||||
sender.f.listenIn(newFlowBatchQueue(batches), 0)
|
||||
sender.f.staged = sc
|
||||
wire := sender.conn.captured()
|
||||
sender.conn.pkts, sender.conn.addrs = nil, nil
|
||||
return wire
|
||||
}
|
||||
|
||||
// rxConn plays wire back to listenOut through the buffer handoff, in batches of batchLen or of the scripted sizes
|
||||
// (the last one repeating), and captures what is sent back. Every buffer handed back is scribbled over before it is
|
||||
// read into, so a stage still using one shows corruption. from, when set, picks each packet's source address by its
|
||||
// index in wire.
|
||||
type rxConn struct {
|
||||
flowCaptureConn
|
||||
wire [][]byte
|
||||
batchLen int
|
||||
sizes []int
|
||||
from func(i int) netip.AddrPort
|
||||
swaps int
|
||||
}
|
||||
|
||||
func (c *rxConn) ListenOut(r udp.EncReader, flush func()) error {
|
||||
return c.ListenOutHandoff(r, func(bufs [][]byte) [][]byte {
|
||||
flush()
|
||||
return bufs
|
||||
})
|
||||
}
|
||||
|
||||
func (c *rxConn) ListenOutHandoff(r udp.EncReader, handoff func(bufs [][]byte) [][]byte) error {
|
||||
n := c.batchLen
|
||||
for _, size := range c.sizes {
|
||||
n = max(n, size)
|
||||
}
|
||||
bufs := make([][]byte, n)
|
||||
for i := range bufs {
|
||||
bufs[i] = make([]byte, udp.MTU)
|
||||
}
|
||||
for off, k := 0, 0; off < len(c.wire); k++ {
|
||||
size := c.batchLen
|
||||
if len(c.sizes) > 0 {
|
||||
size = c.sizes[min(k, len(c.sizes)-1)]
|
||||
}
|
||||
end := min(off+size, len(c.wire))
|
||||
for i, p := range c.wire[off:end] {
|
||||
n := copy(bufs[i], p)
|
||||
from := flowTestUnder
|
||||
if c.from != nil {
|
||||
from = c.from(off + i)
|
||||
}
|
||||
r(from, bufs[i][:n:n])
|
||||
}
|
||||
next := handoff(bufs)
|
||||
if len(next) != len(bufs) {
|
||||
panic("handoff returned the wrong number of buffers")
|
||||
}
|
||||
bufs = next
|
||||
for _, b := range bufs {
|
||||
for j := range b[:udp.MTU] {
|
||||
b[j] = 0x5a
|
||||
}
|
||||
}
|
||||
c.swaps++
|
||||
off = end
|
||||
}
|
||||
return os.ErrClosed
|
||||
}
|
||||
|
||||
type plainConn struct{ udp.Conn }
|
||||
|
||||
var rxBatches = metrics.GetOrRegisterCounter("flow.rx.batches", nil)
|
||||
|
||||
// receive runs the peer's listenOut over conn until conn runs out.
|
||||
func (p *flowTestPeer) receive(conn udp.Conn) {
|
||||
p.f.writers = []udp.Conn{conn}
|
||||
p.f.outside = conn
|
||||
p.f.listenOut(0)
|
||||
}
|
||||
|
||||
// TestFlowStagedFirewallParity: both paths apply the same outbound and inbound policy. An authenticated inbound
|
||||
// denial still consumes its replay counter, exactly as inline Decrypt does.
|
||||
func TestFlowStagedFirewallParity(t *testing.T) {
|
||||
for _, sc := range []stagedConfig{{}, stagedOn(2)} {
|
||||
t.Run(stagedName(sc), func(t *testing.T) {
|
||||
batches, _ := flowTestBatches(4, 3, 1, 8)
|
||||
sender, _ := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
sender.f.firewall.OutRules = newFirewallTable()
|
||||
sender.f.listenIn(newFlowBatchQueue(batches), 0)
|
||||
require.Empty(t, sender.conn.captured())
|
||||
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
wire := wireFor(t, sender, batches)
|
||||
receiver.f.firewall.InRules = newFirewallTable()
|
||||
receiver.receive(&rxConn{wire: wire, batchLen: 64})
|
||||
require.Empty(t, receiver.tun.writes)
|
||||
for _, pkt := range wire {
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(pkt))
|
||||
require.False(t, receiver.hostinfo.ConnectionState.window.Check(receiver.f.l, h.MessageCounter))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedCipherFallback runs the parsed configuration with the real AES cipher: transmit falls back to inline
|
||||
// when the build needs nonce-ordered encryption (BoringCrypto, FIPS), receive decryption stays staged.
|
||||
func TestFlowStagedCipherFallback(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
c.Settings = map[string]any{"tun": map[string]any{"staged": map[string]any{"workers": 2}}}
|
||||
sender, receiver := newFlowTestPair(t, noiseutil.CipherAESGCM, parseStagedConfig(c, l))
|
||||
require.Equal(t, !noiseutil.EncryptLockNeeded, sender.f.staged.tx)
|
||||
require.True(t, sender.f.staged.rx)
|
||||
batches, want := flowTestBatches(4, 8, 1, 45)
|
||||
tx := metrics.GetOrRegisterCounter("flow.tx.batches", nil)
|
||||
tx0, rx0 := tx.Count(), rxBatches.Count()
|
||||
sender.f.listenIn(newFlowBatchQueue(batches), 0)
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
require.Equal(t, tx0, tx.Count())
|
||||
}
|
||||
receiver.receive(&rxConn{wire: sender.conn.captured(), batchLen: 512})
|
||||
require.Greater(t, rxBatches.Count(), rx0)
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
}
|
||||
-583
@@ -1,583 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/netip"
|
||||
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/firewall"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/overlay/batch"
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
)
|
||||
|
||||
var errFlowSegmentOverrun = errors.New("superpacket has more segments than counters reserved for it")
|
||||
|
||||
// txItem is one firewall-approved inside packet (or superpacket) with everything needed to encrypt it. A nonzero
|
||||
// counter is the first of the segs counters reserved for it on ci, relayCounter the same on the relay tunnel when
|
||||
// relayHI is set. Zero counters are allocated per segment while encrypting, as inline sends do.
|
||||
type txItem struct {
|
||||
pkt tio.Packet
|
||||
hostinfo *HostInfo
|
||||
ci *ConnectionState
|
||||
remote netip.AddrPort
|
||||
segs uint64
|
||||
counter uint64
|
||||
relayHI *HostInfo
|
||||
relay *Relay
|
||||
relayCounter uint64
|
||||
}
|
||||
|
||||
// prepareTxItem does the per-packet work sendInsideMessage does before it encrypts, and resolves where the packet goes.
|
||||
func (f *Interface) prepareTxItem(it *txItem, hostinfo *HostInfo, pkt tio.Packet) bool {
|
||||
ci := hostinfo.ConnectionState
|
||||
if ci.eKey == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
f.recordOutbound(hostinfo)
|
||||
it.pkt, it.hostinfo, it.ci = pkt, hostinfo, ci
|
||||
it.remote = hostinfo.GetRemote()
|
||||
if it.remote.IsValid() {
|
||||
return true
|
||||
}
|
||||
|
||||
it.relayHI, it.relay = f.findRelay(hostinfo)
|
||||
if it.relayHI == nil || it.relay == nil {
|
||||
return false
|
||||
}
|
||||
it.remote = it.relayHI.GetRemote()
|
||||
return true
|
||||
}
|
||||
|
||||
// encryptTxItem segments and encrypts it into sb, for inline and staged sends alike.
|
||||
func (f *Interface) encryptTxItem(it *txItem, nb []byte, sb *batch.SendBatch) {
|
||||
reserved := it.counter != 0
|
||||
c, rc, end := it.counter, it.relayCounter, it.counter+it.segs
|
||||
err := tio.SegmentSuperpacket(it.pkt, func(seg []byte) error {
|
||||
if reserved && c >= end {
|
||||
// More segments than counters reserved for them, never encrypt past the reservation
|
||||
return errFlowSegmentOverrun
|
||||
}
|
||||
if it.relayHI == nil {
|
||||
// header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
|
||||
if out := f.encryptTxSegment(it, c, seg, nb, sb.Reserve(header.Len+len(seg)+16)); out != nil {
|
||||
sb.Commit(out, it.remote)
|
||||
}
|
||||
} else {
|
||||
f.encryptTxSegmentVia(it, c, rc, seg, nb, sb)
|
||||
}
|
||||
if reserved {
|
||||
c++
|
||||
rc++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
it.hostinfo.logger(f.l).Error("Failed to segment superpacket for send", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// encryptTxSegment encrypts one segment into out with counter c, or with the next counter of the tunnel when c is
|
||||
// zero. It returns nil when encryption failed, which is already logged.
|
||||
func (f *Interface) encryptTxSegment(it *txItem, c uint64, seg, nb, out []byte) []byte {
|
||||
if c != 0 {
|
||||
// Reserved counters are unique, so the encryption needs no lock
|
||||
return f.encryptMessage(header.Message, 0, it.hostinfo, it.ci, c, seg, nb, out, it.remote)
|
||||
}
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
it.ci.writeLock.Lock()
|
||||
}
|
||||
c = it.ci.messageCounter.Add(1)
|
||||
out = f.encryptMessage(header.Message, 0, it.hostinfo, it.ci, c, seg, nb, out, it.remote)
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
it.ci.writeLock.Unlock()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// encryptTxSegmentVia encrypts one segment for the relayed tunnel, then wraps it for the relay with counter rc, both
|
||||
// allocated on demand when zero like encryptTxSegment does.
|
||||
func (f *Interface) encryptTxSegmentVia(it *txItem, c, rc uint64, seg, nb []byte, sb *batch.SendBatch) {
|
||||
//relay header + header + plaintext + AEAD tag + relay tag
|
||||
scratch := sb.Reserve(len(seg) + header.MaxOverhead)
|
||||
out := f.encryptTxSegment(it, c, seg, nb, scratch[header.Len:])
|
||||
if out == nil {
|
||||
return
|
||||
}
|
||||
toSend, err := f.prepareSendVia(it.relayHI, it.relay, out, nb, scratch, true, rc)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
remote := it.remote
|
||||
if rc == 0 {
|
||||
// Unreserved sends follow the relay's current remote, like sendNoMetrics
|
||||
remote = it.relayHI.GetRemote()
|
||||
}
|
||||
sb.Commit(toSend, remote)
|
||||
}
|
||||
|
||||
// txTunnel accumulates one tunnel's counter needs across a batch so the batch reserves them with one atomic add.
|
||||
type txTunnel struct {
|
||||
ci *ConnectionState
|
||||
hostinfo *HostInfo
|
||||
n uint64
|
||||
base uint64
|
||||
exhausted bool
|
||||
}
|
||||
|
||||
// txReserver turns one tun read into txItems with message counters reserved for them. Only the reader goroutine
|
||||
// collects and reserves counters.
|
||||
type txReserver struct {
|
||||
f *Interface
|
||||
tunnels []txTunnel
|
||||
owner uint64
|
||||
// The staged reader separates relay data before reserving direct work. A nil pointer collects both paths.
|
||||
inlineRelays *[]txItem
|
||||
}
|
||||
|
||||
// collect runs the filter over pkts and appends the sendable ones to items, tallying each tunnel's counter needs.
|
||||
func (r *txReserver) collect(items []txItem, pkts []tio.Packet, fwPacket *firewall.ParsedPacket, rejectBuf []byte, q int, localCache firewall.ConntrackCache) []txItem {
|
||||
f := r.f
|
||||
r.tunnels = r.tunnels[:0]
|
||||
for _, pkt := range pkts {
|
||||
hostinfo := f.filterInsidePacket(pkt, fwPacket, rejectBuf, q, localCache)
|
||||
if hostinfo == nil {
|
||||
continue
|
||||
}
|
||||
var it txItem
|
||||
if !f.prepareTxItem(&it, hostinfo, pkt) {
|
||||
continue
|
||||
}
|
||||
it.segs = uint64(pkt.SegmentCount())
|
||||
if it.relayHI != nil {
|
||||
// The relay bookkeeping inline sends do per segment in prepareSendVia, once per item
|
||||
f.connectionManager.OutNoRebind(it.relayHI)
|
||||
f.connectionManager.RelayUsed(it.relay.LocalIndex)
|
||||
if r.inlineRelays != nil {
|
||||
*r.inlineRelays = append(*r.inlineRelays, it)
|
||||
continue
|
||||
}
|
||||
it.relayCounter = r.need(it.relayHI, it.relayHI.ConnectionState, it.segs)
|
||||
}
|
||||
it.counter = r.need(it.hostinfo, it.ci, it.segs)
|
||||
items = append(items, it)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// need adds n counters to ci's tally for this batch and returns the offset of the first one within it.
|
||||
func (r *txReserver) need(hostinfo *HostInfo, ci *ConnectionState, n uint64) uint64 {
|
||||
t := r.tunnel(ci)
|
||||
if t == nil {
|
||||
r.tunnels = append(r.tunnels, txTunnel{ci: ci, hostinfo: hostinfo})
|
||||
t = &r.tunnels[len(r.tunnels)-1]
|
||||
}
|
||||
off := t.n
|
||||
t.n += n
|
||||
return off
|
||||
}
|
||||
|
||||
// tunnel finds ci's tally, a batch rarely touches more than a couple of tunnels so a scan beats a map.
|
||||
func (r *txReserver) tunnel(ci *ConnectionState) *txTunnel {
|
||||
for i := range r.tunnels {
|
||||
if r.tunnels[i].ci == ci {
|
||||
return &r.tunnels[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reserve takes the counters collect tallied and stamps them onto items, dropping the items of any tunnel whose
|
||||
// counter is exhausted. It returns the items that are left.
|
||||
func (r *txReserver) reserve(items []txItem) []txItem {
|
||||
f := r.f
|
||||
// One atomic add per tunnel reserves the whole batch's counters before any worker sees it, so counter order on a
|
||||
// tunnel is dispatch order, which is the order the batches are flushed in. Reservation and the sender's order are
|
||||
// both taken on the reader goroutine, so there is no window for another batch to slip in between.
|
||||
for i := range r.tunnels {
|
||||
t := &r.tunnels[i]
|
||||
end := t.ci.messageCounter.Add(t.n)
|
||||
t.base = end - t.n + 1
|
||||
if end >= RejectAfterMessages {
|
||||
t.ci.messageCounter.Store(RejectAfterMessages)
|
||||
t.exhausted = true
|
||||
f.messageMetrics.TxExhausted(int64(t.n))
|
||||
if t.base <= RejectAfterMessages {
|
||||
t.hostinfo.logger(f.l).Error("Dropping outbound packets, tunnel message counter is exhausted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
n := 0
|
||||
for _, it := range items {
|
||||
t := r.tunnel(it.ci)
|
||||
if t.exhausted {
|
||||
continue
|
||||
}
|
||||
it.counter += t.base
|
||||
if it.relayHI != nil {
|
||||
rt := r.tunnel(it.relayHI.ConnectionState)
|
||||
if rt.exhausted {
|
||||
continue
|
||||
}
|
||||
it.relayCounter += rt.base
|
||||
}
|
||||
items[n] = it
|
||||
n++
|
||||
}
|
||||
clear(items[n:])
|
||||
return items[:n]
|
||||
}
|
||||
|
||||
// handoffQueue is a tun queue that can give up the buffer its last Read filled. SwapRxBuf(nil) allocates a
|
||||
// correctly sized replacement; later swaps recycle the buffers handed back.
|
||||
type handoffQueue interface {
|
||||
tio.Queue
|
||||
SwapRxBuf([]byte) []byte
|
||||
}
|
||||
|
||||
// txSlot is one staged batch. The reader fills items, a worker encrypts them into sb and signals done, and the
|
||||
// ordered sender flushes sb.
|
||||
type txSlot struct {
|
||||
f *Interface
|
||||
items []txItem
|
||||
// buf owns the queue receive buffer the items point into, swapped out at dispatch
|
||||
buf []byte
|
||||
sb *batch.SendBatch
|
||||
done chan struct{}
|
||||
// reservations hold shared tunnel credit until the flush, including for dropped counters
|
||||
reservations []txTunnel
|
||||
}
|
||||
|
||||
func (s *txSlot) run(nb []byte) {
|
||||
for i := range s.items {
|
||||
s.f.encryptTxItem(&s.items[i], nb, s.sb)
|
||||
}
|
||||
s.done <- struct{}{}
|
||||
}
|
||||
|
||||
// stagedTx is the staged transmit pipeline of one tun reader. Everything but the workers and the sender runs on the
|
||||
// reader goroutine.
|
||||
type stagedTx struct {
|
||||
txReserver
|
||||
// Relay data always leaves on the reader, including small and oversized reads. Its independent reservation
|
||||
// scratch keeps mixed reads from changing the direct pipeline's counters, gate or sender placement.
|
||||
relayReserver txReserver
|
||||
relaySlot txSlot
|
||||
q int
|
||||
cpu int // reader CPU, inline sends stay here
|
||||
senderCPU int // -1 leaves the sender within its inherited affinity
|
||||
queue handoffQueue
|
||||
pool *flowPool
|
||||
// sb and nb are the reader's own, for the sends it does itself
|
||||
sb *batch.SendBatch
|
||||
nb []byte
|
||||
|
||||
// free holds the reader's idle slots. A dispatched slot goes to the workers and, in the same order, to the
|
||||
// sender on ordered; the sender gives it back on returned once it is on the wire.
|
||||
free []*txSlot
|
||||
ordered chan *txSlot
|
||||
returned chan *txSlot
|
||||
inFlight int
|
||||
senderDone chan struct{}
|
||||
// gateInline is the routine's transmit mode, gateStreak how many reads in a row wanted the other one
|
||||
gateInline bool
|
||||
gateStreak int
|
||||
|
||||
metricGateSwitches metrics.Counter
|
||||
|
||||
metricBatches metrics.Counter
|
||||
metricInline metrics.Counter
|
||||
}
|
||||
|
||||
// newStagedTx needs a queue that hands over whole read batches, the offload (TSO/USO) queue on linux. On any other
|
||||
// queue a read is one packet, and staging it would cost a handoff per packet.
|
||||
func newStagedTx(f *Interface, queue handoffQueue, q int) *stagedTx {
|
||||
p := &stagedTx{
|
||||
txReserver: txReserver{f: f, tunnels: make([]txTunnel, 0, 4), owner: txBudgetOwner(q)},
|
||||
q: q,
|
||||
senderCPU: -1,
|
||||
queue: queue,
|
||||
sb: batch.NewSendBatch(f.writers[q], batch.SendBatchCap, batch.SendBatchCap*(udp.MTU+32)),
|
||||
nb: make([]byte, 12),
|
||||
ordered: make(chan *txSlot, f.staged.txSlots),
|
||||
returned: make(chan *txSlot, f.staged.txSlots),
|
||||
senderDone: make(chan struct{}),
|
||||
metricBatches: metrics.GetOrRegisterCounter("flow.tx.batches", nil),
|
||||
metricInline: metrics.GetOrRegisterCounter("flow.tx.inline", nil),
|
||||
// Starts inline, the pipeline is empty, unless the threshold never allows it
|
||||
gateInline: f.staged.inlineBelow > 0,
|
||||
metricGateSwitches: metrics.GetOrRegisterCounter("flow.tx.gate_switches", nil),
|
||||
}
|
||||
// Inline relay sends can share a tunnel with older direct work on this routine. They are not the ordered
|
||||
// sender's sole owner, so they must not recycle credit around a stalled direct reservation.
|
||||
p.relayReserver = txReserver{f: f, tunnels: make([]txTunnel, 0, 4)}
|
||||
p.inlineRelays = &p.relaySlot.items
|
||||
if f.pinThreads {
|
||||
p.cpu = f.threadCPU(q)
|
||||
// Only an explicit list pins the sender, and never onto its reader's CPU, where the two would serialise.
|
||||
// Automatic placement by queue index can put a busy sender on a slow core; unpinned, the scheduler moves it.
|
||||
if n := len(f.cpuAffinity); n > 0 && f.cpuAffinity[(q+1)%n] != p.cpu {
|
||||
p.senderCPU = f.cpuAffinity[(q+1)%n]
|
||||
}
|
||||
}
|
||||
p.pool = newFlowPool(f.staged.workers, f.staged.txSlots)
|
||||
|
||||
// Ciphertext adds per-segment headers and tags; the arena can grow for small segments.
|
||||
buf := queue.SwapRxBuf(nil)
|
||||
bufSize := len(buf)
|
||||
for i := range f.staged.txSlots {
|
||||
if i > 0 {
|
||||
buf = make([]byte, bufSize)
|
||||
}
|
||||
p.free = append(p.free, &txSlot{
|
||||
f: f,
|
||||
buf: buf,
|
||||
sb: batch.NewSendBatch(f.writers[q], 4*batch.SendBatchCap, bufSize+bufSize/4),
|
||||
done: make(chan struct{}, 1),
|
||||
})
|
||||
}
|
||||
go p.sender()
|
||||
return p
|
||||
}
|
||||
|
||||
// run is listenIn's loop with the staged pipeline: read, then hand each batch on, until the queue fails.
|
||||
func (p *stagedTx) run(fwPacket *firewall.ParsedPacket, rejectBuf []byte, conntrackCache *firewall.ConntrackCacheTicker) error {
|
||||
defer p.close()
|
||||
if p.f.pinThreads {
|
||||
p.f.pinThreadToCPU(p.q, p.cpu)
|
||||
}
|
||||
for {
|
||||
pkts, err := p.queue.Read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.ready()
|
||||
p.handle(pkts, fwPacket, rejectBuf, conntrackCache.Get())
|
||||
}
|
||||
}
|
||||
|
||||
// handle takes one tun read through the pipeline. It returns once the batch is queued, or sent when the reader sent
|
||||
// it itself.
|
||||
func (p *stagedTx) handle(pkts []tio.Packet, fwPacket *firewall.ParsedPacket, rejectBuf []byte, localCache firewall.ConntrackCache) {
|
||||
p.ready()
|
||||
inline := p.gate(p.small(pkts))
|
||||
if inline && p.f.routines == 1 {
|
||||
// With only one reader and an empty pipeline, no other staged reservation can be overtaken. Keep this common
|
||||
// case inexpensive.
|
||||
p.inlineSoleReader(pkts, fwPacket, rejectBuf, localCache)
|
||||
return
|
||||
}
|
||||
|
||||
slot := p.free[len(p.free)-1]
|
||||
p.free = p.free[:len(p.free)-1]
|
||||
items := p.collect(slot.items[:0], pkts, fwPacket, rejectBuf, p.q, localCache)
|
||||
if len(p.relaySlot.items) != 0 {
|
||||
p.sendRelays()
|
||||
}
|
||||
if len(items) == 0 {
|
||||
slot.items = items
|
||||
p.free = append(p.free, slot)
|
||||
return
|
||||
}
|
||||
|
||||
if p.oversized() {
|
||||
p.metricInline.Inc(1)
|
||||
p.sendLarge(&p.txReserver, items)
|
||||
slot.items = items[:0]
|
||||
p.free = append(p.free, slot)
|
||||
return
|
||||
}
|
||||
if !p.waitBudget(&p.txReserver) {
|
||||
clear(items)
|
||||
slot.items = items[:0]
|
||||
p.free = append(p.free, slot)
|
||||
return
|
||||
}
|
||||
slot.reservations = append(slot.reservations[:0], p.tunnels...)
|
||||
items = p.reserve(items)
|
||||
slot.items = items
|
||||
if len(items) == 0 {
|
||||
slot.releaseBudget()
|
||||
p.free = append(p.free, slot)
|
||||
return
|
||||
}
|
||||
|
||||
if inline {
|
||||
p.inline(slot)
|
||||
p.free = append(p.free, slot)
|
||||
return
|
||||
}
|
||||
|
||||
// The packets now live in the slot, and the queue reads into the slot's old buffer
|
||||
slot.buf = p.queue.SwapRxBuf(slot.buf)
|
||||
|
||||
p.inFlight++
|
||||
p.metricBatches.Inc(1)
|
||||
// Counters were reserved above on this goroutine and the slot takes its place in the sender's order right here,
|
||||
// before any other batch can, so the sender puts them on the wire in counter order.
|
||||
p.ordered <- slot
|
||||
p.pool.jobs <- slot
|
||||
}
|
||||
|
||||
// sendRelays keeps relay data on one send path for the lifetime of this routine. The gate's software drain only
|
||||
// waits for socket submission; switching CPUs can still overtake packets on another NIC queue. Direct data retains
|
||||
// the existing gate and sender placement. Relay credit is still shared with all other users of both tunnels.
|
||||
func (p *stagedTx) sendRelays() {
|
||||
r, slot := &p.relayReserver, &p.relaySlot
|
||||
r.tunnels = r.tunnels[:0]
|
||||
for i := range slot.items {
|
||||
it := &slot.items[i]
|
||||
it.counter = r.need(it.hostinfo, it.ci, it.segs)
|
||||
it.relayCounter = r.need(it.relayHI, it.relayHI.ConnectionState, it.segs)
|
||||
}
|
||||
if r.oversized() {
|
||||
p.metricInline.Inc(1)
|
||||
p.sendLarge(r, slot.items)
|
||||
slot.items = slot.items[:0]
|
||||
return
|
||||
}
|
||||
if !p.waitBudget(r) {
|
||||
clear(slot.items)
|
||||
slot.items = slot.items[:0]
|
||||
return
|
||||
}
|
||||
slot.reservations = append(slot.reservations[:0], r.tunnels...)
|
||||
slot.items = r.reserve(slot.items)
|
||||
p.inline(slot)
|
||||
}
|
||||
|
||||
// gate reports whether a read goes inline. Each routine holds one
|
||||
// transmit mode, inline on the reader or fanout to the workers and the sender, until gateHold reads in a row want the
|
||||
// other one, the last of which goes the new way. Choosing per read let small inline sends leave from the reader's CPU
|
||||
// between staged ones leaving from the sender's, and the receiver's TCP saw them reordered. Going inline the reader
|
||||
// first waits until everything in flight has been submitted to the socket and the sender is idle. This does not
|
||||
// drain independent NIC queues; relay data therefore always uses the reader. Going to fanout nothing is in flight:
|
||||
// inline sends finish before the reader moves on.
|
||||
func (p *stagedTx) gate(small bool) bool {
|
||||
if small == p.gateInline {
|
||||
p.gateStreak = 0
|
||||
return small
|
||||
}
|
||||
if p.gateStreak++; p.gateStreak < p.f.staged.gateHold {
|
||||
return p.gateInline
|
||||
}
|
||||
p.gateInline, p.gateStreak = small, 0
|
||||
p.metricGateSwitches.Inc(1)
|
||||
if !small {
|
||||
return false
|
||||
}
|
||||
for p.flushOldest() {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ready takes back every slot the sender has finished with, and waits for one when all of them are in flight.
|
||||
func (p *stagedTx) ready() {
|
||||
p.reap()
|
||||
if len(p.free) == 0 {
|
||||
p.release(<-p.returned)
|
||||
}
|
||||
}
|
||||
|
||||
// reap takes back every slot the sender has finished with, without waiting.
|
||||
func (p *stagedTx) reap() {
|
||||
for {
|
||||
select {
|
||||
case s := <-p.returned:
|
||||
p.release(s)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// flushOldest waits for the oldest batch in flight to reach the wire and takes its slot back. It reports false when
|
||||
// nothing is in flight.
|
||||
func (p *stagedTx) flushOldest() bool {
|
||||
if p.inFlight == 0 {
|
||||
return false
|
||||
}
|
||||
p.release(<-p.returned)
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *stagedTx) release(s *txSlot) {
|
||||
p.inFlight--
|
||||
p.free = append(p.free, s)
|
||||
}
|
||||
|
||||
// sender is the ordered send stage: it puts each batch on the wire once its worker is done, in dispatch order.
|
||||
func (p *stagedTx) sender() {
|
||||
defer close(p.senderDone)
|
||||
if p.senderCPU >= 0 {
|
||||
p.f.pinThreadToCPU(p.q, p.senderCPU)
|
||||
}
|
||||
for s := range p.ordered {
|
||||
<-s.done
|
||||
if p.f.closed.Load() {
|
||||
// The sockets are gone, a flush would only log errors
|
||||
s.sb.Reset()
|
||||
} else {
|
||||
p.f.flushSendBatch(s.sb, p.q)
|
||||
}
|
||||
s.releaseBudget()
|
||||
clear(s.items)
|
||||
s.items = s.items[:0]
|
||||
p.returned <- s
|
||||
}
|
||||
}
|
||||
|
||||
// close sends everything still in flight, in order, and stops the sender and the workers.
|
||||
func (p *stagedTx) close() {
|
||||
close(p.ordered)
|
||||
<-p.senderDone
|
||||
p.pool.close()
|
||||
}
|
||||
|
||||
// small counts segments against the inline threshold.
|
||||
func (p *stagedTx) small(pkts []tio.Packet) bool {
|
||||
below := uint64(p.f.staged.inlineBelow)
|
||||
if below == 0 {
|
||||
return false
|
||||
}
|
||||
var n uint64
|
||||
for _, pkt := range pkts {
|
||||
if n += uint64(pkt.SegmentCount()); n >= below {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// inline encrypts a budgeted batch on the reader, with no worker handoff or buffer swap. The local sender is idle,
|
||||
// but other readers may hold reservations on these tunnels, so keep our credit until the flush completes.
|
||||
func (p *stagedTx) inline(slot *txSlot) {
|
||||
p.metricInline.Inc(1)
|
||||
for i := range slot.items {
|
||||
p.f.encryptTxItem(&slot.items[i], p.nb, p.sb)
|
||||
if p.sb.Len() >= batch.SendBatchCap {
|
||||
p.f.flushSendBatch(p.sb, p.q)
|
||||
}
|
||||
}
|
||||
p.f.flushSendBatch(p.sb, p.q)
|
||||
slot.releaseBudget()
|
||||
clear(slot.items)
|
||||
slot.items = slot.items[:0]
|
||||
}
|
||||
|
||||
// inlineSoleReader needs no credit: the interface has no other tun reader and this reader has drained every
|
||||
// reservation before taking the inline path.
|
||||
func (p *stagedTx) inlineSoleReader(pkts []tio.Packet, fwPacket *firewall.ParsedPacket, rejectBuf []byte, localCache firewall.ConntrackCache) {
|
||||
p.metricInline.Inc(1)
|
||||
for _, pkt := range pkts {
|
||||
p.f.consumeInsidePacket(pkt, fwPacket, p.nb, p.sb, rejectBuf, p.q, localCache)
|
||||
if p.sb.Len() >= batch.SendBatchCap {
|
||||
p.f.flushSendBatch(p.sb, p.q)
|
||||
}
|
||||
}
|
||||
p.f.flushSendBatch(p.sb, p.q)
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
//go:build linux && !android && !e2e_testing
|
||||
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/slackhq/nebula/util"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// queuedWire models two CPU-selected NIC queues with independent completion: the reader's
|
||||
// queue is congested, while another CPU's queue drains immediately. WriteBatch returning only
|
||||
// means the kernel accepted the packets; draining staged slots does not drain a NIC queue.
|
||||
// The sampled affinity makes the schedule deterministic without a real socket or NIC. An
|
||||
// unpinned sender alternates between allowed CPUs, even if it happened not to in this run.
|
||||
func (c *affinityConn) queuedWire(readerCPU int) [][]byte {
|
||||
var slow, fast [][]byte
|
||||
wire := c.captured()
|
||||
off := 0
|
||||
for i, n := range c.sizes {
|
||||
mask := c.masks[i]
|
||||
if mask.IsSet(readerCPU) && (mask.Count() == 1 || i%2 == 0) {
|
||||
slow = append(slow, wire[off:off+n]...)
|
||||
} else {
|
||||
fast = append(fast, wire[off:off+n]...)
|
||||
}
|
||||
off += n
|
||||
}
|
||||
return append(fast, slow...)
|
||||
}
|
||||
|
||||
// TestFlowStagedTXRelayQueuedWire reproduces reorder after successful, ordered socket
|
||||
// submissions. Mixed reads switch the sticky gate with an empty software pipeline; relayed
|
||||
// data must stay on the reader throughout, without moving the direct sender. Each routine owns a flow.
|
||||
func TestFlowStagedTXRelayQueuedWire(t *testing.T) {
|
||||
if os.Getenv("NEBULA_FLOW_RING_TEST") != "1" {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestFlowStagedTXRelayQueuedWire$")
|
||||
cmd.Env = append(os.Environ(), "NEBULA_FLOW_RING_TEST=1")
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "%s", out)
|
||||
return
|
||||
}
|
||||
allowed, err := util.AllowedCPUs()
|
||||
require.NoError(t, err)
|
||||
if len(allowed) < 2 {
|
||||
t.Skip("requires two allowed CPUs")
|
||||
}
|
||||
for _, mode := range []string{"gate", "always-staged", "oversized"} {
|
||||
for _, explicit := range []bool{false, true} {
|
||||
for _, routines := range []int{1, 2} {
|
||||
for q := range routines {
|
||||
t.Run(fmt.Sprintf("%s/explicit=%t/routines=%d/q=%d", mode, explicit, routines, q), func(t *testing.T) {
|
||||
sc := gated(stagedGateHold)
|
||||
if mode != "gate" {
|
||||
sc.inlineBelow = 0
|
||||
}
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
f := sender.f
|
||||
f.pinThreads, f.routines = true, routines
|
||||
if explicit {
|
||||
f.cpuAffinity = allowed[:2]
|
||||
}
|
||||
_, relayHI, relayPeer := addTestRelay(t, sender, ReplayWindow)
|
||||
conn := &affinityConn{}
|
||||
f.writers = make([]udp.Conn, routines)
|
||||
for i := range f.writers {
|
||||
f.writers[i] = conn
|
||||
}
|
||||
shape := append(repeatBool(false, 2), repeatBool(true, stagedGateHold+2)...)
|
||||
shape = append(shape, repeatBool(false, stagedGateHold+2)...)
|
||||
if mode != "gate" {
|
||||
shape = []bool{false, true, false, true}
|
||||
}
|
||||
reads, want := gateReads(shape...)
|
||||
if mode == "oversized" {
|
||||
// A deliberately tiny outer budget alone forces the oversized fallback.
|
||||
relayHI.ConnectionState.window = NewBits(16)
|
||||
}
|
||||
queue := &affinityQueue{flowBatchQueue: newFlowBatchQueue(reads), conn: conn}
|
||||
// Each Read waits for all previous socket submissions, making software drain
|
||||
// irrelevant to the independently queued packets in queuedWire.
|
||||
f.listenIn(queue, q)
|
||||
unwrap := func(wire [][]byte) [][]byte {
|
||||
inner := make([][]byte, 0, len(wire))
|
||||
for _, pkt := range wire {
|
||||
inner = append(inner, pkt[header.Len:len(pkt)-relayPeer.dKey.Overhead()])
|
||||
}
|
||||
return inner
|
||||
}
|
||||
require.Equal(t, want, decryptWire(t, receiver, unwrap(conn.captured())), "socket submission order")
|
||||
require.Equal(t, want, decryptWire(t, receiver, unwrap(conn.queuedWire(f.threadCPU(q)))), "NIC queue completion order")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mixed reads must keep direct sends on the original staged sender, including when relay data is present.
|
||||
func TestFlowStagedTXMixedPlacement(t *testing.T) {
|
||||
if os.Getenv("NEBULA_FLOW_MIXED_TEST") != "1" {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestFlowStagedTXMixedPlacement$")
|
||||
cmd.Env = append(os.Environ(), "NEBULA_FLOW_MIXED_TEST=1")
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "%s", out)
|
||||
return
|
||||
}
|
||||
allowed, err := util.AllowedCPUs()
|
||||
require.NoError(t, err)
|
||||
if len(allowed) < 2 {
|
||||
t.Skip("requires two allowed CPUs")
|
||||
}
|
||||
for _, explicit := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("explicit=%t", explicit), func(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
_, _, relayPeer := addTestRelay(t, sender, ReplayWindow)
|
||||
direct, directReceiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
directAddr := netip.MustParseAddr("10.0.0.4")
|
||||
direct.hostinfo.vpnAddrs = []netip.Addr{directAddr}
|
||||
f := sender.f
|
||||
f.hostMap.Hosts[directAddr] = direct.hostinfo
|
||||
f.pinThreads, f.routines = true, 2
|
||||
sendCPU := -1
|
||||
if explicit {
|
||||
f.cpuAffinity = allowed[:2]
|
||||
sendCPU = allowed[1]
|
||||
}
|
||||
conn := &affinityConn{}
|
||||
f.writers = []udp.Conn{conn, conn}
|
||||
var reads [][]tio.Packet
|
||||
var wantRelay, wantDirect []decodedSeg
|
||||
for seq := range uint32(6) {
|
||||
r := flowTCPSuperpacket(0, seq, 3)
|
||||
d := flowTCPSuperpacket(1, seq, 9)
|
||||
copy(d.Bytes[16:20], directAddr.AsSlice())
|
||||
reads = append(reads, []tio.Packet{r, d})
|
||||
for i := range 3 {
|
||||
wantRelay = append(wantRelay, decodedSeg{seq: seq, idx: uint16(i)})
|
||||
}
|
||||
for i := range 9 {
|
||||
wantDirect = append(wantDirect, decodedSeg{flow: 1, seq: seq, idx: uint16(i)})
|
||||
}
|
||||
}
|
||||
queue := &affinityQueue{flowBatchQueue: newFlowBatchQueue(reads), conn: conn}
|
||||
f.listenIn(queue, 0)
|
||||
wire := conn.captured()
|
||||
var directWire, relayWire [][]byte
|
||||
off := 0
|
||||
for i, n := range conn.sizes {
|
||||
for _, pkt := range wire[off : off+n] {
|
||||
var h header.H
|
||||
require.NoError(t, h.Parse(pkt))
|
||||
cpu := sendCPU
|
||||
if h.Subtype == header.MessageRelay {
|
||||
cpu = f.threadCPU(0)
|
||||
require.NoError(t, relayPeer.VerifyRelay(nil, h.MessageCounter, pkt, make([]byte, 12)))
|
||||
relayWire = append(relayWire, pkt[header.Len:len(pkt)-relayPeer.dKey.Overhead()])
|
||||
} else {
|
||||
directWire = append(directWire, pkt)
|
||||
}
|
||||
requireFlowCPU(t, conn.masks[i:i+1], cpu, allowed)
|
||||
}
|
||||
off += n
|
||||
}
|
||||
require.Equal(t, wantDirect, decryptWire(t, directReceiver, directWire))
|
||||
require.Equal(t, wantRelay, decryptWire(t, receiver, relayWire))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A relayed batch shares its outer tunnel with older staged direct data on the SAME routine. Inline completion
|
||||
// must not refund that direct sender's credit while its oldest reservation is stalled.
|
||||
func TestFlowStagedTXRelaySharedBudget(t *testing.T) {
|
||||
sender, _ := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
_, via, _ := addTestRelay(t, sender, ReplayWindow)
|
||||
// Give the relay host the same ordinary peer metadata as a direct tunnel.
|
||||
direct := newFlowTestPeer(t, flowTestLocal, via.vpnAddrs[0], via.ConnectionState, 300, 400)
|
||||
via.buildNetworks(sender.f.myVpnNetworksTable, direct.hostinfo.ConnectionState.peerCert.Certificate)
|
||||
via.remoteIndexId = direct.hostinfo.remoteIndexId
|
||||
ci := via.ConnectionState
|
||||
ci.window = NewBits(32)
|
||||
start := ci.messageCounter.Load()
|
||||
entered, unblock := make(chan struct{}), make(chan struct{})
|
||||
var release sync.Once
|
||||
delayCrypto(direct, func(n uint64) {
|
||||
if n == start+1 {
|
||||
close(entered)
|
||||
<-unblock
|
||||
}
|
||||
})
|
||||
p := newStagedTx(sender.f, newFlowBatchQueue(nil), 0)
|
||||
defer p.close()
|
||||
defer release.Do(func() { close(unblock) })
|
||||
d := flowTCPSuperpacket(1, 0, 9)
|
||||
copy(d.Bytes[16:20], via.vpnAddrs[0].AsSlice())
|
||||
p.send([]tio.Packet{d})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("direct worker did not start")
|
||||
}
|
||||
for seq := range uint32(7) {
|
||||
p.send([]tio.Packet{flowTCPSuperpacket(0, seq, 1)})
|
||||
}
|
||||
require.Equal(t, uint64(16), (ci.txBudget.state.Load()>>24)&txBudgetMask)
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); p.send([]tio.Packet{flowTCPSuperpacket(0, 7, 1)}) }()
|
||||
select {
|
||||
case <-done:
|
||||
t.Error("relay recycled credit around a stalled direct reservation")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
require.Equal(t, start+16, ci.messageCounter.Load())
|
||||
release.Do(func() { close(unblock) })
|
||||
<-done
|
||||
p.drain()
|
||||
require.Zero(t, ci.txBudget.state.Load())
|
||||
}
|
||||
-604
@@ -1,604 +0,0 @@
|
||||
//go:build linux && !android && !e2e_testing
|
||||
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/cpupick"
|
||||
"github.com/slackhq/nebula/firewall"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/overlay/batch"
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/slackhq/nebula/util"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/goleak"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// TestReservedEncryptionMatchesInline encrypts a batch with counters reserved up front: the receiver accepts every
|
||||
// segment, in order.
|
||||
func TestReservedEncryptionMatchesInline(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedConfig{})
|
||||
packets, want := flowTestBatches(1, 3, 3, 9)
|
||||
r := txReserver{f: sender.f}
|
||||
items := r.collect(nil, packets[0], &firewall.ParsedPacket{}, make([]byte, mtu), 0, nil)
|
||||
require.Equal(t, uint64(len(want)), r.tunnels[0].n)
|
||||
sb := batch.NewSendBatch(sender.conn, 128, 65536)
|
||||
for _, it := range r.reserve(items) {
|
||||
sender.f.encryptTxItem(&it, make([]byte, 12), sb)
|
||||
}
|
||||
sender.f.flushSendBatch(sb, 0)
|
||||
require.Equal(t, want, decryptWire(t, receiver, sender.conn.captured()))
|
||||
}
|
||||
|
||||
// TestSegmentCount checks tio.Packet.SegmentCount predicts exactly the segments tio.SegmentSuperpacket cuts, odd tails included.
|
||||
func TestSegmentCount(t *testing.T) {
|
||||
require.Equal(t, 1, tio.Packet{Bytes: make([]byte, 60)}.SegmentCount())
|
||||
for _, segs := range []int{1, 2, 3, 45} {
|
||||
for _, tail := range []int{0, 1, flowTestMSS - 1} {
|
||||
pkt := flowTCPSuperpacket(0, 0, segs)
|
||||
pkt.Bytes = pkt.Bytes[:len(pkt.Bytes)-tail]
|
||||
pkt.GSO = tio.GSOInfo{Size: flowTestMSS, HdrLen: 40, CsumStart: 20, Proto: tio.GSOProtoTCP}
|
||||
want, got := pkt.SegmentCount(), 0
|
||||
require.NoError(t, tio.SegmentSuperpacket(pkt, func([]byte) error { got++; return nil }))
|
||||
require.Equal(t, want, got, "segs %d tail %d", segs, tail)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedTXOrderAndCounters runs the staged transmit pipeline with shuffled workers and a slow socket, so the
|
||||
// sender lags and the reader runs into backpressure, then fails the tun read with batches in flight: the wire must
|
||||
// carry every segment once, in tun read order, under strictly increasing counters that were each reserved exactly
|
||||
// once, and the read error is still reported.
|
||||
func TestFlowStagedTXOrderAndCounters(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
for _, cipher := range []noise.CipherFunc{noiseutil.CipherAESGCM, noise.CipherChaChaPoly} {
|
||||
t.Run(cipher.CipherName(), func(t *testing.T) {
|
||||
if cipher.CipherName() == noiseutil.CipherAESGCM.CipherName() && noiseutil.EncryptLockNeeded {
|
||||
t.Skip("AES-GCM requires encryption in nonce order")
|
||||
}
|
||||
sender, receiver := newFlowTestPair(t, cipher, stagedOn(4))
|
||||
delayCrypto(sender, func(n uint64) {
|
||||
if n%54 == 0 {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
})
|
||||
// Far slower than the reader, even under the race detector
|
||||
sender.conn.delay = 8 * time.Millisecond
|
||||
batches, want := flowTestBatches(60, 6, 3, 9)
|
||||
start := sender.hostinfo.ConnectionState.messageCounter.Load()
|
||||
tx := metrics.GetOrRegisterCounter("flow.tx.batches", nil)
|
||||
tx0 := tx.Count()
|
||||
sender.f.listenIn(newFlowBatchQueue(batches), 0)
|
||||
require.Equal(t, int64(len(batches)), tx.Count()-tx0, "every batch uses the ordered sender")
|
||||
require.Equal(t, want, decryptWire(t, receiver, sender.conn.captured()), "wire order must match tun read order")
|
||||
require.Equal(t, start+uint64(len(want)), sender.hostinfo.ConnectionState.messageCounter.Load())
|
||||
require.NotNil(t, sender.f.fatalErr.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedTXCloseInFlight closes the interface and tun while batches are in flight, 20 times over.
|
||||
func TestFlowStagedTXCloseInFlight(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
for range 20 {
|
||||
sender, _ := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(3))
|
||||
sender.conn.delay = time.Millisecond
|
||||
batches, _ := flowTestBatches(400, 4, 2, 8)
|
||||
q := newFlowBatchQueue(batches)
|
||||
done := make(chan struct{})
|
||||
go func() { sender.f.listenIn(q, 0); close(done) }()
|
||||
require.Eventually(t, func() bool { return q.reads.Load() > 5 }, 5*time.Second, 100*time.Microsecond)
|
||||
sender.f.closed.Store(true)
|
||||
require.NoError(t, q.Close())
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedTXExhausted drops every batch of a tunnel whose counter runs out, like inline sends do.
|
||||
func TestFlowStagedTXExhausted(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sender, _ := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
ci := sender.hostinfo.ConnectionState
|
||||
ci.messageCounter.Store(RejectAfterMessages - 3)
|
||||
sender.f.listenIn(newFlowBatchQueue([][]tio.Packet{{flowTCPSuperpacket(0, 0, 10)}, {flowTCPSuperpacket(0, 1, 2)}}), 0)
|
||||
require.Empty(t, sender.conn.captured())
|
||||
require.Equal(t, RejectAfterMessages, ci.messageCounter.Load())
|
||||
require.Equal(t, int64(12), sender.f.messageMetrics.txExhausted.Count())
|
||||
require.Zero(t, ci.txBudget.state.Load())
|
||||
}
|
||||
|
||||
// TestFlowStagedTXRelay sends staged batches, and an empty read, through a relay: outer and inner layers both verify,
|
||||
// in order, and go to the relay.
|
||||
// With a tiny MSS, the middle superpacket alone exceeds the tunnels' whole credit: it must be split, not admitted as an
|
||||
// unbounded lone batch, with either replay window.
|
||||
func TestFlowStagedTXRelay(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
for _, window := range budgetWindows {
|
||||
t.Run(fmt.Sprintf("window=%d", window), func(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(2))
|
||||
sender.hostinfo.ConnectionState.window = NewBits(window)
|
||||
receiver.hostinfo.ConnectionState.window = NewBits(window)
|
||||
relayRemote, relayHI, relayPeer := addTestRelay(t, sender, window)
|
||||
batches, want := flowTestBatches(2, 3, 1, 6)
|
||||
var payload []byte
|
||||
large := flowTCPSuperpacket(0, 9, 45)
|
||||
large.GSO.Size = 1
|
||||
payload = append([]byte(nil), large.Bytes[40:]...)
|
||||
batches = [][]tio.Packet{batches[0], {large}, batches[1]}
|
||||
sender.f.listenIn(newFlowBatchQueue(append(batches, nil)), 0)
|
||||
wire := sender.conn.captured()
|
||||
require.Len(t, wire, len(want)+len(payload))
|
||||
var got []decodedSeg
|
||||
var tiny []byte
|
||||
var lastOuter, lastInner uint64
|
||||
for i, pkt := range wire {
|
||||
require.Equal(t, relayRemote, sender.conn.addrs[i])
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(pkt))
|
||||
require.Greater(t, h.MessageCounter, lastOuter)
|
||||
lastOuter = h.MessageCounter
|
||||
require.NoError(t, relayPeer.VerifyRelay(nil, h.MessageCounter, pkt, make([]byte, 12)))
|
||||
pkt = pkt[header.Len : len(pkt)-16]
|
||||
require.NoError(t, h.Parse(pkt))
|
||||
require.Greater(t, h.MessageCounter, lastInner)
|
||||
lastInner = h.MessageCounter
|
||||
plain, err := receiver.hostinfo.ConnectionState.Decrypt(receiver.f.l, h.MessageCounter, pkt, make([]byte, 12))
|
||||
require.NoError(t, err)
|
||||
if len(plain) == 41 {
|
||||
tiny = append(tiny, plain[40])
|
||||
} else {
|
||||
got = append(got, decodeSeg(plain[40:]))
|
||||
}
|
||||
}
|
||||
require.Equal(t, want, got)
|
||||
require.Equal(t, payload, tiny)
|
||||
require.Zero(t, sender.hostinfo.ConnectionState.txBudget.state.Load())
|
||||
require.Zero(t, relayHI.ConnectionState.txBudget.state.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// addTestRelay makes sender reach its peer only through a relay tunnel with replay windows of window. It returns the
|
||||
// relay's underlay address, its hostinfo and the relay's side of the tunnel.
|
||||
func addTestRelay(t testing.TB, sender *flowTestPeer, window uint64) (netip.AddrPort, *HostInfo, *ConnectionState) {
|
||||
relayInit, relayResp := runTestHandshake(t)
|
||||
relayCI, err := newConnectionStateFromResult(relayInit)
|
||||
require.NoError(t, err)
|
||||
relayPeer, err := newConnectionStateFromResult(relayResp)
|
||||
require.NoError(t, err)
|
||||
relayCI.window, relayPeer.window = NewBits(window), NewBits(window)
|
||||
|
||||
relayAddr := netip.MustParseAddr("10.0.0.3")
|
||||
relayRemote := netip.MustParseAddrPort("192.0.2.3:4242")
|
||||
relay := &Relay{Type: TerminalType, State: Established, LocalIndex: 5, RemoteIndex: 6, PeerAddr: flowTestRemote}
|
||||
relayHI := &HostInfo{
|
||||
vpnAddrs: []netip.Addr{relayAddr},
|
||||
ConnectionState: relayCI,
|
||||
relayState: RelayState{
|
||||
relayForByAddr: map[netip.Addr]*Relay{flowTestRemote: relay},
|
||||
relayForByIdx: map[uint32]*Relay{relay.LocalIndex: relay},
|
||||
},
|
||||
}
|
||||
relayHI.remote.Store(&relayRemote)
|
||||
sender.f.hostMap.Hosts[relayAddr] = relayHI
|
||||
sender.hostinfo.remote.Store(&netip.AddrPort{})
|
||||
sender.hostinfo.relayState.relays = []netip.Addr{relayAddr}
|
||||
return relayRemote, relayHI, relayPeer
|
||||
}
|
||||
|
||||
// affinityQueue makes every read start with an idle pipeline: before each read it waits until conn has sent what was
|
||||
// read before, recording how many sends that took, then samples the reader's actual thread affinity.
|
||||
type affinityQueue struct {
|
||||
*flowBatchQueue
|
||||
conn *affinityConn
|
||||
sent int
|
||||
boundaries []int
|
||||
masks []unix.CPUSet
|
||||
}
|
||||
|
||||
func (q *affinityQueue) Read() ([]tio.Packet, error) {
|
||||
if n := q.reads.Load(); n > 0 {
|
||||
for _, p := range q.batches[n-1] {
|
||||
q.sent += p.SegmentCount()
|
||||
}
|
||||
}
|
||||
q.boundaries = append(q.boundaries, q.conn.waitFor(q.sent))
|
||||
q.masks = append(q.masks, threadMask())
|
||||
return q.flowBatchQueue.Read()
|
||||
}
|
||||
|
||||
// affinityConn captures every send, sampling the sending thread's actual affinity in each WriteBatch.
|
||||
type affinityConn struct {
|
||||
flowCaptureConn
|
||||
masks []unix.CPUSet
|
||||
sizes []int
|
||||
}
|
||||
|
||||
func (c *affinityConn) WriteBatch(p [][]byte, addrs []netip.AddrPort) (int, error) {
|
||||
mask := threadMask()
|
||||
c.mu.Lock()
|
||||
c.masks = append(c.masks, mask)
|
||||
c.sizes = append(c.sizes, len(p))
|
||||
c.mu.Unlock()
|
||||
return c.flowCaptureConn.WriteBatch(p, addrs)
|
||||
}
|
||||
|
||||
// waitFor waits until n packets were sent and returns how many WriteBatch calls that took.
|
||||
func (c *affinityConn) waitFor(n int) int {
|
||||
for len(c.captured()) < n {
|
||||
time.Sleep(50 * time.Microsecond)
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.masks)
|
||||
}
|
||||
|
||||
func threadMask() unix.CPUSet {
|
||||
var mask unix.CPUSet
|
||||
if err := unix.SchedGetaffinity(0, &mask); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return mask
|
||||
}
|
||||
|
||||
// requireFlowCPU checks every mask is just cpu, or with cpu -1, the whole allowed set.
|
||||
func requireFlowCPU(t *testing.T, masks []unix.CPUSet, cpu int, allowed []int) {
|
||||
t.Helper()
|
||||
require.NotEmpty(t, masks)
|
||||
for _, mask := range masks {
|
||||
if cpu >= 0 {
|
||||
require.Equal(t, 1, mask.Count())
|
||||
require.True(t, mask.IsSet(cpu), "expected CPU %d", cpu)
|
||||
continue
|
||||
}
|
||||
require.Equal(t, len(allowed), mask.Count())
|
||||
for _, c := range allowed {
|
||||
require.True(t, mask.IsSet(c))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedTXAffinity sends large, small and large reads, each from an idle pipeline, and checks the order on the
|
||||
// wire and where the reader and each send actually ran, for every CPU placement, with one routine and with several. A
|
||||
// staged sender is only pinned to an explicit entry other than its reader's CPU, and inline sends stay on the reader.
|
||||
// With the threshold, only the small read goes inline.
|
||||
// The reader only reads again once its earlier reads are on the wire, so this also checks the sender never waits for
|
||||
// the reader. Pinning threads changes the process, so the test runs in a child.
|
||||
func TestFlowStagedTXAffinity(t *testing.T) {
|
||||
if os.Getenv("NEBULA_FLOW_AFFINITY_TEST") != "1" {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestFlowStagedTXAffinity$")
|
||||
cmd.Env = append(os.Environ(), "NEBULA_FLOW_AFFINITY_TEST=1")
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, "%s", out)
|
||||
return
|
||||
}
|
||||
allowed, err := util.AllowedCPUs()
|
||||
require.NoError(t, err)
|
||||
for _, placement := range []string{"fallback", "automatic", "explicit", "explicit-single"} {
|
||||
for _, pin := range []bool{false, true} {
|
||||
for _, sc := range sendPaths() {
|
||||
for _, routines := range []int{1, 2} {
|
||||
t.Run(fmt.Sprintf("%s/pin=%t/%s/routines=%d", placement, pin, stagedName(sc), routines), func(t *testing.T) {
|
||||
if pin && len(allowed) < 2 {
|
||||
t.Skip("requires at least two allowed CPUs")
|
||||
}
|
||||
if sc.inlineBelow > 0 {
|
||||
// Switch on every read that wants the other mode, so the small read goes inline between
|
||||
// staged ones
|
||||
sc.gateHold = 1
|
||||
}
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
f := sender.f
|
||||
f.pinThreads, f.routines = pin, routines
|
||||
switch placement {
|
||||
case "automatic":
|
||||
f.defaultCpuAffinity = cpupick.Default(routines, 4242, nil)
|
||||
case "explicit":
|
||||
f.cpuAffinity = []int{allowed[len(allowed)-1], allowed[0]}
|
||||
case "explicit-single":
|
||||
f.cpuAffinity = allowed[len(allowed)-1:]
|
||||
}
|
||||
readerCPU, sendCPU := -1, -1
|
||||
if pin {
|
||||
readerCPU = f.threadCPU(0)
|
||||
sendCPU = readerCPU
|
||||
if sc.tx {
|
||||
// Never the reader's CPU, and no automatic choice: unpinned unless an explicit entry fits
|
||||
sendCPU = -1
|
||||
if placement == "explicit" {
|
||||
sendCPU = f.cpuAffinity[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
smallCPU := sendCPU
|
||||
if sc.inlineBelow > 0 {
|
||||
smallCPU = readerCPU
|
||||
}
|
||||
conn := &affinityConn{}
|
||||
f.writers = []udp.Conn{conn}
|
||||
batches, want := flowTestBatches(3, 8, 1, 45)
|
||||
batches[1] = batches[1][:1]
|
||||
want = append(want[:405], want[720:]...)
|
||||
q := &affinityQueue{flowBatchQueue: newFlowBatchQueue(batches), conn: conn}
|
||||
inline := metrics.GetOrRegisterCounter("flow.tx.inline", nil)
|
||||
inline0 := inline.Count()
|
||||
f.listenIn(q, 0)
|
||||
require.Equal(t, want, decryptWire(t, receiver, conn.captured()))
|
||||
if sc.inlineBelow > 0 {
|
||||
require.Equal(t, int64(1), inline.Count()-inline0)
|
||||
}
|
||||
b := q.boundaries
|
||||
requireFlowCPU(t, q.masks, readerCPU, allowed)
|
||||
requireFlowCPU(t, conn.masks[:b[1]], sendCPU, allowed)
|
||||
requireFlowCPU(t, conn.masks[b[1]:b[2]], smallCPU, allowed)
|
||||
requireFlowCPU(t, conn.masks[b[2]:], sendCPU, allowed)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sendPaths is inline, staged and, with the threshold, adaptive transmit.
|
||||
func sendPaths() []stagedConfig {
|
||||
return []stagedConfig{{}, stagedOn(2), adaptive(2)}
|
||||
}
|
||||
|
||||
// requireAccepted checks the receiver accepts every packet of wire in the order given. With several readers the wire
|
||||
// order differs from counter order, but every packet must still authenticate and fit within the replay window.
|
||||
func requireAccepted(t *testing.T, receiver *flowTestPeer, wire [][]byte) {
|
||||
t.Helper()
|
||||
for _, pkt := range wire {
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(pkt))
|
||||
_, err := receiver.hostinfo.ConnectionState.Decrypt(receiver.f.l, h.MessageCounter, pkt, make([]byte, 12))
|
||||
require.NoError(t, err, "counter %d", h.MessageCounter)
|
||||
}
|
||||
}
|
||||
|
||||
// slowConn delays every WriteBatch, then writes to the shared capture.
|
||||
type slowConn struct {
|
||||
*flowCaptureConn
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (c slowConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error) {
|
||||
time.Sleep(c.delay)
|
||||
return c.flowCaptureConn.WriteBatch(bufs, addrs)
|
||||
}
|
||||
|
||||
// TestFlowTXBudgetManyReaders saturates one tunnel from eight readers, one of them on a slow socket that lets the
|
||||
// others overtake it, alongside a burst of unreserved control messages: in the order they reach the wire, every packet
|
||||
// is accepted by the receiver's replay window, so none was sent twice or displaced past the window.
|
||||
func TestFlowTXBudgetManyReaders(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
for _, window := range budgetWindows {
|
||||
t.Run(fmt.Sprintf("window=%d", window), func(t *testing.T) {
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, stagedOn(3))
|
||||
ci := sender.hostinfo.ConnectionState
|
||||
ci.window = NewBits(window)
|
||||
receiver.hostinfo.ConnectionState.window = NewBits(window)
|
||||
sender.f.routines = 8
|
||||
sender.f.writers = append([]udp.Conn{slowConn{sender.conn, 4 * time.Millisecond}}, slices.Repeat(sender.f.writers, 8)...)
|
||||
start := ci.messageCounter.Load()
|
||||
var wg sync.WaitGroup
|
||||
for q := range 8 {
|
||||
wg.Go(func() {
|
||||
batches, _ := flowTestBatches(28, 8, 2, 45)
|
||||
p := newStagedTx(sender.f, newFlowBatchQueue(nil), q)
|
||||
defer p.close()
|
||||
for _, packets := range batches {
|
||||
p.send(packets)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A bounded burst of unreserved control messages uses the documented margin, on writer 8
|
||||
wg.Go(func() {
|
||||
for range 128 {
|
||||
sender.f.sendNoMetrics(header.Test, header.TestRequest, ci, sender.hostinfo, flowTestUnder, []byte("x"), make([]byte, 12), make([]byte, mtu), 8)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
}
|
||||
})
|
||||
wg.Wait()
|
||||
require.Zero(t, ci.txBudget.state.Load())
|
||||
wire := sender.conn.captured()
|
||||
require.Len(t, wire, 8*28*360+128)
|
||||
require.Equal(t, start+uint64(len(wire)), ci.messageCounter.Load())
|
||||
requireAccepted(t, receiver, wire)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlowStagedTXInlineOnlyWhenEmpty: a small read behind a staged batch still in flight must not go inline before
|
||||
// that batch is on the wire, it would overtake it.
|
||||
func TestFlowStagedTXInlineOnlyWhenEmpty(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sc := adaptive(2)
|
||||
sc.inlineBelow, sc.gateHold = 4, 1
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
p := newStagedTx(sender.f, newFlowBatchQueue(nil), 0)
|
||||
block := make(chan struct{})
|
||||
delayCrypto(sender, func(uint64) { <-block })
|
||||
batches, want := flowTestBatches(1, 4, 1, 3)
|
||||
p.send(batches[0][:3]) // switches to fanout, its worker is blocked
|
||||
require.Equal(t, 1, p.inFlight)
|
||||
unblock := time.AfterFunc(20*time.Millisecond, func() { close(block) })
|
||||
defer unblock.Stop()
|
||||
p.send(batches[0][3:]) // switches to inline, which waits for the staged batch first
|
||||
require.Zero(t, p.inFlight)
|
||||
p.close()
|
||||
require.Equal(t, want, decryptWire(t, receiver, sender.conn.captured()))
|
||||
}
|
||||
|
||||
// TestFlowStagedTXInlineBelowZero: with inline_below 0 an idle reader never sends a batch itself, in either
|
||||
// direction: every read goes through the workers and the ordered sender or writer.
|
||||
func TestFlowStagedTXInlineBelowZero(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
c.Settings = map[string]any{"tun": map[string]any{"staged": map[string]any{"workers": 2, "inline_below": 0}}}
|
||||
sc := parseStagedConfig(c, l)
|
||||
if !sc.tx {
|
||||
t.Skip("transmit stays inline in this build")
|
||||
}
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
batches, want := flowTestBatches(20, 2, 1, 4)
|
||||
txInline := metrics.GetOrRegisterCounter("flow.tx.inline", nil)
|
||||
tx := metrics.GetOrRegisterCounter("flow.tx.batches", nil)
|
||||
rxInline := metrics.GetOrRegisterCounter("flow.rx.inline", nil)
|
||||
txInline0, tx0, rxInline0, rx0 := txInline.Count(), tx.Count(), rxInline.Count(), rxBatches.Count()
|
||||
sender.f.listenIn(newFlowBatchQueue(batches), 0)
|
||||
wire := sender.conn.captured()
|
||||
require.Equal(t, want, decryptWire(t, receiver, wire))
|
||||
require.Zero(t, txInline.Count()-txInline0)
|
||||
require.Equal(t, int64(len(batches)), tx.Count()-tx0)
|
||||
receiver.receive(&rxConn{wire: wire, sizes: []int{1, 2, 4}})
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
require.Zero(t, rxInline.Count()-rxInline0)
|
||||
require.Positive(t, rxBatches.Count()-rx0)
|
||||
}
|
||||
|
||||
// TestFlowStagedTXDisabled: with tx false the reader never builds a staged pipeline, even on a queue that could hand
|
||||
// off its batches. Receive stays staged.
|
||||
func TestFlowStagedTXDisabled(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
c.Settings = map[string]any{"tun": map[string]any{"staged": map[string]any{"workers": 2, "tx": false}}}
|
||||
sc := parseStagedConfig(c, l)
|
||||
require.False(t, sc.tx)
|
||||
require.True(t, sc.rx)
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
batches, want := flowTestBatches(4, 8, 1, 45)
|
||||
tx := metrics.GetOrRegisterCounter("flow.tx.batches", nil)
|
||||
txInline := metrics.GetOrRegisterCounter("flow.tx.inline", nil)
|
||||
tx0, txInline0, rx0 := tx.Count(), txInline.Count(), rxBatches.Count()
|
||||
q := &swapCountQueue{flowBatchQueue: newFlowBatchQueue(batches)}
|
||||
sender.f.listenIn(q, 0)
|
||||
wire := sender.conn.captured()
|
||||
require.Equal(t, want, decryptWire(t, receiver, wire))
|
||||
require.Zero(t, q.swaps, "newStagedTx always takes the queue's buffer, so it never ran")
|
||||
require.Equal(t, tx0, tx.Count())
|
||||
require.Equal(t, txInline0, txInline.Count())
|
||||
receiver.receive(&rxConn{wire: wire, batchLen: 512})
|
||||
require.Equal(t, want, receiver.tun.segments(t))
|
||||
require.Greater(t, rxBatches.Count(), rx0)
|
||||
}
|
||||
|
||||
// swapCountQueue counts SwapRxBuf calls.
|
||||
type swapCountQueue struct {
|
||||
*flowBatchQueue
|
||||
swaps int
|
||||
}
|
||||
|
||||
func (q *swapCountQueue) SwapRxBuf(buf []byte) []byte {
|
||||
q.swaps++
|
||||
return q.flowBatchQueue.SwapRxBuf(buf)
|
||||
}
|
||||
|
||||
// TestFlowStagedTXAdaptiveBudget: a fast reader's adaptive sends must stop spending credit until another reader's
|
||||
// earlier reservation reaches the wire.
|
||||
func TestFlowStagedTXAdaptiveBudget(t *testing.T) {
|
||||
for _, shape := range []struct {
|
||||
name string
|
||||
packets, segments int
|
||||
}{
|
||||
{"single", 1, 1}, {"batch", 8, 30},
|
||||
} {
|
||||
t.Run(shape.name, func(t *testing.T) {
|
||||
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
|
||||
sc := adaptive(2)
|
||||
// p0's large read must go to the workers at once, p1 stays inline
|
||||
sc.gateHold = 1
|
||||
sender, receiver := newFlowTestPair(t, noise.CipherChaChaPoly, sc)
|
||||
sender.f.routines = 2
|
||||
sender.f.writers = []udp.Conn{sender.conn, sender.conn}
|
||||
ci := sender.hostinfo.ConnectionState
|
||||
start := ci.messageCounter.Load()
|
||||
entered, unblock := make(chan struct{}), make(chan struct{})
|
||||
delayCrypto(sender, func(n uint64) {
|
||||
if n == start+1 {
|
||||
close(entered)
|
||||
<-unblock
|
||||
}
|
||||
})
|
||||
p0 := newStagedTx(sender.f, newFlowBatchQueue(nil), 0)
|
||||
p1 := newStagedTx(sender.f, newFlowBatchQueue(nil), 1)
|
||||
defer p0.close()
|
||||
defer p1.close()
|
||||
var release sync.Once
|
||||
defer release.Do(func() { close(unblock) })
|
||||
large, _ := flowTestBatches(1, 8, 1, 45)
|
||||
p0.send(large[0])
|
||||
<-entered
|
||||
perBatch := shape.packets * shape.segments
|
||||
small, _ := flowTestBatches(9600/perBatch, shape.packets, 1, shape.segments)
|
||||
fits := int(ci.txBudgetLimit()-360) / perBatch
|
||||
for _, packets := range small[:fits] {
|
||||
p1.send(packets)
|
||||
}
|
||||
require.Equal(t, uint64(360+fits*perBatch), (ci.txBudget.state.Load()>>24)&txBudgetMask, "inline sends must spend shared credit")
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for _, packets := range small[fits:] {
|
||||
p1.send(packets)
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
t.Error("adaptive reader bypassed outstanding credit")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
require.LessOrEqual(t, ci.messageCounter.Load()-start, ci.txBudgetLimit())
|
||||
release.Do(func() { close(unblock) })
|
||||
<-done
|
||||
p0.drain()
|
||||
p1.drain()
|
||||
wire := sender.conn.captured()
|
||||
require.Len(t, wire, 360+40*240)
|
||||
requireAccepted(t, receiver, wire)
|
||||
require.Zero(t, ci.txBudget.state.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkFlowStagedTX runs reads of eight 45-segment superpackets through listenIn into a socket that discards
|
||||
// them, inline and staged.
|
||||
func BenchmarkFlowStagedTX(b *testing.B) {
|
||||
for _, cipher := range []noise.CipherFunc{noiseutil.CipherAESGCM, noise.CipherChaChaPoly} {
|
||||
for _, sc := range []stagedConfig{{}, stagedOn(4)} {
|
||||
b.Run(cipher.CipherName()+"/"+stagedName(sc), func(b *testing.B) {
|
||||
if sc.tx && cipher.CipherName() == noiseutil.CipherAESGCM.CipherName() && noiseutil.EncryptLockNeeded {
|
||||
b.Skip("AES-GCM requires encryption in nonce order")
|
||||
}
|
||||
sender, _ := newFlowTestPair(b, cipher, sc)
|
||||
sender.f.writers = []udp.Conn{udp.NoopConn{}}
|
||||
batch, _ := flowTestBatches(1, 8, 4, 45)
|
||||
batches := make([][]tio.Packet, b.N)
|
||||
for i := range batches {
|
||||
batches[i] = batch[0]
|
||||
}
|
||||
b.SetBytes(int64(8 * 45 * flowTestMSS))
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
sender.f.listenIn(newFlowBatchQueue(batches), 0)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@ 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
|
||||
|
||||
@@ -5,6 +5,8 @@ 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=
|
||||
@@ -12,8 +14,6 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/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=
|
||||
|
||||
+33
-23
@@ -61,16 +61,17 @@ 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
|
||||
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
|
||||
metricRejectedBlocklisted metrics.Counter
|
||||
f *Interface
|
||||
l *slog.Logger
|
||||
|
||||
// can be used to trigger outbound handshake for the given vpnIp
|
||||
trigger chan netip.Addr
|
||||
@@ -118,18 +119,19 @@ 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),
|
||||
l: l,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,7 +719,12 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
|
||||
response, result, err := machine.ProcessPacket(nil, packet)
|
||||
if err != nil {
|
||||
f.l.Error("Failed to process handshake packet", "from", via, "error", err)
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -849,6 +856,9 @@ 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",
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
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"
|
||||
@@ -235,6 +240,89 @@ 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.
|
||||
|
||||
@@ -18,20 +18,12 @@ import (
|
||||
)
|
||||
|
||||
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
||||
if hostinfo := f.filterInsidePacket(pkt, fwPacket, rejectBuf, q, localCache); hostinfo != nil {
|
||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
||||
}
|
||||
}
|
||||
|
||||
// filterInsidePacket parses and filters pkt, handling local traffic, destination lookup, pending handshakes and
|
||||
// the outbound firewall. It returns the hostinfo to send pkt to, or nil when pkt was dropped, rejected, forwarded
|
||||
// to self or cached for a pending handshake.
|
||||
func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, rejectBuf []byte, q int, localCache firewall.ConntrackCache) *HostInfo {
|
||||
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
||||
// only valid until the next Read on that queue. Filtering and sending
|
||||
// must finish before then. Self-forwarding writes synchronously and the
|
||||
// handshake cache copies each segment. To retain the packet beyond the
|
||||
// next Read, use pkt.Clone() to detach it from the borrow.
|
||||
// only valid until the next Read on that queue. Every consumer below
|
||||
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
||||
// synchronously; do not retain pkt outside this call. If a future
|
||||
// caller needs to keep the packet, use pkt.Clone() to detach it from
|
||||
// the borrow.
|
||||
//
|
||||
// pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
|
||||
// superpacket. In both cases the L3+L4 headers at the start describe
|
||||
@@ -46,13 +38,13 @@ func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.Parsed
|
||||
"error", err,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
// Ignore local broadcast packets
|
||||
if f.dropLocalBroadcast {
|
||||
if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
|
||||
return nil
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +71,12 @@ func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.Parsed
|
||||
}
|
||||
// Otherwise, drop. On linux, we should never see these packets - Linux
|
||||
// routes packets from the nebula addr to the nebula addr through the loopback device.
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
// Ignore multicast packets
|
||||
if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
|
||||
@@ -111,26 +103,50 @@ func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.Parsed
|
||||
"fwPacket", fwPacket,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
if !ready {
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||
if dropReason == nil {
|
||||
return hostinfo
|
||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
||||
} else {
|
||||
f.rejectInside(packet, rejectBuf, q)
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
||||
"fwPacket", fwPacket,
|
||||
"reason", dropReason,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
ci.writeLock.Lock()
|
||||
}
|
||||
c := ci.messageCounter.Add(1)
|
||||
|
||||
out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
|
||||
|
||||
out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
ci.writeLock.Unlock()
|
||||
}
|
||||
if encErr != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
|
||||
"error", encErr,
|
||||
"udpAddr", hostinfo.GetRemote(),
|
||||
"counter", c,
|
||||
)
|
||||
// Skip this segment; the rest of the superpacket can still go out. TCP will retransmit anything we drop here.
|
||||
return nil
|
||||
}
|
||||
|
||||
f.rejectInside(packet, rejectBuf, q)
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
||||
"fwPacket", fwPacket,
|
||||
"reason", dropReason,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
return out
|
||||
}
|
||||
|
||||
// sendInsideMessage encrypts a firewall-approved inside packet (or every
|
||||
@@ -140,46 +156,88 @@ func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.Parsed
|
||||
// scratch arena: SegmentSuperpacket builds each segment's plaintext in
|
||||
// segScratch[:segLen] in turn, and we encrypt directly into a fresh SendBatch slot.
|
||||
func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch *batch.SendBatch) {
|
||||
var it txItem
|
||||
if f.prepareTxItem(&it, hostinfo, pkt) {
|
||||
f.encryptTxItem(&it, nb, sendBatch)
|
||||
ci := hostinfo.ConnectionState
|
||||
if ci.eKey == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// recordOutbound marks traffic out on hostinfo, once per packet or superpacket, and when we rebound since this tunnel
|
||||
// last sent, asks the lighthouse to get the far side punching at us again.
|
||||
func (f *Interface) recordOutbound(hostinfo *HostInfo) {
|
||||
// One traffic-out mark covers every segment of the superpacket; doing it
|
||||
// per segment in sendInsideEncrypt paid an atomic store up to ~45 extra
|
||||
// times per TSO packet, inside writeLock under boring crypto.
|
||||
//
|
||||
// We rebound since this tunnel last sent, ask the lighthouse to get the far side punching at us again
|
||||
if f.connectionManager.Out(hostinfo) {
|
||||
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind epoch", "vpnAddrs", hostinfo.vpnAddrs)
|
||||
hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind epoch",
|
||||
"vpnAddrs", hostinfo.vpnAddrs,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// findRelay returns the first relay that can reach hostinfo, forgetting the ones that no longer resolve.
|
||||
func (f *Interface) findRelay(hostinfo *HostInfo) (*HostInfo, *Relay) {
|
||||
for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
|
||||
via, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
|
||||
if err == nil {
|
||||
return via, relay
|
||||
remote := hostinfo.GetRemote()
|
||||
if !remote.IsValid() { //the relay path
|
||||
//first, find our relay hostinfo:
|
||||
var relayHostInfo *HostInfo
|
||||
var relay *Relay
|
||||
var err error
|
||||
for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
|
||||
relayHostInfo, relay, err = f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
|
||||
if err != nil {
|
||||
hostinfo.relayState.DeleteRelay(relayIP)
|
||||
hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
|
||||
"relay", relayIP,
|
||||
"error", err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if relayHostInfo == nil || relay == nil {
|
||||
//failure already logged
|
||||
return
|
||||
}
|
||||
hostinfo.relayState.DeleteRelay(relayIP)
|
||||
hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo", "relay", relayIP, "error", err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// encryptMessage encodes the header for counter c and encrypts p behind it into out. The caller allocates c and
|
||||
// holds writeLock when the cipher requires encryption in nonce order.
|
||||
func (f *Interface) encryptMessage(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, ci *ConnectionState, c uint64, p, nb, out []byte, remote netip.AddrPort) []byte {
|
||||
out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
|
||||
out, err := ci.eKey.EncryptDanger(out, out, p, c, nb)
|
||||
if err != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet", "error", err, "udpAddr", remote, "counter", c)
|
||||
err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
||||
//relay header + header + plaintext + AEAD tag + relay tag
|
||||
scratch := sendBatch.Reserve(len(seg) + header.MaxOverhead)
|
||||
|
||||
innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
|
||||
if innerPacket == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
//now we need to do a relay-encrypt:
|
||||
toSend, err := f.prepareSendVia(relayHostInfo, relay, innerPacket, nb, scratch, true)
|
||||
if err != nil {
|
||||
//already logged
|
||||
return nil
|
||||
}
|
||||
|
||||
sendBatch.Commit(toSend, relayHostInfo.GetRemote())
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to segment superpacket for relay send", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
||||
// header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
|
||||
scratch := sendBatch.Reserve(header.Len + len(seg) + 16)
|
||||
|
||||
out := f.sendInsideEncrypt(hostinfo, ci, seg, scratch, nb)
|
||||
if out == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
sendBatch.Commit(out, remote)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to segment superpacket for send", "error", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
|
||||
@@ -388,33 +446,27 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
||||
nb,
|
||||
out []byte,
|
||||
nocopy bool,
|
||||
c uint64,
|
||||
) ([]byte, error) {
|
||||
// A nonzero c was reserved by the caller, who also did the connection manager bookkeeping
|
||||
reserved := c != 0
|
||||
locked := !reserved && noiseutil.EncryptLockNeeded
|
||||
if locked {
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
// NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
|
||||
via.ConnectionState.writeLock.Lock()
|
||||
}
|
||||
if !reserved {
|
||||
var ok bool
|
||||
c, ok = via.ConnectionState.NextMessageCounter()
|
||||
if !ok {
|
||||
if locked {
|
||||
via.ConnectionState.writeLock.Unlock()
|
||||
}
|
||||
f.dropExhausted(via, c, "Dropping outbound relay packets, tunnel message counter is exhausted")
|
||||
return nil, fmt.Errorf("tunnel message counter is exhausted")
|
||||
c, ok := via.ConnectionState.NextMessageCounter()
|
||||
if !ok {
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
via.ConnectionState.writeLock.Unlock()
|
||||
}
|
||||
f.connectionManager.OutNoRebind(via)
|
||||
f.dropExhausted(via, c, "Dropping outbound relay packets, tunnel message counter is exhausted")
|
||||
return nil, fmt.Errorf("tunnel message counter is exhausted")
|
||||
}
|
||||
|
||||
out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
|
||||
f.connectionManager.OutNoRebind(via)
|
||||
|
||||
// Authenticate the header and payload, but do not encrypt for this message type.
|
||||
// The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
|
||||
if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
|
||||
if locked {
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
via.ConnectionState.writeLock.Unlock()
|
||||
}
|
||||
via.logger(f.l).Error("SendVia out buffer not large enough for relay",
|
||||
@@ -438,16 +490,14 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
||||
|
||||
var err error
|
||||
out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
|
||||
if locked {
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
via.ConnectionState.writeLock.Unlock()
|
||||
}
|
||||
if err != nil {
|
||||
via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
if !reserved {
|
||||
f.connectionManager.RelayUsed(relay.LocalIndex)
|
||||
}
|
||||
f.connectionManager.RelayUsed(relay.LocalIndex)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -460,7 +510,7 @@ func (f *Interface) prepareSendVia(via *HostInfo,
|
||||
// out is a buffer used to store the result of the Encrypt operation
|
||||
// q indicates which writer to use to send the packet.
|
||||
func (f *Interface) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
|
||||
toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy, 0)
|
||||
toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
|
||||
if err != nil {
|
||||
// already logged by prepareSendVia
|
||||
return
|
||||
@@ -514,19 +564,34 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
||||
return
|
||||
}
|
||||
|
||||
// A closing tunnel needs neither traffic tracking nor another punch.
|
||||
if t != header.CloseTunnel {
|
||||
f.recordOutbound(hostinfo)
|
||||
}
|
||||
out = f.encryptMessage(t, st, hostinfo, ci, c, p, nb, out, remote)
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
ci.writeLock.Unlock()
|
||||
}
|
||||
if out == nil {
|
||||
return
|
||||
//l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
|
||||
out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
|
||||
// A closing tunnel is torn down right after this, so skip the connection manager entirely: no point recording
|
||||
// traffic or asking the lighthouse for a punch. Otherwise, if we rebound since this tunnel last sent, ask the
|
||||
// lighthouse to get the far side punching at us again.
|
||||
if t != header.CloseTunnel && f.connectionManager.Out(hostinfo) {
|
||||
f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
f.l.Debug("Lighthouse update triggered for punch due to rebind epoch",
|
||||
"vpnAddrs", hostinfo.vpnAddrs,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
|
||||
if noiseutil.EncryptLockNeeded {
|
||||
ci.writeLock.Unlock()
|
||||
}
|
||||
if err != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
|
||||
"error", err,
|
||||
"udpAddr", remote,
|
||||
"counter", c,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if remote.IsValid() {
|
||||
err = f.writers[q].WriteTo(out, remote)
|
||||
if err != nil {
|
||||
@@ -548,8 +613,19 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if via, relay := f.findRelay(hostinfo); via != nil && relay != nil {
|
||||
f.SendVia(via, relay, out, nb, fullOut[:header.Len+len(out)], true, q)
|
||||
// Try to send via a relay
|
||||
for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
|
||||
relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
|
||||
if err != nil {
|
||||
hostinfo.relayState.DeleteRelay(relayIP)
|
||||
hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
|
||||
"relay", relayIP,
|
||||
"error", err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true, q)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gaissmai/bart"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/firewall"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/overlay/batch"
|
||||
"github.com/slackhq/nebula/overlay/overlaytest"
|
||||
"github.com/slackhq/nebula/overlay/tio"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newInsideFilterTestInterface(t *testing.T, allow bool) (*Interface, *HostInfo, *capturingTun) {
|
||||
t.Helper()
|
||||
local := netip.MustParseAddr("192.0.2.1")
|
||||
remote := netip.MustParseAddr("192.0.2.2")
|
||||
f, tun := newSelfForwardInterface(local)
|
||||
f.inside = overlaytest.NoopTun{}
|
||||
f.myVpnNetworksTable = &bart.Lite{}
|
||||
f.myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.0/24"))
|
||||
f.myBroadcastAddrsTable.Insert(netip.MustParsePrefix("192.0.2.255/32"))
|
||||
f.dropLocalBroadcast, f.dropMulticast = true, true
|
||||
localCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(local, 24)}}
|
||||
peerCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(remote, 24)}}
|
||||
f.firewall = NewFirewall(f.l, time.Minute, time.Minute, time.Minute, localCert)
|
||||
if allow {
|
||||
require.NoError(t, f.firewall.AddRule(false, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||
}
|
||||
f.pki = &PKI{}
|
||||
f.pki.caPool.Store(cert.NewCAPool())
|
||||
f.hostMap = newHostMap(f.l)
|
||||
f.lightHouse = newTestLighthouse()
|
||||
f.lightHouse.amLighthouse = true // Keep destination lookup from probing other remotes.
|
||||
f.handshakeManager = NewHandshakeManager(f.l, f.hostMap, f.lightHouse, udp.NoopConn{}, defaultHandshakeConfig)
|
||||
f.handshakeManager.f = f
|
||||
f.connectionManager = &connectionManager{intf: f}
|
||||
h := &HostInfo{
|
||||
vpnAddrs: []netip.Addr{remote},
|
||||
ConnectionState: &ConnectionState{
|
||||
peerCert: &cert.CachedCertificate{Certificate: peerCert},
|
||||
},
|
||||
}
|
||||
f.hostMap.Hosts[remote] = h
|
||||
return f, h, tun
|
||||
}
|
||||
|
||||
func TestFilterInsidePacket(t *testing.T) {
|
||||
local := netip.MustParseAddr("192.0.2.1")
|
||||
remote := netip.MustParseAddr("192.0.2.2")
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
packet []byte
|
||||
allow bool
|
||||
reject bool
|
||||
ready bool
|
||||
writes int
|
||||
}{
|
||||
{name: "allowed", packet: buildIPv4(local, remote, tcpSyn), allow: true, ready: true},
|
||||
{name: "malformed", packet: []byte{0x45}, allow: true},
|
||||
{name: "broadcast", packet: buildIPv4(local, netip.MustParseAddr("192.0.2.255"), udpDatagram), allow: true},
|
||||
{name: "multicast", packet: buildIPv4(local, netip.MustParseAddr("224.0.0.1"), udpDatagram), allow: true},
|
||||
{name: "firewall drop", packet: buildIPv4(local, remote, tcpSyn)},
|
||||
{name: "firewall reject", packet: buildIPv4(local, remote, tcpSyn), reject: true, writes: 1},
|
||||
{name: "unroutable drop", packet: buildIPv4(local, netip.MustParseAddr("198.51.100.1"), tcpSyn), allow: true},
|
||||
{name: "unroutable reject", packet: buildIPv4(local, netip.MustParseAddr("198.51.100.1"), tcpSyn), allow: true, reject: true, writes: 1},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f, h, tun := newInsideFilterTestInterface(t, tt.allow)
|
||||
f.firewall.OutboundSendReject = tt.reject
|
||||
fp := &firewall.ParsedPacket{}
|
||||
got := f.filterInsidePacket(tio.Packet{Bytes: tt.packet}, fp, make([]byte, mtu), 0, nil)
|
||||
if tt.ready {
|
||||
require.Same(t, h, got)
|
||||
assert.Equal(t, local, fp.LocalAddr)
|
||||
assert.Equal(t, remote, fp.RemoteAddr)
|
||||
} else {
|
||||
require.Nil(t, got)
|
||||
}
|
||||
assert.Zero(t, h.ConnectionState.messageCounter.Load(), "filtering must not allocate encryption counters")
|
||||
assert.False(t, h.sentSinceCheck(), "filtering must not mark outbound traffic")
|
||||
require.Len(t, tun.writes, tt.writes)
|
||||
if tt.writes > 0 {
|
||||
require.GreaterOrEqual(t, len(tun.writes[0]), 40)
|
||||
assert.Equal(t, tt.packet[16:20], tun.writes[0][12:16])
|
||||
assert.Equal(t, tt.packet[12:16], tun.writes[0][16:20])
|
||||
assert.NotZero(t, tun.writes[0][33]&0x04, "reject must carry a TCP reset")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterInsidePacketSelf(t *testing.T) {
|
||||
local := netip.MustParseAddr("192.0.2.1")
|
||||
f, _, tun := newInsideFilterTestInterface(t, true)
|
||||
pkt := buildIPv4(local, local, tcpSyn)
|
||||
require.Nil(t, f.filterInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, nil, 0, nil))
|
||||
if immediatelyForwardToSelf {
|
||||
require.Len(t, tun.writes, 1)
|
||||
assert.Equal(t, pkt, tun.writes[0])
|
||||
} else {
|
||||
assert.Empty(t, tun.writes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterInsidePacketPendingHandshake(t *testing.T) {
|
||||
f, h, tun := newInsideFilterTestInterface(t, true)
|
||||
remote := h.vpnAddrs[0]
|
||||
delete(f.hostMap.Hosts, remote)
|
||||
hh := &HandshakeHostInfo{hostinfo: h}
|
||||
f.handshakeManager.vpnIps[remote] = hh
|
||||
pkt := buildIPv4(netip.MustParseAddr("192.0.2.1"), remote, udpDatagram)
|
||||
want := append([]byte(nil), pkt...)
|
||||
require.Nil(t, f.filterInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, nil, 0, nil))
|
||||
require.Len(t, hh.packetStore, 1)
|
||||
clear(pkt)
|
||||
assert.Equal(t, want, hh.packetStore[0].packet, "the handshake cache must own its packet")
|
||||
assert.Equal(t, header.Message, hh.packetStore[0].messageType)
|
||||
assert.Empty(t, tun.writes)
|
||||
assert.Zero(t, h.ConnectionState.messageCounter.Load())
|
||||
}
|
||||
|
||||
type insideFilterConn struct {
|
||||
udp.NoopConn
|
||||
packets [][]byte
|
||||
}
|
||||
|
||||
func (c *insideFilterConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
|
||||
for _, b := range bufs {
|
||||
c.packets = append(c.packets, append([]byte(nil), b...))
|
||||
}
|
||||
return len(bufs), nil
|
||||
}
|
||||
|
||||
func TestConsumeInsidePacketFilterAndSend(t *testing.T) {
|
||||
for _, allow := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "denied", true: "allowed"}[allow], func(t *testing.T) {
|
||||
f, h, _ := newInsideFilterTestInterface(t, allow)
|
||||
initR, respR := runTestHandshake(t)
|
||||
ci, err := newConnectionStateFromResult(initR)
|
||||
require.NoError(t, err)
|
||||
rci, err := newConnectionStateFromResult(respR)
|
||||
require.NoError(t, err)
|
||||
ci.peerCert = h.ConnectionState.peerCert
|
||||
h.ConnectionState = ci
|
||||
h.remoteIndexId = 100
|
||||
remote := netip.MustParseAddrPort("198.51.100.2:4242")
|
||||
h.remote.Store(&remote)
|
||||
conn := &insideFilterConn{}
|
||||
sb := batch.NewSendBatch(conn, 1, mtu)
|
||||
pkt := buildIPv4(netip.MustParseAddr("192.0.2.1"), h.vpnAddrs[0], udpDatagram)
|
||||
before := ci.messageCounter.Load()
|
||||
f.consumeInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, make([]byte, 12), sb, nil, 0, nil)
|
||||
_, err = sb.Flush()
|
||||
require.NoError(t, err)
|
||||
if !allow {
|
||||
assert.Empty(t, conn.packets)
|
||||
assert.Equal(t, before, ci.messageCounter.Load())
|
||||
assert.False(t, h.sentSinceCheck())
|
||||
return
|
||||
}
|
||||
require.Len(t, conn.packets, 1)
|
||||
assert.True(t, h.sentSinceCheck())
|
||||
hdr := &header.H{}
|
||||
require.NoError(t, hdr.Parse(conn.packets[0]))
|
||||
assert.Equal(t, header.Message, hdr.Type)
|
||||
assert.Equal(t, h.remoteIndexId, hdr.RemoteIndex)
|
||||
assert.Equal(t, before+1, hdr.MessageCounter)
|
||||
plain, err := rci.Decrypt(f.l, hdr.MessageCounter, conn.packets[0], make([]byte, 12))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, pkt, plain)
|
||||
})
|
||||
}
|
||||
}
|
||||
+86
-67
@@ -57,19 +57,14 @@ type InterfaceConfig struct {
|
||||
|
||||
// CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
|
||||
// should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
|
||||
// shorter lists than `routines` cycle. Staged sender i uses entry i+1,
|
||||
// unless that is its reader's CPU. Empty uses the automatic order. Only
|
||||
// consulted when PinThreads is true.
|
||||
// shorter lists than `routines` cycle. Empty list keeps the default
|
||||
// pin-to-(i % NumCPU) behavior. Only consulted when PinThreads is true.
|
||||
CpuAffinity []int
|
||||
// defaultCpuAffinity is the automatic pin order for readers, kept apart
|
||||
// from CpuAffinity because staged senders are only pinned to an explicit list.
|
||||
defaultCpuAffinity []int
|
||||
// PinThreads controls whether each TUN reader OS thread is pinned to a
|
||||
// single CPU (via tun.pin_threads, default true). Pinning keeps each
|
||||
// goroutine's sendmmsg on one XPS-selected NIC TX ring so per-flow
|
||||
// packets stay ordered on the wire.
|
||||
PinThreads bool
|
||||
staged stagedConfig
|
||||
|
||||
l *slog.Logger
|
||||
}
|
||||
@@ -99,13 +94,11 @@ type Interface struct {
|
||||
// should pin to. Queue i pins to cpuAffinity[i % len(cpuAffinity)].
|
||||
// Empty falls back to the default pin-to-(allowed CPU) behavior.
|
||||
// Only consulted when pinThreads is true.
|
||||
cpuAffinity []int
|
||||
defaultCpuAffinity []int
|
||||
cpuAffinity []int
|
||||
// pinThreads controls whether listenIn pins each TUN reader OS thread to
|
||||
// a CPU at all (tun.pin_threads, default true). When false, threads are
|
||||
// left free to migrate as on stock nebula.
|
||||
pinThreads bool
|
||||
staged stagedConfig
|
||||
relayManager *relayManager
|
||||
|
||||
tryPromoteEvery atomic.Uint32
|
||||
@@ -131,6 +124,8 @@ 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
|
||||
@@ -254,9 +249,7 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
||||
connectionManager: c.connectionManager,
|
||||
conntrackCacheTimeout: c.ConntrackCacheTimeout,
|
||||
cpuAffinity: c.CpuAffinity,
|
||||
defaultCpuAffinity: c.defaultCpuAffinity,
|
||||
pinThreads: c.PinThreads,
|
||||
staged: c.staged,
|
||||
udpTxErrLimiter: udpTxErrLimiter,
|
||||
udpRelayTxErrLimiter: udpRelayTxErrLimiter,
|
||||
txOversizeLimiter: txOversizeLimiter,
|
||||
@@ -350,14 +343,18 @@ 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)
|
||||
})
|
||||
}
|
||||
@@ -422,19 +419,15 @@ func (f *Interface) listenOut(i int) {
|
||||
f.readOutsidePackets(ViaSender{UdpAddr: fromUdpAddr}, payload, rxc)
|
||||
}
|
||||
|
||||
flusher := func() { f.flushOutside(rxc) }
|
||||
|
||||
var err error
|
||||
if hc, ok := li.(handoffConn); ok && f.staged.rx {
|
||||
// Every stage on its own goroutine, see flow_rx.go. rxc becomes the ordered writer's context.
|
||||
err = newStagedRx(f, i, rxc).listen(hc)
|
||||
} else {
|
||||
if f.staged.rx {
|
||||
f.l.Info("udp conn cannot hand off receive batches, receive stays inline", "reader", i)
|
||||
flusher := func() {
|
||||
if err := f.batchers[i].Flush(); err != nil {
|
||||
f.l.Error("Failed to flush tun coalescer", "error", err)
|
||||
}
|
||||
err = li.ListenOut(listener, flusher)
|
||||
clear(rxc.hostmapCache)
|
||||
}
|
||||
|
||||
err := li.ListenOut(listener, flusher)
|
||||
|
||||
// An error after teardown began is shutdown noise, the closed flag covers resources
|
||||
// Close releases itself and the cancelled ctx covers ones torn down by their owners
|
||||
// reacting to it, like the user device pipes
|
||||
@@ -446,30 +439,32 @@ func (f *Interface) listenOut(i int) {
|
||||
f.l.Debug("underlay reader is done", "reader", i)
|
||||
}
|
||||
|
||||
// threadCPU is the CPU tun reader i pins to.
|
||||
func (f *Interface) threadCPU(i int) int {
|
||||
func (f *Interface) pinThisThread(i int) {
|
||||
var cpu int
|
||||
if n := len(f.cpuAffinity); n > 0 {
|
||||
// Explicit tun.cpu_affinity list wins; parseCpuAffinity already
|
||||
// validated the entries against the allowed CPU set.
|
||||
return f.cpuAffinity[i%n]
|
||||
} else if n := len(f.defaultCpuAffinity); n > 0 {
|
||||
return f.defaultCpuAffinity[i%n]
|
||||
cpu = f.cpuAffinity[i%n]
|
||||
} else if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 {
|
||||
// Default: spread queues across the CPUs we're actually allowed to
|
||||
// run on. Under a cpuset/taskset mask these aren't 0..NumCPU-1, so
|
||||
// i % NumCPU would pick unrunnable IDs and every pin would fail.
|
||||
return allowed[i%len(allowed)]
|
||||
cpu = allowed[i%len(allowed)]
|
||||
} else {
|
||||
cpu = i % runtime.NumCPU()
|
||||
}
|
||||
return i % runtime.NumCPU()
|
||||
}
|
||||
|
||||
func (f *Interface) pinThreadToCPU(i, cpu int) {
|
||||
if err := util.PinThreadToCPU(cpu); err != nil {
|
||||
f.l.Warn("failed to pin tun processing thread to CPU", "queue", i, "cpu", cpu, "err", err)
|
||||
f.l.Warn("failed to pin tun reader to CPU", "queue", i, "cpu", cpu, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Interface) listenIn(queue tio.Queue, i int) {
|
||||
// Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
|
||||
// same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
|
||||
if f.pinThreads {
|
||||
f.pinThisThread(i)
|
||||
}
|
||||
|
||||
rejectBuf := make([]byte, mtu)
|
||||
arenaSize := batch.SendBatchCap * (udp.MTU + 32)
|
||||
sb := batch.NewSendBatch(f.writers[i], batch.SendBatchCap, arenaSize)
|
||||
@@ -478,26 +473,6 @@ func (f *Interface) listenIn(queue tio.Queue, i int) {
|
||||
|
||||
conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
|
||||
|
||||
if sq, ok := queue.(handoffQueue); ok && f.staged.tx {
|
||||
// Every stage on its own goroutine, see flow_tx.go
|
||||
err := newStagedTx(f, sq, i).run(fwPacket, rejectBuf, conntrackCache)
|
||||
if !f.closed.Load() && f.ctx.Err() == nil {
|
||||
f.l.Error("Error while reading outbound packet, closing", "error", err, "reader", i)
|
||||
f.onFatal(err)
|
||||
}
|
||||
f.l.Debug("overlay reader is done", "reader", i)
|
||||
return
|
||||
}
|
||||
if f.staged.tx {
|
||||
f.l.Info("tun queue cannot hand off read batches, transmit stays inline", "reader", i)
|
||||
}
|
||||
|
||||
// Pinning this thread (and goroutine) to a single CPU keeps every sendmmsg from this goroutine going through the
|
||||
// same TX ring on the nic, so the wire sees per-flow order. Skip entirely when tun.pin_threads is false.
|
||||
if f.pinThreads {
|
||||
f.pinThreadToCPU(i, f.threadCPU(i))
|
||||
}
|
||||
|
||||
for {
|
||||
pkts, err := queue.Read()
|
||||
if err != nil {
|
||||
@@ -568,11 +543,12 @@ func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
||||
curCert = cs.getCertificate(cert.Version1)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// 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) {
|
||||
f.l.Debug("No firewall config change detected")
|
||||
return
|
||||
}
|
||||
@@ -713,6 +689,14 @@ 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.
|
||||
@@ -722,20 +706,55 @@ func (f *Interface) Close() error {
|
||||
}
|
||||
|
||||
var errs []error
|
||||
|
||||
// Release the udp readers
|
||||
for i, u := range f.writers {
|
||||
err := u.Close()
|
||||
if err != nil {
|
||||
closeUdp := func(i int, u udp.Conn) {
|
||||
if err := u.Close(); 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)
|
||||
}
|
||||
}
|
||||
|
||||
// Release the tun device (closing the tun also closes all readers)
|
||||
closeErr := f.inside.Close()
|
||||
if closeErr != nil {
|
||||
errs = append(errs, closeErr)
|
||||
// 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 construction token so waiters know the resources are gone
|
||||
|
||||
+58
-3
@@ -135,8 +135,63 @@ func TestReloadFirewall_BadRulesFailTheReload(t *testing.T) {
|
||||
f := &Interface{pki: pki, firewall: fw, l: l}
|
||||
cfg.RegisterReloadCallback(f.reloadFirewall)
|
||||
|
||||
res := cfg.ReloadConfigString(rules("nope"))
|
||||
// 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.True(t, res.Failed)
|
||||
assert.Same(t, fw, f.firewall)
|
||||
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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//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.
|
||||
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")
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//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))
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//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")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//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
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//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, together with the peer check the server
|
||||
// applies on accept unless a group shares the socket, in which case the kernel's check
|
||||
// is the whole of it: connect(2) needs write permission on the socket file on every
|
||||
// unix we build for.
|
||||
//
|
||||
// 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; 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
return nil, fmt.Errorf("could not secure %s: %w", path, err)
|
||||
}
|
||||
|
||||
return ln, nil
|
||||
}
|
||||
|
||||
// applyAccess sets the owning group and the mode of the socket node at path. With no
|
||||
// group configured the socket is handed back to the daemon's own group, so taking the
|
||||
// key out of the config on a reload takes the access away as surely as a restart would.
|
||||
// The chown is Lchown, so a link at the path is not followed to its target.
|
||||
func applyAccess(path string, acc Access) error {
|
||||
gid, err := gidFor(acc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Lchown(path, -1, gid); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(path, acc.Mode.Perm())
|
||||
}
|
||||
|
||||
// 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.
|
||||
func clearStale(path string) error {
|
||||
fi, err := os.Stat(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.
|
||||
func removeSocket(path string) {
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
|
||||
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"
|
||||
|
||||
// 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 }
|
||||
@@ -0,0 +1,358 @@
|
||||
//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")
|
||||
}
|
||||
|
||||
// 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"))
|
||||
}
|
||||
|
||||
// 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)
|
||||
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")
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//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
|
||||
|
||||
// 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 }
|
||||
|
||||
// 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) {}
|
||||
|
||||
// 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.
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//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)
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Package localapi serves the nebula command registry over a local IPC endpoint so the
|
||||
// user who ran nebula can inspect and control it from a CLI on the same machine.
|
||||
//
|
||||
// Access is the socket's own: without a group it is 0600 to the user who ran nebula,
|
||||
// and the server checks the peer's credentials on every connection besides; with a
|
||||
// group configured it is 0660 to that group, and the kernel's check on connect is the
|
||||
// whole of it, so a member has the same control of the daemon as its user. Every
|
||||
// command in the registry is served; nothing is filtered on either side.
|
||||
//
|
||||
// # Protocol
|
||||
//
|
||||
// One JSON object in, one JSON object out, both newline terminated. It is an API, not a
|
||||
// command line: a request names a command and passes its options as named parameters,
|
||||
// rather than shipping an argv the daemon has to parse. A client that is itself a CLI
|
||||
// asks for the schema first (Request.Describe) and turns the user's flags into those
|
||||
// parameters; a client that is not need never think in flags at all.
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// ProtocolVersion is the version of the request and response envelopes. A client sending
|
||||
// a version this server does not know gets a sentence back rather than a parse error,
|
||||
// which matters because the daemon and the CLI are upgraded independently.
|
||||
const ProtocolVersion = 1
|
||||
|
||||
// MaxRequestBytes bounds the request. A request names a command and its parameters, so it
|
||||
// has no business being large, and an unbounded read is a way for a local process to
|
||||
// consume memory the packet path needs.
|
||||
const MaxRequestBytes = 64 * 1024
|
||||
|
||||
// Request is the single JSON object a client sends.
|
||||
type Request struct {
|
||||
Version int `json:"version"`
|
||||
|
||||
// Describe asks for the schema of every command this surface serves, in place of
|
||||
// running one. Command, Params and Args are ignored.
|
||||
Describe bool `json:"describe,omitempty"`
|
||||
|
||||
// Command names the command to run.
|
||||
Command string `json:"command,omitempty"`
|
||||
|
||||
// Params carries the command's options by name, with JSON's own types, true rather
|
||||
// than "true", 3 rather than "3", or as the strings a command line parsed them from,
|
||||
// which is what nebula ctl sends. Unknown names are an error, so a typo is reported
|
||||
// instead of ignored. The schema lists json and pretty on every command because the
|
||||
// command lines take them; here they are refused, since Format is how a request
|
||||
// chooses its rendering.
|
||||
Params map[string]any `json:"params,omitempty"`
|
||||
|
||||
// Args carries the command's operands, the values that are not options: the vpn
|
||||
// address `print-tunnel` prints, for instance. They stay positional because the
|
||||
// commands do not name them.
|
||||
Args []string `json:"args,omitempty"`
|
||||
|
||||
// Format asks for a rendering other than the default. "" and "json" return the
|
||||
// command's result as a JSON value, which is what a program wants. "text" asks the
|
||||
// daemon to run the command's own human rendering and return it as a string, which is
|
||||
// how `nebula ctl` shows an operator the same output the ssh server would.
|
||||
Format string `json:"format,omitempty"`
|
||||
}
|
||||
|
||||
// Response is the single JSON object a server sends back.
|
||||
type Response struct {
|
||||
Version int `json:"version"`
|
||||
|
||||
// Result is what a request for JSON produced: the command's value, or the schema
|
||||
// when the request was a Describe, as a JSON value, so a caller reads it directly
|
||||
// instead of parsing a string that happens to contain JSON.
|
||||
//
|
||||
// Whitespace inside a JSON result is not preserved: an envelope normalises it, and
|
||||
// in an API it carries no meaning anyway. Formatting a result for a human to read is
|
||||
// the client's job.
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
|
||||
// Text is what a request for text produced: the command's own human rendering, the
|
||||
// bytes it wrote and nothing else. They travel as bytes, base64 in the envelope,
|
||||
// rather than as a JSON string, because a string is UTF-8 and the rendering need
|
||||
// not be: a name from a certificate is whatever the certificate holds, and the ssh
|
||||
// server passes it through, so this does too.
|
||||
Text []byte `json:"text,omitempty"`
|
||||
|
||||
// Error explains a failure in a sentence, and is absent on success. It is the only
|
||||
// signal a caller needs: there is no separate status field, because a command that
|
||||
// failed always says why and one that succeeded never does. A command line client
|
||||
// turns its presence into a non-zero exit.
|
||||
//
|
||||
// A command that ran and refused sets Error too, alongside its Result when the
|
||||
// caller asked for JSON. That is how a refusal and a request that never ran are
|
||||
// told apart: the first has both, the second has Error alone.
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// frameError is a frame that arrived and was not one: oversized, or not the JSON object
|
||||
// the protocol defines. It is told from a failed read so the client can say the daemon
|
||||
// answered with something it could not read, rather than that it could not be reached.
|
||||
type frameError struct{ err error }
|
||||
|
||||
func (e *frameError) Error() string { return e.err.Error() }
|
||||
func (e *frameError) Unwrap() error { return e.err }
|
||||
|
||||
// readFrame reads one frame, a newline terminated JSON object, from r into v. With
|
||||
// writeFrame it is where the framing rule lives, for both directions: a frame is a
|
||||
// single line, a line over max bytes is refused rather than buffered, and a final line
|
||||
// with no newline before EOF still counts. what names the frame in errors ("request", "response"); a
|
||||
// read failure is returned wrapped, so a caller can still see io.EOF or a timeout in it.
|
||||
// strict refuses a field v does not declare, which is the daemon's reading of a request:
|
||||
// a client that misspells one deserves to hear about it, as it does for a parameter.
|
||||
// The client reads a response leniently, so a field a newer daemon adds is passed over
|
||||
// rather than fatal.
|
||||
func readFrame(r io.Reader, max int, what string, v any, strict bool) error {
|
||||
br := bufio.NewReader(io.LimitReader(r, int64(max)+1))
|
||||
|
||||
line, err := br.ReadBytes('\n')
|
||||
if err != nil && (len(line) == 0 || !errors.Is(err, io.EOF)) {
|
||||
// EOF after a partial line is the unterminated final line the rule allows, and
|
||||
// an oversized line looks the same once the LimitReader cuts it off, so both go
|
||||
// on to be judged by their length. Anything else is a failed read, whatever was
|
||||
// buffered first: a deadline that lands mid frame is a timeout, not a parse
|
||||
// error in half a document.
|
||||
return fmt.Errorf("could not read %s: %w", what, err)
|
||||
}
|
||||
|
||||
// The limit is on the body, not the frame, so the terminator does not count
|
||||
// against it. A body that exceeds max is cut off by the LimitReader before its
|
||||
// newline, so a missing terminator is also what an oversized line looks like.
|
||||
body := bytes.TrimSuffix(line, []byte{'\n'})
|
||||
if len(body) > max {
|
||||
return &frameError{fmt.Errorf("%s exceeded %d bytes", what, max)}
|
||||
}
|
||||
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
if strict {
|
||||
dec.DisallowUnknownFields()
|
||||
}
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return &frameError{fmt.Errorf("could not parse %s: %w", what, err)}
|
||||
}
|
||||
|
||||
// Strict is one object and nothing after it: a second object, or stray bytes, on
|
||||
// the line would be read as part of a request that happened to decode, and is
|
||||
// refused the way an unknown field is.
|
||||
if strict {
|
||||
if _, err := dec.Token(); err != io.EOF {
|
||||
return fmt.Errorf("could not parse %s: unexpected data after the object", what)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeFrame writes v to w as one frame: the JSON object and the newline that ends it.
|
||||
func writeFrame(w io.Writer, v any) error {
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not encode frame: %w", err)
|
||||
}
|
||||
|
||||
_, err = w.Write(append(body, '\n'))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestReadFrameLimitIsOnTheBody pins the framing rule at its edge: the limit bounds the
|
||||
// JSON body, so the newline that terminates the frame must not count against it.
|
||||
func TestReadFrameLimitIsOnTheBody(t *testing.T) {
|
||||
// A JSON string whose encoded form is exactly n bytes, with or without a terminator.
|
||||
body := func(n int) string {
|
||||
return fmt.Sprintf(`"%s"`, strings.Repeat("a", n-2))
|
||||
}
|
||||
|
||||
var v string
|
||||
|
||||
// Exactly at the limit, terminated: accepted.
|
||||
v = ""
|
||||
require.NoError(t, readFrame(bytes.NewReader([]byte(body(64)+"\n")), 64, "request", &v, true))
|
||||
assert.Len(t, v, 62)
|
||||
|
||||
// Exactly at the limit, EOF instead of a newline: still accepted.
|
||||
v = ""
|
||||
require.NoError(t, readFrame(bytes.NewReader([]byte(body(64))), 64, "request", &v, true))
|
||||
assert.Len(t, v, 62)
|
||||
|
||||
// One byte over: refused as oversized, not as a parse failure.
|
||||
err := readFrame(bytes.NewReader([]byte(body(65)+"\n")), 64, "request", &v, true)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "exceeded 64 bytes")
|
||||
}
|
||||
|
||||
// stallingReader hands out its bytes and then fails with err, the shape of a peer that
|
||||
// sends part of a frame and then stops, until the deadline on the connection lands.
|
||||
type stallingReader struct {
|
||||
data []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *stallingReader) Read(p []byte) (int, error) {
|
||||
if len(r.data) == 0 {
|
||||
return 0, r.err
|
||||
}
|
||||
n := copy(p, r.data)
|
||||
r.data = r.data[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
type timeoutError struct{}
|
||||
|
||||
func (timeoutError) Error() string { return "i/o timeout" }
|
||||
func (timeoutError) Timeout() bool { return true }
|
||||
func (timeoutError) Temporary() bool { return true }
|
||||
|
||||
// TestReadFramePartialLineThenReadErrorIsTheError: a read that fails after part of a
|
||||
// frame has arrived is a failed read, and the caller sees that error. The old behaviour
|
||||
// treated the fragment as the whole frame and reported a parse failure, so a client
|
||||
// that stalled mid request was told its JSON was malformed, and a daemon that stalled
|
||||
// mid response hid the timeout the client's error path looks for.
|
||||
func TestReadFramePartialLineThenReadErrorIsTheError(t *testing.T) {
|
||||
var v map[string]any
|
||||
|
||||
err := readFrame(&stallingReader{data: []byte(`{"command": "hel`), err: timeoutError{}}, 1024, "request", &v, true)
|
||||
require.Error(t, err)
|
||||
var ne net.Error
|
||||
require.ErrorAs(t, err, &ne, "the timeout is still visible through the wrapping: %v", err)
|
||||
assert.True(t, ne.Timeout())
|
||||
assert.NotContains(t, err.Error(), "parse", "a stalled peer is not a parse failure")
|
||||
|
||||
// EOF after an unterminated line is the one exception: a final line with no newline
|
||||
// is still a frame.
|
||||
v = nil
|
||||
require.NoError(t, readFrame(&stallingReader{data: []byte(`{"command": "help"}`), err: io.EOF}, 1024, "request", &v, true))
|
||||
assert.Equal(t, "help", v["command"])
|
||||
|
||||
// And an unterminated line that is EOF only because the limit cut it off is still
|
||||
// reported as oversized.
|
||||
err = readFrame(bytes.NewReader([]byte(strings.Repeat("a", 70)+"\n")), 64, "request", &v, true)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "exceeded 64 bytes")
|
||||
}
|
||||
|
||||
// TestReadFrameUnknownFieldIsRefusedWhenStrict: the daemon refuses a request field it
|
||||
// does not know, as it refuses an unknown parameter, so a misspelling is reported rather
|
||||
// than ignored; the client, reading leniently, passes over a field a newer daemon sends.
|
||||
func TestReadFrameUnknownFieldIsRefusedWhenStrict(t *testing.T) {
|
||||
var req Request
|
||||
err := readFrame(bytes.NewReader([]byte(`{"version":1,"comand":"help"}`+"\n")), 1024, "request", &req, true)
|
||||
require.ErrorContains(t, err, `unknown field "comand"`)
|
||||
|
||||
var res Response
|
||||
require.NoError(t, readFrame(bytes.NewReader([]byte(`{"version":1,"later":true}`+"\n")), 1024, "response", &res, false))
|
||||
assert.Equal(t, 1, res.Version)
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultMaxConns caps concurrent connections. Exceeding it is rejected rather than
|
||||
// queued: a queue turns a load problem into a latency problem and hides it.
|
||||
defaultMaxConns = 8
|
||||
|
||||
// readTimeout bounds how long a client may take to send its request line.
|
||||
readTimeout = 10 * time.Second
|
||||
|
||||
// writeTimeout bounds a single write. A client that stops reading is dropped rather
|
||||
// than waited on, so a paused terminal cannot pin daemon resources.
|
||||
writeTimeout = 30 * time.Second
|
||||
|
||||
// defaultSlowAfter is how long a command may run before the daemon says so. A
|
||||
// command holds a connection slot until it returns, and one that never returns
|
||||
// holds it for good; after enough of those the socket answers only "busy". The
|
||||
// warning is what tells an operator that from load, and names the command.
|
||||
defaultSlowAfter = 30 * time.Second
|
||||
)
|
||||
|
||||
// Server serves a command registry over a local socket to the user who ran nebula.
|
||||
type Server struct {
|
||||
l *slog.Logger
|
||||
src *commands.Registry
|
||||
|
||||
maxConns int
|
||||
slowAfter time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
ln net.Listener
|
||||
path string
|
||||
running bool
|
||||
unwatch func() bool
|
||||
|
||||
sem chan struct{}
|
||||
euid uint32
|
||||
|
||||
// access is what the socket at path was bound with, so a reload that changes only
|
||||
// the group or the mode is applied without moving the socket.
|
||||
access Access
|
||||
|
||||
// trustSocket is set while a group shares the socket. The kernel admitted the peer
|
||||
// through the socket's mode and group, which is the whole access control then, and
|
||||
// the peer check in serve stands aside: on unix it sees the peer's uid and primary
|
||||
// gid only, so it could not tell a member of the group from anyone else.
|
||||
trustSocket atomic.Bool
|
||||
}
|
||||
|
||||
// NewServer returns a Server that will serve every command in reg, including one
|
||||
// registered on it after the server is built.
|
||||
func NewServer(l *slog.Logger, reg *commands.Registry) *Server {
|
||||
return &Server{
|
||||
l: l,
|
||||
src: reg,
|
||||
maxConns: defaultMaxConns,
|
||||
slowAfter: defaultSlowAfter,
|
||||
// The same identity the client's owner check is made for, so the peer check
|
||||
// cannot disagree with it, and so a test can stand in for it the same way.
|
||||
euid: currentUID(),
|
||||
}
|
||||
}
|
||||
|
||||
// Rebind brings the server up at path, moves a running server there, and serves it until
|
||||
// Stop or ctx cancellation. It is the one way the server comes up, so Wire's first
|
||||
// attempt and its reload callback are the same call, and a server already serving path
|
||||
// is left as it is: Wire registers the callback before the first attempt, so a HUP that
|
||||
// lands between the two has the callback do the first bind, and the first attempt then
|
||||
// finds the socket it was about to create already up.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// s.mu is held for the whole operation, bind included. Releasing it around listen would
|
||||
// let a Stop land in between, and this would then install a fresh listener on a server
|
||||
// that had just shut down, leaving a live socket on disk until the process exits. listen
|
||||
// does not take s.mu, so holding it costs the other methods one bind's wait, at most the
|
||||
// stale socket probe, once per reload.
|
||||
//
|
||||
// An error here is never fatal to the caller: nebula keeps forwarding packets without a
|
||||
// control endpoint, and the caller is expected to log and carry on.
|
||||
func (s *Server) Rebind(ctx context.Context, path string, acc Access) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// Set before the access is applied, not after, so no connection the new access
|
||||
// admits is checked against the old setting. Early is safe either way: a member
|
||||
// arriving before a group's mode is set is refused by the kernel, and with a group
|
||||
// being taken away the peer check applies a moment before the mode tightens.
|
||||
prev := s.trustSocket.Swap(acc.shared())
|
||||
err := s.rebindLocked(ctx, path, acc)
|
||||
if err != nil {
|
||||
// Whatever was serving still is, with the access it had.
|
||||
s.trustSocket.Store(prev)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) rebindLocked(ctx context.Context, path string, acc Access) error {
|
||||
reopening := false
|
||||
if s.running && s.path == path {
|
||||
if s.access == acc {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Only the access changed. On unix it is set on the socket in place; on windows
|
||||
// the descriptor is fixed when the pipe is created, so the pipe is created again.
|
||||
// The name cannot be held twice, so the old one goes first, and a bind that then
|
||||
// fails leaves the server down rather than on the access the operator asked to
|
||||
// change; that is reported.
|
||||
err := applyAccess(path, acc)
|
||||
if err == nil {
|
||||
s.access = acc
|
||||
s.l.Info("Changed the local control socket's 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)
|
||||
}
|
||||
reopening = true
|
||||
release(s.ln, s.path)
|
||||
s.ln, s.path, s.running, s.access = nil, "", false, Access{}
|
||||
}
|
||||
|
||||
ln, err := listen(path, acc)
|
||||
if err != nil {
|
||||
if reopening {
|
||||
return fmt.Errorf("the local control socket was closed to change its access and could not be created again: %w", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// A reload that arrives during shutdown must not bring the endpoint back. Stop is
|
||||
// not terminal (Rebind after Stop is allowed, and is how a server whose first bind
|
||||
// failed comes up), so running is no guide; the context is what shutdown cancels,
|
||||
// and it is checked here, while nothing else can change the server's state.
|
||||
if err := ctx.Err(); err != nil {
|
||||
release(ln, path)
|
||||
return fmt.Errorf("not starting the local control socket, nebula is shutting down: %w", err)
|
||||
}
|
||||
|
||||
oldLn, oldPath := s.ln, s.path
|
||||
s.ln = ln
|
||||
s.path = path
|
||||
s.access = acc
|
||||
s.running = true
|
||||
sem := s.semaphore()
|
||||
|
||||
s.watchLocked(ctx)
|
||||
|
||||
// Stop accepting on the old listener. In flight commands keep their connections,
|
||||
// which stay usable until they finish. Its accept loop exits on the closed-listener
|
||||
// error, so it is gone as soon as this returns. oldPath differs from path whenever
|
||||
// oldLn is set: a running server on the same path returned above.
|
||||
if oldLn != nil {
|
||||
release(oldLn, oldPath)
|
||||
}
|
||||
|
||||
s.l.Info("Local control socket listening", "path", path, "access", acc.String())
|
||||
|
||||
go func() {
|
||||
s.accept(ln, sem)
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// watchLocked stops the server when ctx is cancelled. One watcher covers a run of the
|
||||
// server, 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 server must not stack a second
|
||||
// watcher on the same ctx. Stop detaches the watcher, so a server 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 s.mu.
|
||||
func (s *Server) watchLocked(ctx context.Context) {
|
||||
if s.unwatch != nil {
|
||||
return
|
||||
}
|
||||
s.unwatch = context.AfterFunc(ctx, s.Stop)
|
||||
}
|
||||
|
||||
// Path returns the socket path currently being served, or "" when stopped.
|
||||
func (s *Server) Path() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.path
|
||||
}
|
||||
|
||||
// Stop closes the listener and removes the socket. In flight commands are allowed to
|
||||
// finish; Stop does not wait for them.
|
||||
//
|
||||
// The whole of it runs under s.mu, listener 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
|
||||
// listener it is replacing.
|
||||
func (s *Server) Stop() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if !s.running {
|
||||
return
|
||||
}
|
||||
|
||||
release(s.ln, s.path)
|
||||
s.running = false
|
||||
s.access = Access{}
|
||||
s.ln = nil
|
||||
s.path = ""
|
||||
|
||||
// Set whenever running is. When this Stop is the watcher's own, stopping a watcher
|
||||
// that has already fired is a no-op.
|
||||
s.unwatch()
|
||||
s.unwatch = nil
|
||||
}
|
||||
|
||||
// release gives up a listener and the socket node at its path. The node goes first,
|
||||
// while the listener is still open: for as long as it is, the node is this server'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.
|
||||
func release(ln net.Listener, path string) {
|
||||
removeSocket(path)
|
||||
_ = ln.Close()
|
||||
}
|
||||
|
||||
// semaphore returns the connection limiter, creating it on first use. It is made once
|
||||
// and never replaced: a handler releases into the channel it acquired from, so swapping
|
||||
// in a fresh one across a Stop and Start would leave any handler still in flight
|
||||
// blocked forever on a channel nothing had filled. Callers hold s.mu.
|
||||
func (s *Server) semaphore() chan struct{} {
|
||||
if s.sem == nil {
|
||||
s.sem = make(chan struct{}, s.maxConns)
|
||||
}
|
||||
return s.sem
|
||||
}
|
||||
|
||||
// Accept failures that are not the listener closing are retried after a pause that
|
||||
// doubles from acceptRetryMin up to acceptRetryMax, the same shape as net/http.Serve.
|
||||
const (
|
||||
acceptRetryMin = 5 * time.Millisecond
|
||||
acceptRetryMax = time.Second
|
||||
)
|
||||
|
||||
// accept serves connections from ln until it is closed. sem is the limiter to acquire
|
||||
// from and release into; it is passed rather than read from s so the handlers spawned
|
||||
// here never touch s.sem without the lock.
|
||||
//
|
||||
// Only a closed listener ends the loop; Stop and Rebind are the two things that close
|
||||
// it. Every other error is retried: the process being out of descriptors (EMFILE,
|
||||
// ENFILE) or a client that hung up between the kernel's queue and us (ECONNABORTED)
|
||||
// are passing conditions, and giving up on them would leave a socket on disk that
|
||||
// nothing answers, with the reason buried in a log line from minutes or days earlier.
|
||||
func (s *Server) accept(ln net.Listener, sem chan struct{}) {
|
||||
var delay time.Duration
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() {
|
||||
continue
|
||||
}
|
||||
|
||||
if delay == 0 {
|
||||
delay = acceptRetryMin
|
||||
} else {
|
||||
delay = min(delay*2, acceptRetryMax)
|
||||
}
|
||||
s.l.Warn("Local control socket could not accept a connection, retrying", "error", err, "retry_in", delay)
|
||||
time.Sleep(delay)
|
||||
continue
|
||||
}
|
||||
delay = 0
|
||||
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
default:
|
||||
// At capacity. Say so and hang up rather than holding the connection open.
|
||||
// Logged too: a slot is held for as long as a command runs, and the slow
|
||||
// command warning in serve says which ones are still running.
|
||||
s.l.Warn("Local control socket is at capacity, refusing a connection", "max", s.maxConns)
|
||||
s.reply(conn, &Response{Version: ProtocolVersion, Error: "local control socket is busy, try again"})
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer func() { <-sem }()
|
||||
s.handle(conn)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// handle serves one request. It recovers from panics in command callbacks: this
|
||||
// surface is present on every install and reachable by any local process running as
|
||||
// the daemon's user, so a malformed argument must cost a connection rather than the
|
||||
// overlay.
|
||||
func (s *Server) handle(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
var args []string
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
s.l.Error("Recovered from panic serving a local control command",
|
||||
"panic", r,
|
||||
"args", args,
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
s.reply(conn, &Response{Version: ProtocolVersion, Error: "command failed"})
|
||||
}
|
||||
}()
|
||||
|
||||
// Where the platform can identify the caller, check it, unless a group shares the
|
||||
// socket; see trustSocket. Otherwise listen's mode or security descriptor stands.
|
||||
if peerCheckSupported && !s.trustSocket.Load() {
|
||||
uid, err := peerUID(conn)
|
||||
if err != nil {
|
||||
s.l.Warn("Refusing local control connection with unreadable credentials", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Access is restricted to the user who ran nebula. Root is allowed through
|
||||
// because it can reach the daemon's memory regardless of what this check says.
|
||||
if uid != s.euid && uid != 0 {
|
||||
s.l.Warn("Refusing local control connection from another user", "peerUid", uid)
|
||||
s.reply(conn, &Response{Version: ProtocolVersion, Error: "not permitted"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
_ = conn.SetReadDeadline(time.Now().Add(readTimeout))
|
||||
|
||||
req, err := readRequest(conn)
|
||||
if err != nil {
|
||||
s.reply(conn, &Response{Version: ProtocolVersion, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
args = req.Args
|
||||
|
||||
// No deadline while a command runs; the write deadline below is what bounds a client
|
||||
// that stops reading.
|
||||
_ = conn.SetReadDeadline(time.Time{})
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
|
||||
|
||||
s.reply(conn, s.serve(req))
|
||||
}
|
||||
|
||||
// serve runs one request and describes the outcome.
|
||||
//
|
||||
// Nothing bounds a command's run; a context would have to reach every Run. What is
|
||||
// bounded is the silence: a command still running at slowAfter is named in the log, with
|
||||
// the slot it is holding, so a socket that has gone "busy" can be traced to the commands
|
||||
// that wedged it. The timer is stopped however the command ends, a panic included, so
|
||||
// the line is only ever written about a command that is still running.
|
||||
func (s *Server) serve(req *Request) *Response {
|
||||
slow := time.AfterFunc(s.slowAfter, func() {
|
||||
s.l.Warn("Local control command is still running and holding a connection slot",
|
||||
"command", req.Command,
|
||||
"args", req.Args,
|
||||
"after", s.slowAfter,
|
||||
"max", s.maxConns,
|
||||
)
|
||||
})
|
||||
defer slow.Stop()
|
||||
|
||||
res := &Response{Version: ProtocolVersion}
|
||||
reg := s.src
|
||||
|
||||
if req.Describe {
|
||||
schema, err := json.Marshal(reg.Schema())
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
|
||||
res.Result = schema
|
||||
return res
|
||||
}
|
||||
|
||||
if req.Command == "" {
|
||||
res.Error = "no command given"
|
||||
return res
|
||||
}
|
||||
|
||||
params, err := stringParams(req.Params)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
|
||||
format, err := parseFormat(req.Format)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
|
||||
cmd, err := reg.Resolve(commands.Name(req.Command))
|
||||
if err != nil {
|
||||
s.l.Debug("Local control command refused", "command", req.Command, "error", err)
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
|
||||
r, err := commands.Invoke(commands.Request{Command: cmd, Params: params, Args: req.Args})
|
||||
if err != nil {
|
||||
s.l.Debug("Local control command failed", "command", req.Command, "error", err)
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
|
||||
// A command that acts does so now, before the one reply this surface gives, and the
|
||||
// reply carries both halves: the line Run promised and the outcome Then produced.
|
||||
// In JSON only the outcome travels, since the promise is for a person to read.
|
||||
var preface []byte
|
||||
if cmd.Then != nil && r.OK {
|
||||
if format == commands.FormatText && !r.Empty() {
|
||||
buf := &bytes.Buffer{}
|
||||
if err := commands.Render(cmd, r, format, buf); err == nil {
|
||||
preface = buf.Bytes()
|
||||
}
|
||||
}
|
||||
r = cmd.Then()
|
||||
}
|
||||
|
||||
// A command with nothing to say gets an empty, successful reply.
|
||||
if r.Empty() {
|
||||
res.Text = preface
|
||||
return res
|
||||
}
|
||||
|
||||
return render(res, cmd, r, format, preface)
|
||||
}
|
||||
|
||||
// render turns a command's Result into the response, in the format the caller asked for,
|
||||
// through commands.Render, so the JSON is byte for byte what -json prints over ssh.
|
||||
func render(res *Response, cmd *commands.Command, r commands.Result, format commands.Format, preface []byte) *Response {
|
||||
buf := &bytes.Buffer{}
|
||||
if err := commands.Render(cmd, r, format, buf); err != nil {
|
||||
res.Error = err.Error()
|
||||
return res
|
||||
}
|
||||
|
||||
if format != commands.FormatText {
|
||||
// The caller is a program. Carry the payload as JSON rather than as a string that
|
||||
// happens to contain some; the newline Render ends a line with is not the value's.
|
||||
res.Result = bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
|
||||
|
||||
// A command that ran and refused is a failure to whoever asked, in either format.
|
||||
// The structured outcome still travels in Result for a program to read; Error
|
||||
// carries the reason so the one rule, Error set means failed, holds here too and
|
||||
// a client never has to guess from the payload.
|
||||
if !r.OK {
|
||||
res.Error = r.Reason
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// A command that ran and refused reads as an error to whoever asked for text: they
|
||||
// are a person or a script, and both expect a refusal on the error stream.
|
||||
if !r.OK {
|
||||
res.Error = string(append(preface, buf.Bytes()...))
|
||||
return res
|
||||
}
|
||||
|
||||
// The bytes the command wrote, as they are; see Response.Text.
|
||||
res.Text = append(preface, buf.Bytes()...)
|
||||
return res
|
||||
}
|
||||
|
||||
// parseFormat turns the request's format into the one the registry understands. An
|
||||
// unknown value is an error rather than a silent default, so a client that asks for
|
||||
// something this daemon cannot do hears about it.
|
||||
func parseFormat(s string) (commands.Format, error) {
|
||||
switch s {
|
||||
case "", "json":
|
||||
return commands.FormatJSON, nil
|
||||
case "text":
|
||||
return commands.FormatText, nil
|
||||
default:
|
||||
return commands.FormatJSON, fmt.Errorf("unknown format %q, expected \"json\" or \"text\"", s)
|
||||
}
|
||||
}
|
||||
|
||||
// reply writes one response frame.
|
||||
func (s *Server) reply(conn net.Conn, res *Response) {
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
|
||||
if err := writeFrame(conn, res); err != nil {
|
||||
s.l.Debug("Could not send a local control response", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// stringParams converts JSON's types into the strings flag.Value.Set expects, so a
|
||||
// caller writes true and 3 rather than "true" and "3".
|
||||
func stringParams(in map[string]any) (map[string]string, error) {
|
||||
if len(in) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
out := make(map[string]string, len(in))
|
||||
for k, v := range in {
|
||||
switch t := v.(type) {
|
||||
case bool:
|
||||
out[k] = strconv.FormatBool(t)
|
||||
case string:
|
||||
out[k] = t
|
||||
case float64:
|
||||
// encoding/json gives every number as a float64; render whole ones without
|
||||
// a decimal point so an int flag accepts them.
|
||||
if t != math.Trunc(t) {
|
||||
out[k] = strconv.FormatFloat(t, 'f', -1, 64)
|
||||
continue
|
||||
}
|
||||
|
||||
// A whole float64 can be far outside int64, and Go's conversion of one that is
|
||||
// gives an unspecified value rather than an error, so the bounds are checked
|
||||
// first. MinInt64 is exactly representable and is in range. MaxInt64 is not:
|
||||
// as a float64 it rounds up to 2^63, which is the first value out of range,
|
||||
// hence the >= on that side.
|
||||
if t < math.MinInt64 || t >= math.MaxInt64 {
|
||||
return nil, fmt.Errorf("parameter %q is %s, outside the range of a 64-bit integer",
|
||||
k, strconv.FormatFloat(t, 'g', -1, 64))
|
||||
}
|
||||
out[k] = strconv.FormatInt(int64(t), 10)
|
||||
case nil:
|
||||
return nil, fmt.Errorf("parameter %q has no value", k)
|
||||
default:
|
||||
return nil, fmt.Errorf("parameter %q is not a string, number or boolean", k)
|
||||
}
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func readRequest(conn net.Conn) (*Request, error) {
|
||||
req := &Request{}
|
||||
if err := readFrame(conn, MaxRequestBytes, "request", req, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.Version != ProtocolVersion {
|
||||
return nil, fmt.Errorf(
|
||||
"this nebula speaks local control protocol v%d, the client sent v%d; the two binaries are different versions",
|
||||
ProtocolVersion, req.Version,
|
||||
)
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
||||
@@ -0,0 +1,950 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// testSocket returns a short socket path whose directory does not exist yet and whose
|
||||
// parent is private: one level below the test's own directory, so that listen has a
|
||||
// directory of its own to create.
|
||||
func testSocket(t *testing.T) string {
|
||||
t.Helper()
|
||||
return filepath.Join(test.ShortTempDir(t), "n", "s.sock")
|
||||
}
|
||||
|
||||
func serve(t *testing.T, reg *commands.Registry) (*Server, string) {
|
||||
t.Helper()
|
||||
|
||||
path := testSocket(t)
|
||||
s := NewServer(test.NewLogger(), reg)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
return s, path
|
||||
}
|
||||
|
||||
// serveAt starts a server on an exact path, for tests that care where the socket is.
|
||||
func serveAt(t *testing.T, path string) (*Server, func()) {
|
||||
t.Helper()
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
return s, s.Stop
|
||||
}
|
||||
|
||||
// echoCommand reports its operands, for tests on either surface.
|
||||
func echoCommand() *commands.Command {
|
||||
return &commands.Command{
|
||||
Name: "echo",
|
||||
ShortDescription: "echoes its arguments",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value(fmt.Sprintf("%v", a)), nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func basicRegistry() *commands.Registry {
|
||||
reg := commands.New()
|
||||
reg.Register(echoCommand())
|
||||
reg.Register(&commands.Command{
|
||||
Name: "boom",
|
||||
ShortDescription: "panics",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
panic("this command is broken")
|
||||
},
|
||||
})
|
||||
return reg
|
||||
}
|
||||
|
||||
// run invokes one command and returns its output and its error text. An empty error is
|
||||
// success: the protocol has no separate status field.
|
||||
func run(t *testing.T, path, command string, args ...string) (string, string) {
|
||||
t.Helper()
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke(command, nil, args, "")
|
||||
require.NoError(t, err)
|
||||
return textOf(res), res.Error
|
||||
}
|
||||
|
||||
// textOf is what a test reads as a command's output: the text when text was asked for,
|
||||
// else the JSON result, unquoted when it is a JSON string so a test can compare words.
|
||||
func textOf(res *Response) string {
|
||||
if len(res.Text) > 0 {
|
||||
return string(res.Text)
|
||||
}
|
||||
if len(res.Result) > 0 && res.Result[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(res.Result, &s); err == nil {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return string(res.Result)
|
||||
}
|
||||
|
||||
func TestServeAllowedCommand(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
out, errOut := run(t, path, "echo", "a", "b")
|
||||
assert.Equal(t, "[a b]", out)
|
||||
assert.Empty(t, errOut, "a command that worked reports no error")
|
||||
}
|
||||
|
||||
// TestPanicInCommandDoesNotKillTheDaemon: a broken command costs a connection, not the
|
||||
// overlay.
|
||||
func TestPanicInCommandDoesNotKillTheDaemon(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
out, errOut := run(t, path, "boom")
|
||||
assert.Empty(t, out)
|
||||
assert.Contains(t, errOut, "command failed")
|
||||
|
||||
// The server is still serving, which is the point of the test.
|
||||
out, errOut = run(t, path, "echo", "still", "here")
|
||||
assert.Equal(t, "[still here]", out)
|
||||
assert.Empty(t, errOut)
|
||||
}
|
||||
|
||||
// TestSocketPermissions: the modes are pinned, not left to the umask. A 077 umask would
|
||||
// make the directory 0700 and hide a root daemon's socket from an unprivileged nebula
|
||||
// ctl.
|
||||
func TestSocketPermissions(t *testing.T) {
|
||||
for _, umask := range []int{0, 0077} {
|
||||
t.Run(fmt.Sprintf("umask %04o", umask), func(t *testing.T) {
|
||||
old := unix.Umask(umask)
|
||||
defer unix.Umask(old)
|
||||
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
fi, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0600), fi.Mode().Perm(), "socket must not be reachable by other users")
|
||||
|
||||
di, err := os.Stat(filepath.Dir(path))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, os.FileMode(0755), di.Mode().Perm(), "a directory we create ourselves is searchable, so ServedByRoot can see into it")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveSocketIsNotStolen(t *testing.T) {
|
||||
first, path := serve(t, basicRegistry())
|
||||
require.NotNil(t, first)
|
||||
|
||||
second := NewServer(test.NewLogger(), basicRegistry())
|
||||
err := second.Rebind(context.Background(), path, ownerOnly())
|
||||
assert.ErrorContains(t, err, "already in use", "a live endpoint must not be unlinked by a second instance")
|
||||
}
|
||||
|
||||
// TestLiveSocketIsNotStolenBeforeItsChmod: between an instance's bind and its chmod the
|
||||
// socket is at whatever mode the umask left. A second instance starting in that window
|
||||
// must still see it as live, not stale: only a refused connect proves nothing is behind
|
||||
// the file.
|
||||
func TestLiveSocketIsNotStolenBeforeItsChmod(t *testing.T) {
|
||||
first, path := serve(t, basicRegistry())
|
||||
require.NotNil(t, first)
|
||||
require.NoError(t, os.Chmod(path, 0666))
|
||||
|
||||
second := NewServer(test.NewLogger(), basicRegistry())
|
||||
err := second.Rebind(context.Background(), path, ownerOnly())
|
||||
require.ErrorContains(t, err, "already in use", "a live socket at any mode is not thereby dead")
|
||||
|
||||
_, err = os.Stat(path)
|
||||
require.NoError(t, err, "the first instance's socket is still there")
|
||||
require.NoError(t, os.Chmod(path, 0600))
|
||||
out, _ := run(t, path, "echo", "ok")
|
||||
assert.Equal(t, "[ok]", out, "and still served")
|
||||
}
|
||||
|
||||
func TestRebindMovesTheSocket(t *testing.T) {
|
||||
s, path := serve(t, basicRegistry())
|
||||
next := filepath.Join(filepath.Dir(path), "n.sock")
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), next, ownerOnly()))
|
||||
assert.Equal(t, next, s.Path())
|
||||
|
||||
out, _ := run(t, next, "echo", "moved")
|
||||
assert.Equal(t, "[moved]", out)
|
||||
|
||||
_, err := os.Stat(path)
|
||||
assert.True(t, os.IsNotExist(err), "the old socket should be unlinked")
|
||||
}
|
||||
|
||||
func TestRebindFailureKeepsTheOldSocket(t *testing.T) {
|
||||
s, path := serve(t, basicRegistry())
|
||||
|
||||
err := s.Rebind(context.Background(), "/nonexistent-dir-for-tests/x.sock", ownerOnly())
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, path, s.Path(), "a bad path must leave the working endpoint alone")
|
||||
|
||||
out, _ := run(t, path, "echo", "ok")
|
||||
assert.Equal(t, "[ok]", out)
|
||||
}
|
||||
|
||||
// TestSemaphoreSurvivesRestart pins the rule that the connection limiter is made once. A
|
||||
// handler releases into the channel it acquired from, so if Rebind replaced it after a
|
||||
// Stop, a command still running across the restart would block forever on the new,
|
||||
// empty channel and leak its goroutine and connection.
|
||||
func TestSemaphoreSurvivesRestart(t *testing.T) {
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
path := testSocket(t)
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
first := s.sem
|
||||
require.NotNil(t, first)
|
||||
s.Stop()
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
defer s.Stop()
|
||||
assert.Equal(t, first, s.sem, "Rebind after Stop must keep the same semaphore")
|
||||
|
||||
require.NoError(t, s.Rebind(context.Background(), testSocket(t), ownerOnly()))
|
||||
assert.Equal(t, first, s.sem, "Rebind must keep the same semaphore")
|
||||
}
|
||||
|
||||
// TestRestartIsWatchedOnItsOwnContext: the ctx watcher is installed by the first bind of
|
||||
// a run and cleared by Stop, so a server stopped by one context's cancellation and
|
||||
// started again under another is stopped when that second context is cancelled, not
|
||||
// left serving until the process exits.
|
||||
func TestRestartIsWatchedOnItsOwnContext(t *testing.T) {
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
path := testSocket(t)
|
||||
|
||||
ctxA, cancelA := context.WithCancel(context.Background())
|
||||
require.NoError(t, s.Rebind(ctxA, path, ownerOnly()))
|
||||
cancelA()
|
||||
require.Eventually(t, func() bool { return s.Path() == "" }, time.Second, 10*time.Millisecond, "the first context must stop the server")
|
||||
|
||||
ctxB, cancelB := context.WithCancel(context.Background())
|
||||
require.NoError(t, s.Rebind(ctxB, path, ownerOnly()))
|
||||
defer s.Stop()
|
||||
assert.Equal(t, path, s.Path())
|
||||
|
||||
cancelB()
|
||||
require.Eventually(t, func() bool { return s.Path() == "" }, time.Second, 10*time.Millisecond, "the second context must stop the server too")
|
||||
_, err := os.Stat(path)
|
||||
assert.True(t, os.IsNotExist(err), "the socket must be removed when the second context stops the server")
|
||||
}
|
||||
|
||||
// TestStopDetachesTheWatcher: a server stopped by Stop and started again under another
|
||||
// context belongs to that context alone. The one that started the earlier run, ending
|
||||
// later, must not take the new run down with it.
|
||||
func TestStopDetachesTheWatcher(t *testing.T) {
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
path := testSocket(t)
|
||||
|
||||
ctxA, cancelA := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancelA)
|
||||
require.NoError(t, s.Rebind(ctxA, path, ownerOnly()))
|
||||
s.Stop()
|
||||
|
||||
ctxB, cancelB := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancelB)
|
||||
require.NoError(t, s.Rebind(ctxB, path, ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
cancelA()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
assert.Equal(t, path, s.Path(), "the first run's context has nothing to do with the second run")
|
||||
_, err := (&Client{Path: path}).Describe()
|
||||
require.NoError(t, err)
|
||||
|
||||
cancelB()
|
||||
require.Eventually(t, func() bool { return s.Path() == "" }, time.Second, 10*time.Millisecond, "the second run's context stops it")
|
||||
}
|
||||
|
||||
func TestVersionMismatchIsExplained(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
conn, err := net.Dial("unix", path)
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
body, _ := json.Marshal(Request{Version: ProtocolVersion + 1, Command: "echo"})
|
||||
_, err = conn.Write(append(body, '\n'))
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := readResponse(conn)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, res.Error, "different versions")
|
||||
}
|
||||
|
||||
func TestOversizedRequestIsRejected(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
conn, err := net.Dial("unix", path)
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
_, err = conn.Write(append(bytes.Repeat([]byte("a"), MaxRequestBytes+10), '\n'))
|
||||
if err == nil {
|
||||
res, rerr := readResponse(conn)
|
||||
require.NoError(t, rerr)
|
||||
assert.NotEmpty(t, res.Error)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrentClientsAreBounded checks that going over the connection cap is answered
|
||||
// rather than queued, so a burst of clients cannot pile up against the packet path.
|
||||
// TestSlowCommandIsNamedInTheLog: a command that does not return holds its slot for
|
||||
// good, and enough of them leave the socket answering only "busy". Both are logged, the
|
||||
// command by name once it has run past slowAfter and each refused connection as it
|
||||
// happens, so a busy socket can be traced to what wedged it.
|
||||
func TestSlowCommandIsNamedInTheLog(t *testing.T) {
|
||||
reg := commands.New()
|
||||
release := make(chan struct{})
|
||||
reg.Register(&commands.Command{
|
||||
Name: "block",
|
||||
ShortDescription: "blocks until released",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
<-release
|
||||
return commands.Value("done"), nil
|
||||
},
|
||||
})
|
||||
|
||||
var logs lockedBuffer
|
||||
s := NewServer(test.NewLoggerWithOutput(&logs), reg)
|
||||
s.maxConns = 1
|
||||
s.slowAfter = 20 * time.Millisecond
|
||||
path := testSocket(t)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
defer s.Stop()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = (&Client{Path: path}).Invoke("block", nil, []string{"x"}, "")
|
||||
}()
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
return strings.Contains(logs.String(), "still running")
|
||||
}, 2*time.Second, 10*time.Millisecond)
|
||||
assert.Contains(t, logs.String(), "command=block")
|
||||
assert.Contains(t, logs.String(), "args=[x]")
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("block", nil, nil, "")
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, res.Error, "busy")
|
||||
assert.Contains(t, logs.String(), "at capacity")
|
||||
|
||||
close(release)
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// TestPanickedCommandIsNotReportedAsStillRunning: the slow command line is about a slot
|
||||
// that is still held. A command that panicked has given its slot back, and the client
|
||||
// its answer, so no line must claim otherwise after the fact.
|
||||
func TestPanickedCommandIsNotReportedAsStillRunning(t *testing.T) {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "boom",
|
||||
ShortDescription: "panics",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
panic("this command is broken")
|
||||
},
|
||||
})
|
||||
|
||||
var logs lockedBuffer
|
||||
s := NewServer(test.NewLoggerWithOutput(&logs), reg)
|
||||
s.slowAfter = 20 * time.Millisecond
|
||||
path := testSocket(t)
|
||||
require.NoError(t, s.Rebind(context.Background(), path, ownerOnly()))
|
||||
defer s.Stop()
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("boom", nil, nil, "")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "command failed", res.Error)
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
assert.Contains(t, logs.String(), "Recovered from panic")
|
||||
assert.NotContains(t, logs.String(), "still running")
|
||||
}
|
||||
|
||||
// lockedBuffer is a strings.Builder the server's goroutines and the test can share.
|
||||
type lockedBuffer struct {
|
||||
mu sync.Mutex
|
||||
b strings.Builder
|
||||
}
|
||||
|
||||
func (l *lockedBuffer) Write(p []byte) (int, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.b.Write(p)
|
||||
}
|
||||
|
||||
func (l *lockedBuffer) String() string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.b.String()
|
||||
}
|
||||
|
||||
// flakyListener fails its first few Accepts the way a process that is out of file
|
||||
// descriptors does, then behaves.
|
||||
type flakyListener struct {
|
||||
net.Listener
|
||||
failures int
|
||||
}
|
||||
|
||||
func (f *flakyListener) Accept() (net.Conn, error) {
|
||||
if f.failures > 0 {
|
||||
f.failures--
|
||||
return nil, &net.OpError{Op: "accept", Net: "unix", Err: errors.New("too many open files")}
|
||||
}
|
||||
return f.Listener.Accept()
|
||||
}
|
||||
|
||||
// TestAcceptSurvivesTransientErrors: an Accept that fails for a reason other than the
|
||||
// listener being closed is retried, so a moment at the descriptor limit does not take
|
||||
// the control socket down for the rest of the process. Closing the listener is still
|
||||
// what ends the loop.
|
||||
func TestAcceptSurvivesTransientErrors(t *testing.T) {
|
||||
path := testSocket(t)
|
||||
require.NoError(t, os.Mkdir(filepath.Dir(path), 0700))
|
||||
ln, err := listen(path, ownerOnly())
|
||||
require.NoError(t, err)
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
s.accept(&flakyListener{Listener: ln, failures: 3}, make(chan struct{}, 1))
|
||||
}()
|
||||
|
||||
out, errText := run(t, path, "echo", "still", "here")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[still here]", out)
|
||||
|
||||
require.NoError(t, ln.Close())
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("accept loop did not exit when the listener was closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopRemovesTheSocket(t *testing.T) {
|
||||
s, path := serve(t, basicRegistry())
|
||||
s.Stop()
|
||||
|
||||
_, err := os.Stat(path)
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
}
|
||||
|
||||
func TestContextCancellationStops(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
path := testSocket(t)
|
||||
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(ctx, path, ownerOnly()))
|
||||
|
||||
cancel()
|
||||
assert.Eventually(t, func() bool {
|
||||
_, err := os.Stat(path)
|
||||
return os.IsNotExist(err)
|
||||
}, 2*time.Second, 20*time.Millisecond)
|
||||
}
|
||||
|
||||
// TestNamedParametersDriveFlags is the point of the protocol: a caller passes options by
|
||||
// name, with JSON's own types, and never assembles a command line.
|
||||
// TestStringParamsNumbers: JSON numbers arrive as float64. Whole ones render as integers
|
||||
// so int flags accept them, and a whole one outside int64 is refused rather than
|
||||
// converted, since Go's float-to-int conversion of an out-of-range value is unspecified
|
||||
// and would set a number the caller never sent.
|
||||
func TestStringParamsNumbers(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
in float64
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
"whole": {in: 3, want: "3"},
|
||||
"negative whole": {in: -1, want: "-1"},
|
||||
"fraction": {in: 1.5, want: "1.5"},
|
||||
"min int64": {in: math.MinInt64, want: "-9223372036854775808"},
|
||||
"largest in range": {in: 9223372036854774784, want: "9223372036854774784"},
|
||||
"2^63": {in: 9223372036854775808, wantErr: true},
|
||||
"1e19": {in: 1e19, wantErr: true},
|
||||
"below min int64": {in: -9.3e18, wantErr: true},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
out, err := stringParams(map[string]any{"n": tc.in})
|
||||
if tc.wantErr {
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, `parameter "n" is `)
|
||||
assert.ErrorContains(t, err, "outside the range of a 64-bit integer")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.want, out["n"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNamedParametersDriveFlags(t *testing.T) {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "report",
|
||||
ShortDescription: "reports its flags",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := struct {
|
||||
Verbose bool
|
||||
Label string
|
||||
}{}
|
||||
fl.BoolVar(&s.Verbose, "verbose", false, "say more")
|
||||
fl.StringVar(&s.Label, "label", "none", "a label")
|
||||
return fl, &s
|
||||
},
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
s := fs.(*struct {
|
||||
Verbose bool
|
||||
Label string
|
||||
})
|
||||
return commands.Value(fmt.Sprintf("verbose=%v label=%s args=%v", s.Verbose, s.Label, a)), nil
|
||||
},
|
||||
})
|
||||
|
||||
_, path := serve(t, reg)
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("report",
|
||||
map[string]string{"verbose": "true", "label": "here"},
|
||||
[]string{"an-operand"},
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Empty(t, res.Error)
|
||||
assert.Equal(t, "verbose=true label=here args=[an-operand]", textOf(res))
|
||||
}
|
||||
|
||||
// TestUnknownParameterIsReported: a misspelled parameter is an error rather than a
|
||||
// silently applied default, which is the difference between an API and a guess.
|
||||
func TestUnknownParameterIsReported(t *testing.T) {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "report",
|
||||
ShortDescription: "takes a flag",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
fl.Bool("verbose", false, "say more")
|
||||
return fl, nil
|
||||
},
|
||||
Run: func(fs any, a []string) (commands.Result, error) { return commands.Nothing(), nil },
|
||||
})
|
||||
|
||||
_, path := serve(t, reg)
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("report", map[string]string{"verbos": "true"}, nil, "")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Contains(t, res.Error, `report has no parameter "verbos"`)
|
||||
}
|
||||
|
||||
func TestParametersOnACommandThatTakesNoneAreReported(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("echo", map[string]string{"nope": "true"}, nil, "")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Contains(t, res.Error, "echo takes no parameters")
|
||||
}
|
||||
|
||||
// TestJSONOutputIsAJSONValue: a command that emits JSON lands in the response as JSON,
|
||||
// not as a string a caller has to parse a second time.
|
||||
func TestJSONOutputIsAJSONValue(t *testing.T) {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "emit",
|
||||
ShortDescription: "emits json",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value(map[string]any{"hosts": []int{1, 2, 3}}), nil
|
||||
},
|
||||
})
|
||||
|
||||
_, path := serve(t, reg)
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("emit", nil, nil, "")
|
||||
require.NoError(t, err)
|
||||
|
||||
var decoded struct {
|
||||
Hosts []int `json:"hosts"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(res.Result, &decoded))
|
||||
assert.Equal(t, []int{1, 2, 3}, decoded.Hosts)
|
||||
}
|
||||
|
||||
// TestStringValueIsAJSONString: a command whose value is a string answers a JSON request
|
||||
// with a JSON string, quotes and all.
|
||||
func TestStringValueIsAJSONString(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("echo", nil, []string{"hi"}, "")
|
||||
require.NoError(t, err)
|
||||
|
||||
var s string
|
||||
require.NoError(t, json.Unmarshal(res.Result, &s))
|
||||
assert.Equal(t, "[hi]", s)
|
||||
}
|
||||
|
||||
func TestDescribeListsTheCommands(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
schema, err := (&Client{Path: path}).Describe()
|
||||
require.NoError(t, err)
|
||||
|
||||
names := make([]string, 0, len(schema))
|
||||
for _, c := range schema {
|
||||
names = append(names, string(c.Name))
|
||||
}
|
||||
|
||||
assert.ElementsMatch(t, []string{"help", "echo", "boom"}, names)
|
||||
}
|
||||
|
||||
// TestPresentationParametersAreRefused: the schema lists json and pretty on every
|
||||
// command, because the command lines take them, but a request has one way to choose its
|
||||
// rendering, the format field. A client that sends them as parameters is pointed there
|
||||
// rather than given a second, weaker way to say the same thing.
|
||||
func TestPresentationParametersAreRefused(t *testing.T) {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "pair",
|
||||
ShortDescription: "returns a pair",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value(map[string]int{"a": 1}), nil
|
||||
},
|
||||
Text: func(v any, w io.Writer) error {
|
||||
_, err := fmt.Fprintln(w, "a is one")
|
||||
return err
|
||||
},
|
||||
})
|
||||
_, path := serve(t, reg)
|
||||
c := &Client{Path: path}
|
||||
|
||||
for _, name := range []string{"json", "pretty"} {
|
||||
res, err := c.Invoke("pair", map[string]string{name: "true"}, nil, "text")
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, res.Error, name+" is a command line flag, not a parameter")
|
||||
assert.Contains(t, res.Error, "format")
|
||||
assert.Empty(t, res.Result, "a refused request runs nothing")
|
||||
}
|
||||
|
||||
// The format field is the one that counts.
|
||||
res, err := c.Invoke("pair", nil, nil, "text")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
assert.Equal(t, "a is one\n", textOf(res))
|
||||
|
||||
res, err = c.Invoke("pair", nil, nil, "")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
assert.JSONEq(t, `{"a":1}`, string(res.Result), "the API default is JSON")
|
||||
}
|
||||
|
||||
// TestTextRequestToATextlessCommand: a command with no human rendering still answers a
|
||||
// text request when the answer is a refusal, since a refusal always has one. Only a
|
||||
// successful result has nothing to say in text, and that is reported then, by the daemon.
|
||||
func TestTextRequestToATextlessCommand(t *testing.T) {
|
||||
reg := commands.New()
|
||||
reg.Register(&commands.Command{
|
||||
Name: "tunnel",
|
||||
ShortDescription: "data on success, a refusal without an operand",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
if len(a) == 0 {
|
||||
return commands.Failed("No vpn address was provided"), nil
|
||||
}
|
||||
return commands.Value(map[string]int{"index": 7}), nil
|
||||
},
|
||||
JSONOnly: true,
|
||||
})
|
||||
_, path := serve(t, reg)
|
||||
c := &Client{Path: path}
|
||||
|
||||
res, err := c.Invoke("tunnel", nil, nil, "text")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "No vpn address was provided\n", res.Error, "the refusal is rendered, not the missing text form")
|
||||
|
||||
res, err = c.Invoke("tunnel", nil, []string{"10.0.0.1"}, "text")
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, res.Error, "tunnel has no human readable output yet; pass -json or -pretty")
|
||||
assert.Empty(t, res.Result)
|
||||
|
||||
res, err = c.Invoke("tunnel", nil, []string{"10.0.0.1"}, "json")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
assert.JSONEq(t, `{"index":7}`, string(res.Result))
|
||||
|
||||
// A refusal asked for as JSON carries the outcome for a program and the reason in
|
||||
// Error, so a client exits non-zero on the envelope alone, never by sniffing the
|
||||
// payload for an ok field some unrelated result might also have.
|
||||
res, err = c.Invoke("tunnel", nil, nil, "json")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "No vpn address was provided", res.Error)
|
||||
assert.JSONEq(t, `{"ok":false,"reason":"No vpn address was provided"}`, string(res.Result))
|
||||
}
|
||||
|
||||
// TestRebindAfterFailedBindStillStopsOnCancel covers a daemon whose initial listen
|
||||
// failed and which later Rebinds onto a good path from a reloaded config. The context
|
||||
// watcher has to be installed by that Rebind, or the socket outlives the daemon.
|
||||
func TestRebindAfterFailedBindStillStopsOnCancel(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
base := test.ShortTempDir(t)
|
||||
|
||||
// listen creates one level only, so a socket directory under a parent that is not
|
||||
// there yet fails to bind, the shape of a runtime directory that does not exist.
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.Error(t, s.Rebind(ctx, filepath.Join(base, "missing", "n", "s.sock"), ownerOnly()))
|
||||
|
||||
good := filepath.Join(base, "n", "s.sock")
|
||||
require.NoError(t, s.Rebind(ctx, good, ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
_, err := (&Client{Path: good}).Describe()
|
||||
require.NoError(t, err)
|
||||
|
||||
cancel()
|
||||
assert.Eventually(t, func() bool {
|
||||
_, err := os.Stat(good)
|
||||
return os.IsNotExist(err)
|
||||
}, 2*time.Second, 20*time.Millisecond)
|
||||
}
|
||||
|
||||
// TestCommandRegisteredAfterStartIsServed: the server filters the registry per request,
|
||||
// so a command an embedder registers after wiring the socket is served, and described,
|
||||
// just as it would be over ssh.
|
||||
func TestCommandRegisteredAfterStartIsServed(t *testing.T) {
|
||||
reg := basicRegistry()
|
||||
_, path := serve(t, reg)
|
||||
|
||||
reg.Register(&commands.Command{
|
||||
Name: "late",
|
||||
ShortDescription: "registered after the server started",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Value("late"), nil
|
||||
},
|
||||
})
|
||||
|
||||
c := &Client{Path: path}
|
||||
|
||||
schema, err := c.Describe()
|
||||
require.NoError(t, err)
|
||||
names := make([]string, 0, len(schema))
|
||||
for _, cs := range schema {
|
||||
names = append(names, string(cs.Name))
|
||||
}
|
||||
assert.Contains(t, names, "late")
|
||||
|
||||
res, err := c.Invoke("late", nil, nil, "")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
assert.JSONEq(t, `"late"`, string(res.Result))
|
||||
}
|
||||
|
||||
// TestThenIsAnsweredInTheOneReply: this surface answers in one piece, so a command that
|
||||
// acts does so before the reply, and the reply carries Run's line and Then's outcome in
|
||||
// text, and the outcome alone in JSON.
|
||||
func TestThenIsAnsweredInTheOneReply(t *testing.T) {
|
||||
reg := commands.New()
|
||||
acted := false
|
||||
reg.Register(&commands.Command{
|
||||
Name: "act",
|
||||
ShortDescription: "replies, then acts",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Did("about to act"), nil
|
||||
},
|
||||
Then: func() commands.Result {
|
||||
acted = true
|
||||
return commands.Did("acted")
|
||||
},
|
||||
})
|
||||
_, path := serve(t, reg)
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("act", nil, nil, "text")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, acted)
|
||||
assert.Empty(t, res.Error)
|
||||
assert.Equal(t, "about to act\nacted\n", string(res.Text))
|
||||
|
||||
res, err = (&Client{Path: path}).Invoke("act", nil, nil, "")
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{"ok":true,"reason":"acted"}`, string(res.Result))
|
||||
|
||||
// A refusal from Then still carries Run's line ahead of it in text, as ssh prints it.
|
||||
acted = false
|
||||
reg.Register(&commands.Command{
|
||||
Name: "fail",
|
||||
ShortDescription: "replies, then fails to act",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Did("about to act"), nil
|
||||
},
|
||||
Then: func() commands.Result {
|
||||
return commands.Failed("could not act")
|
||||
},
|
||||
})
|
||||
res, err = (&Client{Path: path}).Invoke("fail", nil, nil, "text")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "about to act\ncould not act\n", res.Error)
|
||||
assert.Empty(t, res.Text)
|
||||
|
||||
// A Run that refused is the outcome, and Then does not run.
|
||||
acted = false
|
||||
reg.Register(&commands.Command{
|
||||
Name: "refuse",
|
||||
ShortDescription: "refuses, so never acts",
|
||||
Run: func(fs any, a []string) (commands.Result, error) {
|
||||
return commands.Failed("not like that"), nil
|
||||
},
|
||||
Then: func() commands.Result {
|
||||
acted = true
|
||||
return commands.Did("acted anyway")
|
||||
},
|
||||
})
|
||||
res, err = (&Client{Path: path}).Invoke("refuse", nil, nil, "text")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "not like that\n", res.Error)
|
||||
assert.False(t, acted)
|
||||
}
|
||||
|
||||
// TestRebindRefusesDuringShutdown: a reload that lands after the daemon's context is
|
||||
// cancelled must not bring the endpoint back. Stop is not terminal, so Rebind has to
|
||||
// take the answer from the context rather than from the running flag.
|
||||
func TestRebindRefusesDuringShutdown(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// Built by hand rather than through serve: the context watcher is installed once,
|
||||
// by the first bind, and this test needs it on a context it can cancel.
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(ctx, testSocket(t), ownerOnly()))
|
||||
t.Cleanup(s.Stop)
|
||||
|
||||
cancel()
|
||||
assert.Eventually(t, func() bool { return s.Path() == "" }, 2*time.Second, 20*time.Millisecond, "the watcher stops the server")
|
||||
|
||||
next := testSocket(t)
|
||||
err := s.Rebind(ctx, next, ownerOnly())
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "shutting down")
|
||||
assert.Empty(t, s.Path(), "the server stays stopped")
|
||||
|
||||
_, statErr := os.Stat(next)
|
||||
assert.True(t, os.IsNotExist(statErr), "and the refused socket is not left on disk")
|
||||
}
|
||||
|
||||
// TestRebindAndStopSerialize hammers Rebind against Stop. Whichever runs last decides
|
||||
// the final state, so after the dust settles a Stop must leave nothing listening and no
|
||||
// socket file behind, on either path.
|
||||
func TestRebindAndStopSerialize(t *testing.T) {
|
||||
a := testSocket(t)
|
||||
b := testSocket(t)
|
||||
|
||||
for i := 0; i < 50; i++ {
|
||||
s := NewServer(test.NewLogger(), basicRegistry())
|
||||
require.NoError(t, s.Rebind(context.Background(), a, ownerOnly()))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = s.Rebind(context.Background(), b, ownerOnly())
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.Stop()
|
||||
}()
|
||||
wg.Wait()
|
||||
|
||||
// The Rebind may have run after the Stop, which restarts the server by design.
|
||||
// A final Stop then has to take everything down.
|
||||
s.Stop()
|
||||
assert.Empty(t, s.Path())
|
||||
for _, p := range []string{a, b} {
|
||||
_, err := os.Stat(p)
|
||||
assert.True(t, os.IsNotExist(err), "iteration %d: %s left behind", i, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnknownRequestFieldIsRefused: a request with a field the protocol does not define
|
||||
// is answered with the field named, the way an unknown parameter is, and not run.
|
||||
func TestUnknownRequestFieldIsRefused(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
conn, err := dial(path, time.Second)
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
require.NoError(t, writeFrame(conn, map[string]any{"version": ProtocolVersion, "command": "echo", "arguments": []string{"x"}}))
|
||||
|
||||
var res Response
|
||||
require.NoError(t, readFrame(conn, MaxResponseBytes, "response", &res, false))
|
||||
assert.Contains(t, res.Error, `unknown field "arguments"`)
|
||||
assert.Empty(t, res.Result)
|
||||
}
|
||||
|
||||
// TestTrailingBytesOnARequestAreRefused: a request line is one object and nothing
|
||||
// more; a second object or stray bytes after it are refused rather than ignored.
|
||||
func TestTrailingBytesOnARequestAreRefused(t *testing.T) {
|
||||
_, path := serve(t, basicRegistry())
|
||||
|
||||
for _, line := range []string{
|
||||
`{"version":1,"command":"echo"} junk` + "\n",
|
||||
`{"version":1,"command":"echo"}{"version":1,"command":"boom"}` + "\n",
|
||||
} {
|
||||
conn, err := dial(path, time.Second)
|
||||
require.NoError(t, err)
|
||||
_, err = conn.Write([]byte(line))
|
||||
require.NoError(t, err)
|
||||
|
||||
var res Response
|
||||
require.NoError(t, readFrame(conn, MaxResponseBytes, "response", &res, false))
|
||||
assert.Contains(t, res.Error, "unexpected data after the object", line)
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestTextOutputKeepsTheBytes: a text rendering travels as the bytes the command wrote.
|
||||
// A JSON string would have had to be UTF-8, and a byte that is not would have come out
|
||||
// as U+FFFD, where the ssh server passes it through.
|
||||
func TestTextOutputKeepsTheBytes(t *testing.T) {
|
||||
reg := commands.New()
|
||||
raw := []byte{'n', 'a', 'm', 'e', ' ', 0xff, 0xfe, '\n'}
|
||||
reg.Register(&commands.Command{
|
||||
Name: "raw",
|
||||
ShortDescription: "writes what a certificate held",
|
||||
Run: func(fs any, a []string) (commands.Result, error) { return commands.Value("raw"), nil },
|
||||
Text: func(v any, w io.Writer) error {
|
||||
_, err := w.Write(raw)
|
||||
return err
|
||||
},
|
||||
})
|
||||
_, path := serve(t, reg)
|
||||
|
||||
res, err := (&Client{Path: path}).Invoke("raw", nil, nil, "text")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, res.Error)
|
||||
assert.Equal(t, raw, res.Text)
|
||||
assert.Empty(t, res.Result, "text is not also carried as JSON")
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
)
|
||||
|
||||
// Wire brings up the local control socket for a running nebula, unless the config turns
|
||||
// it off, and keeps it following the config across reloads.
|
||||
//
|
||||
// Every entry point that runs nebula as a daemon calls this, so the endpoint behaves the
|
||||
// same whether nebula was started from a shell or by a service manager. It deliberately
|
||||
// does not live in nebula.Main: the endpoint is on by default, so an embedder inside an
|
||||
// app sandbox would have to know to turn off a socket it cannot use. Wiring it at the
|
||||
// daemon entry points means embedders get the command registry and no listener.
|
||||
//
|
||||
// Every failure below is a warning, bar one. Nebula is expected to keep forwarding
|
||||
// packets whether or not anyone can reach it; but a name that another process holds is
|
||||
// not a misconfiguration, it is a process that will be answering nebula ctl in the
|
||||
// daemon's place, and that is logged as an error.
|
||||
//
|
||||
// Call it after Control.Start, so the listener only exists once the interface is up.
|
||||
func Wire(ctx context.Context, l *slog.Logger, c *config.C, reg *commands.Registry) *Server {
|
||||
l = l.With("subsystem", "localapi")
|
||||
srv := NewServer(l, reg)
|
||||
|
||||
// Registered before the first attempt, so that a path or bind that is bad at startup
|
||||
// can be fixed with a config edit and a reload, the same as one that goes bad later,
|
||||
// and so that a HUP landing in between is harmless: Rebind on a server already at
|
||||
// the path is a no-op.
|
||||
reconcile := followControlConfig(ctx, l, c, srv)
|
||||
reconcile(c)
|
||||
if !ControlEnabled(c) {
|
||||
l.Info("Local control socket is disabled", "key", CtlEnabledKey)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
// followControlConfig registers the reload callback that keeps the socket where
|
||||
// local_api.control.socket says it is, moving it when the key changes and bringing one
|
||||
// up while there is none, and returns it for the first attempt to call.
|
||||
//
|
||||
// The key is reloadable because the client finds the socket by reading the config: if the
|
||||
// two could disagree, the file on disk would name a socket that is not there.
|
||||
//
|
||||
// Every reload is reconciled rather than gated on the key having changed. Rebind on a
|
||||
// server already at the path is a no-op, so that costs nothing; and a bind that failed
|
||||
// for a reason outside the config, a runtime directory that was not there yet, is fixed
|
||||
// outside the config too, so the reload that follows the fix is a plain one. That holds
|
||||
// for a move as much as for the first bind: a daemon left on its old path by a move that
|
||||
// could not bind is one the client, reading the new path from the same file, cannot
|
||||
// reach, and the operator's fix is the directory and a reload, not an edit to an
|
||||
// unrelated line to make the key read as changed.
|
||||
//
|
||||
// The callback recovers from its own panics rather than relying on the config package,
|
||||
// whose callback loop has no isolation of its own. A panic there would take the daemon
|
||||
// down and skip every callback queued behind this one.
|
||||
func followControlConfig(ctx context.Context, l *slog.Logger, c *config.C, srv *Server) func(*config.C) {
|
||||
reconcile := func(c *config.C) {
|
||||
if !ControlEnabled(c) {
|
||||
if srv.Path() != "" {
|
||||
srv.Stop()
|
||||
l.Info("Stopped the local control socket, it is disabled in the reloaded config")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
want, err := SocketPathFromConfig(c)
|
||||
if err != nil {
|
||||
warnUnusable(l, "local control socket", srv.Path(), err)
|
||||
return
|
||||
}
|
||||
|
||||
acc, err := controlAccessFrom(c)
|
||||
if err != nil {
|
||||
warnUnusable(l, "local control socket", srv.Path(), err)
|
||||
return
|
||||
}
|
||||
|
||||
old := srv.Path()
|
||||
err = srv.Rebind(ctx, want, acc)
|
||||
reportRebind(l, old, want, err, srv.Path())
|
||||
}
|
||||
|
||||
c.RegisterReloadCallback(func(c *config.C, _ *config.Reload) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
l.Error("Recovered from panic reloading the local control socket", "panic", r)
|
||||
}
|
||||
}()
|
||||
reconcile(c)
|
||||
})
|
||||
return reconcile
|
||||
}
|
||||
|
||||
// warnUnusable logs a config the endpoint cannot follow: with nothing serving, the
|
||||
// endpoint is not available; with something serving, it is kept as it is.
|
||||
func warnUnusable(l *slog.Logger, what, current string, err error) {
|
||||
if current == "" {
|
||||
l.Warn("The "+what+" is not available, its config is unusable", "error", err)
|
||||
return
|
||||
}
|
||||
l.Warn("Ignoring unusable "+what+" config from the reload, keeping the current endpoint", "error", err, "current", current)
|
||||
}
|
||||
|
||||
// reportRebind logs what a Rebind did beyond the listening line the bind itself writes:
|
||||
// nothing for a server left where it was, a move with both paths, and a failure with
|
||||
// what the operator is left with. old is the path served before the call, "" for none,
|
||||
// want the one asked for, and now the path served after it: on unix a failed move keeps
|
||||
// the old socket, and now is old; on windows a change of access closes the pipe before
|
||||
// creating it again, and a failure there leaves nothing serving, so now is "".
|
||||
//
|
||||
// Nearly every failure is the operator's environment, a missing runtime directory or a
|
||||
// bad path, and a warning; a name held by another process is an error, since nothing
|
||||
// else will say that something is sitting where the daemon should be.
|
||||
func reportRebind(l *slog.Logger, old, want string, err error, now string) {
|
||||
level := l.Warn
|
||||
if errors.Is(err, errEndpointHeld) {
|
||||
level = l.Error
|
||||
}
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
if old != "" && old != want {
|
||||
l.Info("Moved the local control socket", "from", old, "to", want)
|
||||
}
|
||||
case old == "":
|
||||
level("Could not start the local control socket, control commands will not be available until a reload binds it", "error", err, "path", want)
|
||||
default:
|
||||
level("Could not bind the local control socket at the requested path", "error", err, "requested", want, "serving", now)
|
||||
}
|
||||
}
|
||||
|
||||
// errEndpointHeld is returned by listen when the endpoint's name is already held by
|
||||
// some other process, which nebula will not serve alongside: whoever holds it would be
|
||||
// answering nebula ctl. It is only raised on windows, where the default name can be
|
||||
// held by another administrator's process and an override outside the protected
|
||||
// namespace by any account's; on unix a path that is still being served is an earlier
|
||||
// nebula, which clearStale reports as in use.
|
||||
var errEndpointHeld = errors.New("the local control socket's name is held by another process")
|
||||
@@ -0,0 +1,175 @@
|
||||
//go:build !windows
|
||||
|
||||
package localapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestWireRecoversFromBadPathAtStartup covers a socket path that is unusable when nebula
|
||||
// starts. The operator's fix is a config edit and a reload, so the reload has to be able
|
||||
// to bring up a socket that never existed, not only move one that does.
|
||||
func TestWireRecoversFromBadPathAtStartup(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(fmt.Sprintf("local_api:\n control:\n socket: /%s\n", strings.Repeat("x", sunPathMax))))
|
||||
|
||||
srv := Wire(ctx, test.NewLogger(), c, basicRegistry())
|
||||
t.Cleanup(srv.Stop)
|
||||
assert.Empty(t, srv.Path(), "an over-long path must not produce a socket")
|
||||
|
||||
good := testSocket(t)
|
||||
require.NoError(t, c.ReloadConfigString(fmt.Sprintf("local_api:\n control:\n socket: %s\n", good)).Err)
|
||||
|
||||
assert.Equal(t, good, srv.Path())
|
||||
out, errText := run(t, good, "echo", "hi")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[hi]", out)
|
||||
}
|
||||
|
||||
// TestRebindAfterReloadBoundTheSocket covers a HUP that lands inside Wire, after the
|
||||
// reload callback is registered and before the first attempt runs. The callback does the
|
||||
// first bind; the attempt must then find the socket it was about to create already up
|
||||
// and leave it, not fail or rebind it, which would have Wire warn that commands are
|
||||
// unavailable while they are.
|
||||
func TestRebindAfterReloadBoundTheSocket(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
path := testSocket(t)
|
||||
cfg := fmt.Sprintf("local_api:\n control:\n socket: %s\n", path)
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(cfg))
|
||||
|
||||
srv := NewServer(test.NewLogger(), basicRegistry())
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
// Wire's first half, then the HUP.
|
||||
followControlConfig(ctx, test.NewLogger(), c, srv)
|
||||
require.NoError(t, c.ReloadConfigString(cfg).Err)
|
||||
require.Equal(t, path, srv.Path(), "the reload callback does the first bind")
|
||||
|
||||
// Wire's second half.
|
||||
require.NoError(t, srv.Rebind(ctx, path, ownerOnly()))
|
||||
assert.Equal(t, path, srv.Path())
|
||||
out, errText := run(t, path, "echo", "hi")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[hi]", out)
|
||||
}
|
||||
|
||||
// TestWireRetriesAFailedMoveOnPlainReload covers a move whose bind fails for a reason
|
||||
// outside the config: the key names a path under a runtime directory that is not there
|
||||
// yet. The daemon keeps the old socket, but the client reads the new path from the same
|
||||
// file and cannot reach it, so the operator creates the directory and reloads. The key
|
||||
// has not changed since the move was asked for, and the reload still has to make it.
|
||||
func TestWireRetriesAFailedMoveOnPlainReload(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
section := func(path string) string {
|
||||
return fmt.Sprintf("local_api:\n control:\n socket: %s\n", path)
|
||||
}
|
||||
first := testSocket(t)
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(section(first)))
|
||||
|
||||
srv := Wire(ctx, test.NewLogger(), c, basicRegistry())
|
||||
t.Cleanup(srv.Stop)
|
||||
require.Equal(t, first, srv.Path())
|
||||
|
||||
runtimeDir := filepath.Join(privateBase(t), "run")
|
||||
moved := filepath.Join(runtimeDir, DirName, "s.sock")
|
||||
require.NoError(t, c.ReloadConfigString(section(moved)).Err)
|
||||
assert.Equal(t, first, srv.Path(), "a move that cannot bind keeps the socket it had")
|
||||
|
||||
require.NoError(t, os.Mkdir(runtimeDir, 0700))
|
||||
require.NoError(t, c.ReloadConfigString(section(moved)).Err)
|
||||
require.False(t, c.HasChanged(CtlSocketKey), "the config is the same; the fix was on disk")
|
||||
|
||||
assert.Equal(t, moved, srv.Path())
|
||||
_, err := os.Stat(first)
|
||||
assert.True(t, os.IsNotExist(err), "the old socket is given up once the move binds")
|
||||
out, errText := run(t, moved, "echo", "hi")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[hi]", out)
|
||||
}
|
||||
|
||||
// TestWireRecoversOnPlainReloadAfterBadBind covers a path that is fine but a bind that
|
||||
// is not: the runtime directory is missing when nebula starts. The fix is made outside
|
||||
// the config, so the config does not change; a plain reload still has to bring the
|
||||
// socket up.
|
||||
func TestWireRecoversOnPlainReloadAfterBadBind(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
base := privateBase(t)
|
||||
runtimeDir := filepath.Join(base, "run")
|
||||
path := filepath.Join(runtimeDir, DirName, "s.sock")
|
||||
cfg := fmt.Sprintf("local_api:\n control:\n socket: %s\n", path)
|
||||
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(cfg))
|
||||
|
||||
srv := Wire(ctx, test.NewLogger(), c, basicRegistry())
|
||||
t.Cleanup(srv.Stop)
|
||||
assert.Empty(t, srv.Path(), "listen creates one level only, so a missing runtime dir fails the bind")
|
||||
|
||||
require.NoError(t, os.Mkdir(runtimeDir, 0700))
|
||||
require.NoError(t, c.ReloadConfigString(cfg).Err)
|
||||
require.False(t, c.HasChanged(CtlSocketKey), "the config is the same; the fix was on disk")
|
||||
|
||||
assert.Equal(t, path, srv.Path())
|
||||
out, errText := run(t, path, "echo", "hi")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[hi]", out)
|
||||
|
||||
// And a reload with a socket up and no change in the key is still a no-op.
|
||||
require.NoError(t, c.ReloadConfigString(cfg).Err)
|
||||
assert.Equal(t, path, srv.Path())
|
||||
out, errText = run(t, path, "echo", "still")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[still]", out)
|
||||
}
|
||||
|
||||
// TestWireControlCanBeDisabled: local_api.control.enabled false serves no socket, and
|
||||
// the key follows reloads both ways.
|
||||
func TestWireControlCanBeDisabled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
path := testSocket(t)
|
||||
section := func(enabled bool) string {
|
||||
return fmt.Sprintf("local_api:\n control:\n enabled: %t\n socket: %s\n", enabled, path)
|
||||
}
|
||||
|
||||
c := config.NewC(test.NewLogger())
|
||||
require.NoError(t, c.LoadString(section(false)))
|
||||
srv := Wire(ctx, test.NewLogger(), c, basicRegistry())
|
||||
t.Cleanup(srv.Stop)
|
||||
assert.Empty(t, srv.Path())
|
||||
_, err := os.Lstat(path)
|
||||
assert.True(t, os.IsNotExist(err), "no socket is bound")
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(section(true)).Err)
|
||||
assert.Equal(t, path, srv.Path())
|
||||
out, errText := run(t, path, "echo", "on")
|
||||
assert.Empty(t, errText)
|
||||
assert.Equal(t, "[on]", out)
|
||||
|
||||
require.NoError(t, c.ReloadConfigString(section(false)).Err)
|
||||
assert.Empty(t, srv.Path())
|
||||
_, err = os.Lstat(path)
|
||||
assert.True(t, os.IsNotExist(err), "the socket is removed")
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/cpupick"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
@@ -71,7 +72,11 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
}
|
||||
l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
|
||||
|
||||
ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
|
||||
// The command registry is shared by every surface that exposes these commands, so a
|
||||
// command cannot reach one of them without reaching the others.
|
||||
cmdRegistry := commands.New()
|
||||
|
||||
ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"), cmdRegistry)
|
||||
if err != nil {
|
||||
return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
|
||||
}
|
||||
@@ -244,8 +249,6 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
|
||||
pinThreads := c.GetBool("tun.pin_threads", true)
|
||||
cpuAffinity := parseCpuAffinity(c, l, routines)
|
||||
var defaultCpuAffinity []int
|
||||
staged := parseStagedConfig(c, l)
|
||||
if pinThreads && routines > 1 && len(cpuAffinity) == 0 && !configTest {
|
||||
// The operator didn't choose pin CPUs, so pick a default set that
|
||||
// prefers performance cores and doesn't stack co-located instances
|
||||
@@ -272,7 +275,7 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
l.Warn("tun.pin_threads_key is invalid, using PID")
|
||||
}
|
||||
|
||||
defaultCpuAffinity = cpupick.Default(routines, key, l)
|
||||
cpuAffinity = cpupick.Default(routines, key, l)
|
||||
}
|
||||
|
||||
ifConfig := &InterfaceConfig{
|
||||
@@ -297,9 +300,7 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
punchy: punchy,
|
||||
ConntrackCacheTimeout: conntrackCacheTimeout,
|
||||
CpuAffinity: cpuAffinity,
|
||||
defaultCpuAffinity: defaultCpuAffinity,
|
||||
PinThreads: pinThreads,
|
||||
staged: staged,
|
||||
l: l,
|
||||
}
|
||||
|
||||
@@ -347,13 +348,14 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
attachCommands(l, c, ssh, ifce)
|
||||
attachCommands(l, c, cmdRegistry, ifce)
|
||||
|
||||
networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
|
||||
|
||||
return &Control{
|
||||
state: StateReady,
|
||||
f: ifce,
|
||||
commands: cmdRegistry,
|
||||
l: l,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
|
||||
@@ -5,14 +5,12 @@ import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
cert_test "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/slackhq/nebula/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -125,70 +123,3 @@ firewall:
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, ctrl, "a config test hands back nothing to stop, so it must stop itself")
|
||||
}
|
||||
|
||||
func TestParseStagedConfig(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
staged := func(workers any) stagedConfig {
|
||||
c := config.NewC(l)
|
||||
if workers != nil {
|
||||
c.Settings["tun"] = map[string]any{"staged": map[string]any{"workers": workers}}
|
||||
}
|
||||
return parseStagedConfig(c, l)
|
||||
}
|
||||
for _, workers := range []any{nil, -1, 0} {
|
||||
require.Equal(t, stagedConfig{}, staged(workers))
|
||||
}
|
||||
if runtime.GOOS != "linux" {
|
||||
require.Equal(t, stagedConfig{}, staged(2))
|
||||
return
|
||||
}
|
||||
want := stagedConfig{workers: 2, tx: !noiseutil.EncryptLockNeeded, rx: true, inlineBelow: 256, gateHold: stagedGateHold,
|
||||
txSlots: 8, rxSlots: 6}
|
||||
require.Equal(t, want, staged(2))
|
||||
|
||||
c := config.NewC(l)
|
||||
c.Settings["listen"] = map[string]any{"batch": 128}
|
||||
c.Settings["tun"] = map[string]any{"staged": map[string]any{"workers": 2, "tx_slots": 3, "rx_slots": 1}}
|
||||
got := parseStagedConfig(c, l)
|
||||
require.Equal(t, []int{3, 2}, []int{got.txSlots, got.rxSlots}, "overrides apply, down to the minimum")
|
||||
|
||||
c = config.NewC(l)
|
||||
c.Settings["tun"] = map[string]any{"staged": map[string]any{"workers": 2, "tx": false, "inline_below": 0}}
|
||||
got = parseStagedConfig(c, l)
|
||||
require.False(t, got.tx, "tx: false keeps transmit inline")
|
||||
require.True(t, got.rx)
|
||||
require.Zero(t, got.inlineBelow, "inline_below: 0 hands every batch off")
|
||||
|
||||
c = config.NewC(l)
|
||||
c.Settings["tun"] = map[string]any{"staged": map[string]any{"workers": 2, "inline_below": 32}}
|
||||
require.Equal(t, 32, parseStagedConfig(c, l).inlineBelow)
|
||||
c.Settings["tun"] = map[string]any{"staged": map[string]any{"workers": 2, "inline_below": -1}}
|
||||
require.Zero(t, parseStagedConfig(c, l).inlineBelow, "a negative threshold is 0")
|
||||
|
||||
for _, tt := range []struct {
|
||||
hold any
|
||||
want int
|
||||
}{{nil, stagedGateHold}, {8, 8}, {0, 1}, {-3, 1}} {
|
||||
c = config.NewC(l)
|
||||
settings := map[string]any{"workers": 2}
|
||||
if tt.hold != nil {
|
||||
settings["gate_hold"] = tt.hold
|
||||
}
|
||||
c.Settings["tun"] = map[string]any{"staged": settings}
|
||||
require.Equal(t, tt.want, parseStagedConfig(c, l).gateHold, "gate_hold %v", tt.hold)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedSlots(t *testing.T) {
|
||||
for _, tt := range []struct{ workers, batch, tx, rx int }{
|
||||
{workers: 2, batch: 64, tx: 8, rx: 6},
|
||||
{workers: 12, batch: 64, tx: 14, rx: 6},
|
||||
{workers: 2, batch: 96, tx: 8, rx: 4},
|
||||
{workers: 2, batch: 512, tx: 8, rx: 4},
|
||||
{workers: 2, batch: 32, tx: 8, rx: 6},
|
||||
{workers: 2, batch: 1, tx: 8, rx: 6},
|
||||
} {
|
||||
tx, rx := stagedSlots(tt.workers, tt.batch, 0, 0)
|
||||
require.Equal(t, []int{tt.tx, tt.rx}, []int{tx, rx}, "workers %d batch %d", tt.workers, tt.batch)
|
||||
}
|
||||
}
|
||||
+9
-25
@@ -130,10 +130,17 @@ func (f *Interface) readOutsidePackets(via ViaSender, packet []byte, rxc *rxCont
|
||||
}
|
||||
|
||||
out, err := hostinfo.ConnectionState.Decrypt(f.l, h.MessageCounter, packet, rxc.nb)
|
||||
if !f.finishOutsideDecrypt(hostinfo, via, h.MessageCounter, err) {
|
||||
if err != nil {
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("Failed to decrypt packet", "error", err, "from", via, "header", h)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Roam before we respond
|
||||
f.handleHostRoaming(hostinfo, via)
|
||||
f.connectionManager.In(hostinfo)
|
||||
|
||||
switch h.Type {
|
||||
case header.Message:
|
||||
switch h.Subtype {
|
||||
@@ -466,36 +473,13 @@ func parseV4(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// finishOutsideDecrypt logs a failed decrypt, or roams and records the traffic for an authenticated packet before it
|
||||
// is handled. It reports whether the packet authenticated.
|
||||
func (f *Interface) finishOutsideDecrypt(hostinfo *HostInfo, via ViaSender, counter uint64, err error) bool {
|
||||
if err != nil {
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("Failed to decrypt packet", "error", err, "from", via, "counter", counter)
|
||||
}
|
||||
return false
|
||||
}
|
||||
// Roam before we respond
|
||||
f.handleHostRoaming(hostinfo, via)
|
||||
f.connectionManager.In(hostinfo)
|
||||
return true
|
||||
}
|
||||
|
||||
// flushOutside ends a receive batch: it writes out the tun coalescer and drops the batch's hostmap cache.
|
||||
func (f *Interface) flushOutside(rxc *rxContext) {
|
||||
if err := f.batchers[rxc.q].Flush(); err != nil {
|
||||
f.l.Error("Failed to flush tun coalescer", "error", err)
|
||||
}
|
||||
clear(rxc.hostmapCache)
|
||||
}
|
||||
|
||||
func (f *Interface) handleOutsideMessagePacket(hostinfo *HostInfo, messageCounter uint64, out []byte, rxc *rxContext) {
|
||||
err := newPacket(out, true, rxc.fwPacket)
|
||||
if err != nil {
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("Error while validating inbound packet", "error", err, "packet", out)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
dropReason := f.firewall.Drop(rxc.fwPacket.Packet, true, hostinfo, f.pki.GetCAPool(), rxc.ctCache.Get())
|
||||
|
||||
@@ -43,14 +43,6 @@ func (b *SendBatch) Commit(pkt []byte, dst netip.AddrPort) {
|
||||
b.dsts = append(b.dsts, dst)
|
||||
}
|
||||
|
||||
// Reset drops every queued packet without sending it.
|
||||
func (b *SendBatch) Reset() {
|
||||
clear(b.bufs)
|
||||
b.bufs = b.bufs[:0]
|
||||
b.dsts = b.dsts[:0]
|
||||
b.arena.Reset()
|
||||
}
|
||||
|
||||
// Flush writes every queued packet and reports how many actually went out. A short count means some destinations
|
||||
// were undeliverable; the batch is drained either way.
|
||||
func (b *SendBatch) Flush() (int, error) {
|
||||
@@ -59,6 +51,9 @@ func (b *SendBatch) Flush() (int, error) {
|
||||
if len(b.bufs) > 0 {
|
||||
written, err = b.out.WriteBatch(b.bufs, b.dsts)
|
||||
}
|
||||
b.Reset()
|
||||
clear(b.bufs)
|
||||
b.bufs = b.bufs[:0]
|
||||
b.dsts = b.dsts[:0]
|
||||
b.arena.Reset()
|
||||
return written, err
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type offloadQueueSet struct {
|
||||
// usoEnabled is true when newTun successfully negotiated TUN_F_USO4|6 with the kernel.
|
||||
// Queues created by Add inherit this and surface it via Offload.USOSupported so coalescers can gate USO emission.
|
||||
usoEnabled bool
|
||||
shutdown atomic.Bool
|
||||
closed atomic.Bool
|
||||
// l is handed to each queue for its bad-vnet-header drop logging.
|
||||
l *slog.Logger
|
||||
@@ -69,6 +70,17 @@ func (c *offloadQueueSet) wakeForShutdown() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Shutdown wakes every reader without releasing any fds, they see POLLIN on the eventfd and return os.ErrClosed
|
||||
func (c *offloadQueueSet) Shutdown() error {
|
||||
if c.shutdown.Swap(true) {
|
||||
return nil
|
||||
}
|
||||
for _, x := range c.pq {
|
||||
x.shutdown.Store(true)
|
||||
}
|
||||
return c.wakeForShutdown()
|
||||
}
|
||||
|
||||
func (c *offloadQueueSet) Close() error {
|
||||
if c.closed.Swap(true) {
|
||||
return nil
|
||||
@@ -76,9 +88,7 @@ func (c *offloadQueueSet) Close() error {
|
||||
|
||||
errs := []error{}
|
||||
|
||||
// Signal all readers blocked in poll to wake up and exit.
|
||||
// They observe POLLIN on the shutdown eventfd and return os.ErrClosed.
|
||||
if err := c.wakeForShutdown(); err != nil {
|
||||
if err := c.Shutdown(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ type pollQueueSet struct {
|
||||
// pqi is exactly the same as pq, but stored as the interface type
|
||||
pqi []Queue
|
||||
shutdownFd int
|
||||
shutdown atomic.Bool
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
@@ -59,6 +60,17 @@ func (c *pollQueueSet) wakeForShutdown() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Shutdown wakes every reader without releasing any fds, they see POLLIN on the eventfd and return os.ErrClosed
|
||||
func (c *pollQueueSet) Shutdown() error {
|
||||
if c.shutdown.Swap(true) {
|
||||
return nil
|
||||
}
|
||||
for _, x := range c.pq {
|
||||
x.shutdown.Store(true)
|
||||
}
|
||||
return c.wakeForShutdown()
|
||||
}
|
||||
|
||||
func (c *pollQueueSet) Close() error {
|
||||
if c.closed.Swap(true) {
|
||||
return nil
|
||||
@@ -66,9 +78,7 @@ func (c *pollQueueSet) Close() error {
|
||||
|
||||
errs := []error{}
|
||||
|
||||
// Signal all readers blocked in poll to wake up and exit.
|
||||
// They observe POLLIN on the shutdown eventfd and return os.ErrClosed.
|
||||
if err := c.wakeForShutdown(); err != nil {
|
||||
if err := c.Shutdown(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
|
||||
|
||||
+2
-9
@@ -7,6 +7,8 @@ import (
|
||||
// QueueSet holds one or many Queue objects and helps close them in an orderly way.
|
||||
type QueueSet interface {
|
||||
io.Closer
|
||||
// Shutdown wakes every reader without releasing any fds, Close only once they have exited
|
||||
Shutdown() error
|
||||
Queues() []Queue
|
||||
|
||||
// Add takes a tun fd, adds it to the set, and prepares it for use as a Queue.
|
||||
@@ -75,15 +77,6 @@ type GSOInfo struct {
|
||||
// superpacket that needs segmentation before its bytes can be encrypted and sent on the wire.
|
||||
func (g GSOInfo) IsSuperpacket() bool { return g.Size > 0 }
|
||||
|
||||
// SegmentCount reports how many segments SegmentSuperpacket will cut p into, without touching its bytes.
|
||||
func (p Packet) SegmentCount() int {
|
||||
if !p.GSO.IsSuperpacket() {
|
||||
return 1
|
||||
}
|
||||
n := (len(p.Bytes) - int(p.GSO.HdrLen) + int(p.GSO.Size) - 1) / int(p.GSO.Size)
|
||||
return max(n, 1)
|
||||
}
|
||||
|
||||
// Clone returns a Packet whose Bytes is a freshly allocated copy of p.Bytes,
|
||||
// safe to retain past the next Read or Close on the originating Queue.
|
||||
// GSO metadata is copied verbatim.
|
||||
|
||||
@@ -66,7 +66,9 @@ type Offload struct {
|
||||
// usoEnabled records whether the kernel agreed to TUN_F_USO* on this FD,
|
||||
// so writers can decide whether emitting GSO_UDP_L4 superpackets is safe.
|
||||
usoEnabled bool
|
||||
closed atomic.Bool
|
||||
// shutdown is set before shutdownFd is signaled, a busy reader never polls to see that
|
||||
shutdown atomic.Bool
|
||||
closed atomic.Bool
|
||||
|
||||
// gsoHdrBuf is a per-queue 10-byte scratch for the virtio_net_hdr emitted
|
||||
// by WriteGSO. Kept separate from the read-only package-level validVnetHdr
|
||||
@@ -176,6 +178,9 @@ func (r *Offload) readPacket(block bool) (int, error) {
|
||||
// This amortizes the poll wake over bursts of small packets (e.g. TCP ACKs).
|
||||
// Packet.Bytes slices point into the Offload's internal buffer and are only valid until the next Read or Close on this Queue.
|
||||
func (r *Offload) Read() ([]Packet, error) {
|
||||
if r.shutdown.Load() {
|
||||
return nil, os.ErrClosed
|
||||
}
|
||||
r.pending = r.pending[:0]
|
||||
r.rxOff = 0
|
||||
|
||||
@@ -219,21 +224,6 @@ func (r *Offload) Read() ([]Packet, error) {
|
||||
return r.pending, nil
|
||||
}
|
||||
|
||||
// SwapRxBuf installs buf as the receive buffer for the following Reads and returns the one backing the packets
|
||||
// of the most recent Read, so the caller can keep them past the next Read. A nil buf allocates a replacement of
|
||||
// the required size. Single-reader only, like Read.
|
||||
func (r *Offload) SwapRxBuf(buf []byte) []byte {
|
||||
if buf == nil {
|
||||
buf = make([]byte, tunRxBufCap)
|
||||
}
|
||||
if len(buf) < tunRxBufCap {
|
||||
panic(fmt.Sprintf("tio: SwapRxBuf buffer is %d bytes, need %d", len(buf), tunRxBufCap))
|
||||
}
|
||||
old := r.rxBuf
|
||||
r.rxBuf = buf
|
||||
return old
|
||||
}
|
||||
|
||||
// logDroppedRead reports a tun packet dropped for a bad/unsupported virtio
|
||||
// header. Debug-gated so the happy path never pays for attribute assembly.
|
||||
func (r *Offload) logDroppedRead(err error) {
|
||||
|
||||
@@ -13,7 +13,9 @@ import (
|
||||
type Poll struct {
|
||||
fd int
|
||||
shutdownFd int
|
||||
closed atomic.Bool
|
||||
// shutdown is set before shutdownFd is signaled, a busy reader never polls to see that
|
||||
shutdown atomic.Bool
|
||||
closed atomic.Bool
|
||||
|
||||
readBuf []byte
|
||||
batchRet [1]Packet
|
||||
@@ -52,6 +54,9 @@ func (t *Poll) blockOnWrite() error {
|
||||
// config currently lose that batching. blockOn and the EAGAIN plumbing are
|
||||
// already shared; kept one-packet-per-Read for now to preserve behavior.
|
||||
func (t *Poll) Read() ([]Packet, error) {
|
||||
if t.shutdown.Load() {
|
||||
return nil, os.ErrClosed
|
||||
}
|
||||
n, err := t.readOne(t.readBuf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -223,3 +223,30 @@ func TestOffloadQueueSet_Close_ClosesShutdownFd(t *testing.T) {
|
||||
// Second Close must not touch fds (shutdownFd is now -1) and must return nil.
|
||||
require.NoError(t, qs.Close())
|
||||
}
|
||||
|
||||
// A busy reader never polls the shutdown eventfd, so Read has to stop on its own with data still waiting
|
||||
func TestQueueSet_ShutdownStopsReaderWithDataWaiting(t *testing.T) {
|
||||
sets := map[string]func() (QueueSet, error){
|
||||
"poll": NewPollQueueSet,
|
||||
"offload": func() (QueueSet, error) { return NewOffloadQueueSet(false, slog.New(slog.DiscardHandler)) },
|
||||
}
|
||||
for name, newSet := range sets {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
var fds [2]int
|
||||
require.NoError(t, unix.Pipe2(fds[:], unix.O_CLOEXEC))
|
||||
t.Cleanup(func() { _ = unix.Close(fds[1]) })
|
||||
|
||||
qs, err := newSet()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, qs.Add(fds[0]))
|
||||
t.Cleanup(func() { _ = qs.Close() })
|
||||
|
||||
_, err = unix.Write(fds[1], make([]byte, 64))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, qs.Shutdown())
|
||||
|
||||
_, err = qs.Queues()[0].Read()
|
||||
require.ErrorIs(t, err, os.ErrClosed)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -911,25 +911,6 @@ func TestOffloadWriteZeroLength(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOffloadSwapRxBuf: SwapRxBuf hands over the buffer the last Read filled and reads into the one it is given.
|
||||
func TestOffloadSwapRxBuf(t *testing.T) {
|
||||
o := &Offload{rxBuf: make([]byte, tunRxBufCap)}
|
||||
read := o.rxBuf
|
||||
owned := o.SwapRxBuf(nil)
|
||||
if &owned[0] != &read[0] || len(o.rxBuf) != tunRxBufCap || &o.rxBuf[0] == &read[0] {
|
||||
t.Fatal("SwapRxBuf(nil) must hand over the last read buffer and allocate a new one")
|
||||
}
|
||||
if back := o.SwapRxBuf(owned); &back[0] == &owned[0] || &o.rxBuf[0] != &owned[0] {
|
||||
t.Fatal("SwapRxBuf must install the buffer it is given")
|
||||
}
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Fatal("SwapRxBuf must reject a short buffer")
|
||||
}
|
||||
}()
|
||||
o.SwapRxBuf(make([]byte, 10))
|
||||
}
|
||||
|
||||
// TestWriteGSOSuperpacketGeometry decodes the vnet header the kernel would see for a multi-segment write:
|
||||
// the GSO type must match the proto and IP version
|
||||
// gso_size must be the per-segment size (the kernel rejects a superpacket with gso_size == 0),
|
||||
|
||||
+54
-84
@@ -3,7 +3,6 @@
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/bits"
|
||||
@@ -12,6 +11,7 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/gaissmai/bart"
|
||||
@@ -35,6 +35,26 @@ type tun struct {
|
||||
// and routes for it. NEPacketTunnelProvider on darwin does this.
|
||||
hostOwned bool
|
||||
l *slog.Logger
|
||||
|
||||
// routesMu serializes changes to the system routing table between reload and the route watcher, and guards the
|
||||
// fields below it
|
||||
routesMu sync.Mutex
|
||||
// routeStates is who held each installable unsafe_route prefix when we last looked
|
||||
routeStates map[netip.Prefix]routeState
|
||||
// routeWatch is the routing socket watchRoutes reads, Close closes it
|
||||
routeWatch *os.File
|
||||
// routeSweep reconciles the unsafe_routes every routeSweepEvery
|
||||
routeSweep *time.Timer
|
||||
routeSweepEvery time.Duration
|
||||
closed bool
|
||||
|
||||
// routeMovers is who last changed each unsafe_route prefix since the last reconcile, for its logs. It has its own
|
||||
// lock so the route watcher never waits on a reconcile
|
||||
routeMoversMu sync.Mutex
|
||||
routeMovers map[netip.Prefix]routeMover
|
||||
|
||||
// lastRouteEvent is when the routing socket last reported something that may have moved a prefix, in unix nanos
|
||||
lastRouteEvent atomic.Int64
|
||||
}
|
||||
|
||||
type ifReq struct {
|
||||
@@ -139,11 +159,12 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*t
|
||||
}
|
||||
|
||||
t := &tun{
|
||||
f: os.NewFile(uintptr(fd), ""),
|
||||
Device: name,
|
||||
vpnNetworks: vpnNetworks,
|
||||
DefaultMTU: getMTU(l, c),
|
||||
l: l,
|
||||
f: os.NewFile(uintptr(fd), ""),
|
||||
Device: name,
|
||||
vpnNetworks: vpnNetworks,
|
||||
DefaultMTU: getMTU(l, c),
|
||||
routeSweepEvery: routeSweepInterval,
|
||||
l: l,
|
||||
}
|
||||
|
||||
err = t.reload(c, true, nil)
|
||||
@@ -219,6 +240,16 @@ func utunNameFromFd(fd int) string {
|
||||
}
|
||||
|
||||
func (t *tun) Close() error {
|
||||
t.routesMu.Lock()
|
||||
t.closed = true
|
||||
if t.routeWatch != nil {
|
||||
_ = t.routeWatch.Close()
|
||||
}
|
||||
if t.routeSweep != nil {
|
||||
t.routeSweep.Stop()
|
||||
}
|
||||
t.routesMu.Unlock()
|
||||
|
||||
if t.f != nil {
|
||||
return t.f.Close()
|
||||
}
|
||||
@@ -287,8 +318,22 @@ func (t *tun) Activate() error {
|
||||
return fmt.Errorf("failed to run tun device: %s", err)
|
||||
}
|
||||
|
||||
// Watch before adding so a route removed in between is still noticed
|
||||
watch, err := openRouteSocket()
|
||||
if err != nil {
|
||||
t.l.Error("Failed to watch the system routing table, unsafe_routes held by another interface are only retried every minute", "error", err)
|
||||
}
|
||||
|
||||
// Unsafe path routes
|
||||
return t.addRoutes(false, nil)
|
||||
if err = t.addRoutes(false, nil); err != nil {
|
||||
if watch != nil {
|
||||
_ = watch.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
t.startRouteWatch(watch)
|
||||
return nil
|
||||
}
|
||||
|
||||
// activate4 assigns our vpn address as a /32 and routes the vpn network to the tun explicitly.
|
||||
@@ -393,7 +438,8 @@ func (t *tun) reload(c *config.C, initial bool, r *config.Reload) error {
|
||||
}
|
||||
|
||||
if !initial && !change {
|
||||
return nil
|
||||
// Any reload puts back the unsafe_routes someone deleted
|
||||
return t.addRoutes(true, r)
|
||||
}
|
||||
|
||||
routeTree, err := makeRouteTree(t.l, routes, false)
|
||||
@@ -511,82 +557,6 @@ func getLinkAddr(name string) (*netroute.LinkAddr, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (t *tun) addRoutes(logErrors bool, rl *config.Reload) error {
|
||||
// The route tree is still ours, the system routing table is not
|
||||
if t.hostOwned {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Activate hasn't run yet, it will install the routes
|
||||
linkAddr := t.linkAddr.Load()
|
||||
if linkAddr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
routes := *t.Routes.Load()
|
||||
systemRoutes := sync.OnceValues(fetchRoutes)
|
||||
|
||||
for _, r := range routes {
|
||||
if len(r.Via) == 0 || !r.Install {
|
||||
// We don't allow route MTUs so only install routes with a via
|
||||
continue
|
||||
}
|
||||
|
||||
err := addRoute(r.Cidr, linkAddr)
|
||||
if err != nil {
|
||||
if errors.Is(err, unix.EEXIST) {
|
||||
// Every route we added already exists on a reload, only warn about someone else's
|
||||
msgs, err := systemRoutes()
|
||||
if err != nil {
|
||||
t.l.Warn("unable to add unsafe_route, a route already exists but its interface could not be determined", "route", r.Cidr, "error", err)
|
||||
} else if routeInterfaceIn(msgs, r.Cidr) != linkAddr.Index {
|
||||
t.l.Warn("unable to add unsafe_route, the destination is already routed through another interface", "route", r.Cidr)
|
||||
}
|
||||
} else {
|
||||
retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
|
||||
if logErrors {
|
||||
retErr.Log(t.l)
|
||||
rl.Failed()
|
||||
} else {
|
||||
return retErr
|
||||
}
|
||||
}
|
||||
} else {
|
||||
t.l.Info("Added route", "route", r)
|
||||
// A cidr listed twice would otherwise find our own route missing from an older fetch
|
||||
systemRoutes = sync.OnceValues(fetchRoutes)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *tun) removeRoutes(routes []Route, rl *config.Reload) error {
|
||||
linkAddr := t.linkAddr.Load()
|
||||
if t.hostOwned || linkAddr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, r := range routes {
|
||||
if len(r.Via) == 0 || !r.Install {
|
||||
// addRoutes never installs these
|
||||
continue
|
||||
}
|
||||
|
||||
err := delRoute(r.Cidr, linkAddr)
|
||||
if errors.Is(err, unix.ESRCH) {
|
||||
// Already gone, which is what we wanted
|
||||
t.l.Info("Route was already removed", "route", r)
|
||||
} else if err != nil {
|
||||
t.l.Error("Failed to remove route", "error", err, "route", r)
|
||||
rl.Failed()
|
||||
} else {
|
||||
t.l.Info("Removed route", "route", r)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func addRoute(prefix netip.Prefix, gateway netroute.Addr) error {
|
||||
sock, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/routing"
|
||||
@@ -104,6 +109,367 @@ func TestTunReloadLeavesRoutesItNeverInstalled(t *testing.T) {
|
||||
assert.Equal(t, lo0.Index, routeInterfaceIn(msgs, netip.MustParsePrefix(cidr)))
|
||||
}
|
||||
|
||||
// Captured on macOS 15.6 while adding and removing 198.51.100.77/24 on a feth
|
||||
const (
|
||||
// The kernel deleting the address's subnet route. It packs its sockaddrs without padding, x/net/route can't parse it
|
||||
kernelSubnetDelete = "870005022300000000010002070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010020000c63364000000000000000000141223000600000000000000000000000000000007ffffffffffff"
|
||||
addressRemoved = "5000050db400000001010000230000000000000007020000ffffff00141223000606060066657468373766657468004d10020000c633644d000000000000000010020000c63364ff0000000000000000"
|
||||
// With no interface address, which x/net/route skips
|
||||
interfaceChanged = "7000050e000000004288000023000000060000060e000000dc05000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000073e5ce6a0000000000000000000001000000000000000000"
|
||||
)
|
||||
|
||||
func TestRoutesMayHaveMoved(t *testing.T) {
|
||||
cidr := netip.MustParsePrefix("192.168.1.0/24")
|
||||
via := routing.Gateways{routing.NewGateway(netip.MustParseAddr("10.250.0.2"), 1)}
|
||||
routes := []Route{{Cidr: cidr, Via: via, Install: true}}
|
||||
// A request like route(8) sends, the kernel echoes it to every routing socket
|
||||
request := func(typ, flags int, dst, mask [4]byte) []byte {
|
||||
m := &netroute.RouteMessage{
|
||||
Version: unix.RTM_VERSION,
|
||||
Type: typ,
|
||||
Flags: flags,
|
||||
ID: 1234,
|
||||
Addrs: []netroute.Addr{
|
||||
unix.RTAX_DST: &netroute.Inet4Addr{IP: dst},
|
||||
unix.RTAX_GATEWAY: &netroute.LinkAddr{Index: 4},
|
||||
unix.RTAX_NETMASK: &netroute.Inet4Addr{IP: mask},
|
||||
},
|
||||
}
|
||||
b, err := m.Marshal()
|
||||
require.NoError(t, err)
|
||||
return b
|
||||
}
|
||||
raw := func(s string) []byte {
|
||||
b, err := hex.DecodeString(s)
|
||||
require.NoError(t, err)
|
||||
return b
|
||||
}
|
||||
lan, mask := [4]byte{192, 168, 1, 0}, [4]byte{255, 255, 255, 0}
|
||||
routesMayHaveMoved := func(b []byte, routes []Route) bool {
|
||||
moved, _, _ := routesMayHaveMoved(b, routes)
|
||||
return moved
|
||||
}
|
||||
|
||||
assert.True(t, routesMayHaveMoved(request(unix.RTM_DELETE, unix.RTF_UP, lan, mask), routes))
|
||||
assert.True(t, routesMayHaveMoved(request(unix.RTM_ADD, unix.RTF_UP, lan, mask), routes))
|
||||
assert.True(t, routesMayHaveMoved(request(unix.RTM_CHANGE, unix.RTF_UP, lan, mask), routes))
|
||||
assert.False(t, routesMayHaveMoved(request(unix.RTM_GET, unix.RTF_UP, lan, mask), routes))
|
||||
assert.False(t, routesMayHaveMoved(request(unix.RTM_DELETE, unix.RTF_UP|unix.RTF_IFSCOPE, lan, mask), routes), "a scoped route never held the prefix")
|
||||
assert.False(t, routesMayHaveMoved(request(unix.RTM_ADD, unix.RTF_UP|unix.RTF_IFSCOPE, lan, mask), routes), "configd adds a scoped copy for each interface")
|
||||
assert.False(t, routesMayHaveMoved(request(unix.RTM_DELETE, unix.RTF_UP, lan, [4]byte{255, 255, 0, 0}), routes), "only an exact prefix counts")
|
||||
assert.False(t, routesMayHaveMoved(request(unix.RTM_DELETE, unix.RTF_UP, lan, mask), []Route{{Cidr: cidr, Install: true}}), "a route with no via is never installed")
|
||||
assert.False(t, routesMayHaveMoved(request(unix.RTM_DELETE, unix.RTF_UP, lan, mask), []Route{{Cidr: cidr, Via: via}}), "install: false")
|
||||
|
||||
failed := request(unix.RTM_DELETE, unix.RTF_UP, lan, mask)
|
||||
binary.NativeEndian.PutUint32(failed[24:28], uint32(unix.ESRCH))
|
||||
assert.False(t, routesMayHaveMoved(failed, routes), "a failed request is echoed too")
|
||||
|
||||
_, err := netroute.ParseRIB(unix.NET_RT_DUMP, raw(kernelSubnetDelete))
|
||||
require.Error(t, err, "if x/net/route learns to parse these, match their prefix instead")
|
||||
assert.True(t, routesMayHaveMoved(raw(kernelSubnetDelete), routes), "the kernel's own deletes could be any prefix")
|
||||
neighbor := raw(kernelSubnetDelete)
|
||||
binary.NativeEndian.PutUint32(neighbor[8:12], unix.RTF_UP|unix.RTF_HOST|unix.RTF_LLINFO)
|
||||
assert.False(t, routesMayHaveMoved(neighbor, routes), "a neighbor expiring")
|
||||
|
||||
assert.True(t, routesMayHaveMoved(raw(addressRemoved), routes))
|
||||
assert.True(t, routesMayHaveMoved(raw(interfaceChanged), routes), "detaching an interface deletes its routes without a message for each")
|
||||
}
|
||||
|
||||
// A request names its prefix and who made it, the kernel's own and interface changes name neither
|
||||
func TestRoutesMayHaveMovedSaysWho(t *testing.T) {
|
||||
cidr := netip.MustParsePrefix("192.168.1.0/24")
|
||||
routes := []Route{{Cidr: cidr, Via: routing.Gateways{routing.NewGateway(netip.MustParseAddr("10.250.0.2"), 1)}, Install: true}}
|
||||
m := &netroute.RouteMessage{
|
||||
Version: unix.RTM_VERSION,
|
||||
Type: unix.RTM_CHANGE,
|
||||
Flags: unix.RTF_UP,
|
||||
ID: 1234,
|
||||
Addrs: []netroute.Addr{
|
||||
unix.RTAX_DST: &netroute.Inet4Addr{IP: [4]byte{192, 168, 1, 0}},
|
||||
unix.RTAX_GATEWAY: &netroute.LinkAddr{Index: 4},
|
||||
unix.RTAX_NETMASK: &netroute.Inet4Addr{IP: [4]byte{255, 255, 255, 0}},
|
||||
},
|
||||
}
|
||||
b, err := m.Marshal()
|
||||
require.NoError(t, err)
|
||||
moved, p, pid := routesMayHaveMoved(b, routes)
|
||||
assert.True(t, moved)
|
||||
assert.Equal(t, cidr, p)
|
||||
assert.Equal(t, int32(1234), pid)
|
||||
|
||||
for name, s := range map[string]string{"kernel": kernelSubnetDelete, "ifinfo": interfaceChanged} {
|
||||
b, err := hex.DecodeString(s)
|
||||
require.NoError(t, err)
|
||||
moved, p, pid := routesMayHaveMoved(b, routes)
|
||||
assert.True(t, moved, name)
|
||||
assert.False(t, p.IsValid(), name)
|
||||
assert.Zero(t, pid, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessName(t *testing.T) {
|
||||
assert.Equal(t, "launchd", processName(1))
|
||||
self := filepath.Base(os.Args[0])
|
||||
assert.Equal(t, self[:min(len(self), 16)], processName(int32(os.Getpid())))
|
||||
assert.Empty(t, processName(-1))
|
||||
}
|
||||
|
||||
// newRouteTestTun is an activated tun for the root tests below with an unsafe_route for each of cidrs. sweep replaces
|
||||
// the minute between sweeps when it isn't zero.
|
||||
func newRouteTestTun(t *testing.T, sweep time.Duration, cidrs ...string) (*tun, *config.C, string) {
|
||||
requireRoot(t)
|
||||
|
||||
cfg := "tun:\n unsafe_routes:\n"
|
||||
for _, cidr := range cidrs {
|
||||
via := "10.250.0.2"
|
||||
if netip.MustParsePrefix(cidr).Addr().Is6() {
|
||||
via = "fd00:250::2"
|
||||
}
|
||||
cfg += " - route: " + cidr + "\n via: " + via + "\n"
|
||||
}
|
||||
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
require.NoError(t, c.LoadString(cfg))
|
||||
tn, err := newTun(c, l, []netip.Prefix{netip.MustParsePrefix("10.250.0.1/24"), netip.MustParsePrefix("fd00:250::1/64")}, false)
|
||||
require.NoError(t, err)
|
||||
if sweep != 0 {
|
||||
tn.routeSweepEvery = sweep
|
||||
}
|
||||
t.Cleanup(func() { _ = tn.Close() })
|
||||
require.NoError(t, tn.Activate())
|
||||
return tn, c, cfg
|
||||
}
|
||||
|
||||
func requireRoot(t *testing.T) {
|
||||
if os.Geteuid() != 0 {
|
||||
t.Skip("creating interfaces and adding routes needs root")
|
||||
}
|
||||
}
|
||||
|
||||
// routeVia is the index of the interface that routes cidr, 0 if none does
|
||||
func routeVia(t *testing.T, cidr string) int {
|
||||
msgs, err := fetchRoutes()
|
||||
require.NoError(t, err)
|
||||
return routeInterfaceIn(msgs, netip.MustParsePrefix(cidr))
|
||||
}
|
||||
|
||||
// routeStateOf is what tn made of cidr when it last looked
|
||||
func routeStateOf(tn *tun, cidr string) routeState {
|
||||
tn.routesMu.Lock()
|
||||
defer tn.routesMu.Unlock()
|
||||
return tn.routeStates[netip.MustParsePrefix(cidr)]
|
||||
}
|
||||
|
||||
func routeArgs(action, cidr string, extra ...string) []string {
|
||||
args := []string{"-q", "-n", action}
|
||||
if netip.MustParsePrefix(cidr).Addr().Is6() {
|
||||
args = append(args, "-inet6")
|
||||
}
|
||||
return append(append(args, "-net", cidr), extra...)
|
||||
}
|
||||
|
||||
func routeCmd(t *testing.T, action, cidr string, extra ...string) {
|
||||
requireRouteOK(t, exec.Command("route", routeArgs(action, cidr, extra...)...))
|
||||
}
|
||||
|
||||
// requireRouteOK runs cmd, which runs route(8). route exits 0 when the kernel rejects its request, only what it prints
|
||||
// says so
|
||||
func requireRouteOK(t *testing.T, cmd *exec.Cmd) {
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoError(t, err, string(out))
|
||||
require.NotContains(t, string(out), "writing to routing socket")
|
||||
}
|
||||
|
||||
// cleanupRoute deletes cidr's route when the test ends, whoever holds it
|
||||
func cleanupRoute(t *testing.T, cidr string) {
|
||||
t.Cleanup(func() { _ = exec.Command("route", routeArgs("delete", cidr)...).Run() })
|
||||
}
|
||||
|
||||
// routeThroughLo0 routes cidr through lo0, like a lan nebula started on
|
||||
func routeThroughLo0(t *testing.T, cidr string) int {
|
||||
requireRoot(t)
|
||||
routeCmd(t, "add", cidr, "-interface", "lo0")
|
||||
cleanupRoute(t, cidr)
|
||||
lo0, err := net.InterfaceByName("lo0")
|
||||
require.NoError(t, err)
|
||||
return lo0.Index
|
||||
}
|
||||
|
||||
// Leaving the lan that held an unsafe_route's prefix must not need a restart to get the unsafe_route
|
||||
func TestTunAddsRouteOnceItsPrefixIsFree(t *testing.T) {
|
||||
for _, cidr := range []string{"10.251.0.0/24", "2001:db8:251::/64"} {
|
||||
t.Run(cidr, func(t *testing.T) {
|
||||
lo0 := routeThroughLo0(t, cidr)
|
||||
tn, _, _ := newRouteTestTun(t, 0, cidr)
|
||||
require.Equal(t, lo0, routeVia(t, cidr), "an existing route keeps its prefix")
|
||||
|
||||
routeCmd(t, "delete", cidr)
|
||||
assert.Eventually(t, func() bool { return routeVia(t, cidr) == tn.linkAddr.Load().Index }, 5*time.Second, 50*time.Millisecond)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The kernel deletes a route by prefix alone, so dropping an unsafe_route someone else holds must not delete theirs
|
||||
func TestTunReloadLeavesRouteItYielded(t *testing.T) {
|
||||
cidr := "10.251.1.0/24"
|
||||
lo0 := routeThroughLo0(t, cidr)
|
||||
_, c, _ := newRouteTestTun(t, 0, cidr)
|
||||
|
||||
res := c.ReloadConfigString("tun: {}\n")
|
||||
require.NoError(t, res.Err)
|
||||
assert.False(t, res.Failed)
|
||||
assert.Equal(t, lo0, routeVia(t, cidr))
|
||||
}
|
||||
|
||||
// configd takes a prefix by deleting the route holding it and adding its own. Ours goes back once theirs is removed
|
||||
func TestTunYieldsToARouteThatReplacesIt(t *testing.T) {
|
||||
cidr := "10.251.3.0/24"
|
||||
tn, _, _ := newRouteTestTun(t, 0, cidr)
|
||||
ours := tn.linkAddr.Load().Index
|
||||
require.Equal(t, ours, routeVia(t, cidr))
|
||||
|
||||
cleanupRoute(t, cidr)
|
||||
requireRouteOK(t, exec.Command("sh", "-c", "route -q -n delete -net "+cidr+" && route -q -n add -net "+cidr+" -interface lo0"))
|
||||
lo0, err := net.InterfaceByName("lo0")
|
||||
require.NoError(t, err)
|
||||
time.Sleep(2 * routeRetryDelay)
|
||||
require.Equal(t, lo0.Index, routeVia(t, cidr))
|
||||
|
||||
routeCmd(t, "delete", cidr)
|
||||
assert.Eventually(t, func() bool { return routeVia(t, cidr) == ours }, 5*time.Second, 50*time.Millisecond)
|
||||
}
|
||||
|
||||
// A route someone deleted, with nothing in its place, stays gone until a reload, so they can put their own there
|
||||
func TestTunLeavesRouteDeletedByHand(t *testing.T) {
|
||||
cidr := "10.251.4.0/24"
|
||||
tn, c, cfg := newRouteTestTun(t, 200*time.Millisecond, cidr)
|
||||
ours := tn.linkAddr.Load().Index
|
||||
require.Equal(t, ours, routeVia(t, cidr))
|
||||
|
||||
routeCmd(t, "delete", cidr)
|
||||
assert.Never(t, func() bool { return routeVia(t, cidr) != 0 }, 3*routeRetryDelay, 50*time.Millisecond)
|
||||
|
||||
// A reload with nothing changed is how to ask for it back
|
||||
res := c.ReloadConfigString(cfg)
|
||||
require.NoError(t, res.Err)
|
||||
assert.False(t, res.Failed)
|
||||
assert.Equal(t, ours, routeVia(t, cidr))
|
||||
}
|
||||
|
||||
// configd deleting ours and adding the lan's more than routeRetryDelay apart, or a sweep landing in between, looks like
|
||||
// a hand delete. Seeing the lan hold the prefix puts ours back in line, it goes back once theirs is removed
|
||||
func TestTunYieldsAfterLeavingARouteDeletedByHand(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
cidr string
|
||||
sweep time.Duration
|
||||
misfile func(t *testing.T, tn *tun, cidr string)
|
||||
}{
|
||||
// The table went quiet with nothing in its place. The minute sweep leaves noticing the lan's route to the watcher
|
||||
"settled": {"10.251.6.0/24", 0, func(t *testing.T, tn *tun, cidr string) {
|
||||
require.Eventually(t, func() bool { return routeStateOf(tn, cidr).kind == routeRemoved }, 5*time.Second, 50*time.Millisecond)
|
||||
}},
|
||||
// The sweep that caps a table that never settles
|
||||
"swept": {"10.251.7.0/24", 200 * time.Millisecond, func(t *testing.T, tn *tun, cidr string) {
|
||||
tn.reconcileRoutes()
|
||||
require.Equal(t, routeRemoved, routeStateOf(tn, cidr).kind)
|
||||
}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
tn, _, _ := newRouteTestTun(t, tc.sweep, tc.cidr)
|
||||
ours := tn.linkAddr.Load().Index
|
||||
require.Equal(t, ours, routeVia(t, tc.cidr))
|
||||
|
||||
routeCmd(t, "delete", tc.cidr)
|
||||
tc.misfile(t, tn, tc.cidr)
|
||||
|
||||
lo0 := routeThroughLo0(t, tc.cidr)
|
||||
require.Eventually(t, func() bool {
|
||||
s := routeStateOf(tn, tc.cidr)
|
||||
return s.kind == routeYielded && s.holder == lo0
|
||||
}, 5*time.Second, 50*time.Millisecond)
|
||||
|
||||
routeCmd(t, "delete", tc.cidr)
|
||||
assert.Eventually(t, func() bool { return routeVia(t, tc.cidr) == ours }, 5*time.Second, 50*time.Millisecond)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Changing our route to another interface hands it the prefix, ours goes back once theirs is removed rather than being
|
||||
// taken for a hand delete
|
||||
func TestTunYieldsToARouteChangedAway(t *testing.T) {
|
||||
for _, cidr := range []string{"10.251.8.0/24", "2001:db8:258::/64"} {
|
||||
t.Run(cidr, func(t *testing.T) {
|
||||
tn, _, _ := newRouteTestTun(t, 0, cidr)
|
||||
ours := tn.linkAddr.Load().Index
|
||||
require.Equal(t, ours, routeVia(t, cidr))
|
||||
|
||||
cleanupRoute(t, cidr)
|
||||
routeCmd(t, "change", cidr, "-interface", "lo0")
|
||||
lo0, err := net.InterfaceByName("lo0")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, lo0.Index, routeVia(t, cidr))
|
||||
require.Eventually(t, func() bool {
|
||||
s := routeStateOf(tn, cidr)
|
||||
return s.kind == routeYielded && s.holder == lo0.Index
|
||||
}, 5*time.Second, 50*time.Millisecond)
|
||||
|
||||
routeCmd(t, "delete", cidr)
|
||||
assert.Eventually(t, func() bool { return routeVia(t, cidr) == ours }, 5*time.Second, 50*time.Millisecond)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Detaching an interface deletes its routes without a routing socket message for each, like unplugging the dock whose
|
||||
// ethernet configd routed the lan through
|
||||
func TestTunAddsRouteWhenItsInterfaceDetaches(t *testing.T) {
|
||||
requireRoot(t)
|
||||
var feth string
|
||||
for i := 100; i < 200 && feth == ""; i++ {
|
||||
if _, err := net.InterfaceByName(fmt.Sprintf("feth%d", i)); err != nil {
|
||||
feth = fmt.Sprintf("feth%d", i)
|
||||
}
|
||||
}
|
||||
require.NotEmpty(t, feth)
|
||||
require.NoError(t, exec.Command("ifconfig", feth, "create").Run())
|
||||
t.Cleanup(func() { _ = exec.Command("ifconfig", feth, "destroy").Run() })
|
||||
require.NoError(t, exec.Command("ifconfig", feth, "inet", "198.51.100.5/24", "up").Run())
|
||||
|
||||
// Static and cloning with no gateway, like the lan routes configd installs. Named by the feth's address, macOS 27
|
||||
// refuses one named by the feth itself
|
||||
cidr := "10.251.2.0/24"
|
||||
routeCmd(t, "add", cidr, "-interface", "198.51.100.5")
|
||||
cleanupRoute(t, cidr)
|
||||
ifc, err := net.InterfaceByName(feth)
|
||||
require.NoError(t, err)
|
||||
|
||||
tn, _, _ := newRouteTestTun(t, 0, cidr)
|
||||
require.Equal(t, ifc.Index, routeVia(t, cidr))
|
||||
|
||||
// Losing the address first leaves the route, the reconcile finds it still held
|
||||
require.NoError(t, exec.Command("ifconfig", feth, "inet", "198.51.100.5", "-alias").Run())
|
||||
time.Sleep(2 * routeRetryDelay)
|
||||
require.Equal(t, ifc.Index, routeVia(t, cidr))
|
||||
|
||||
// Only RTM_IFINFO says the interface went, its route goes with no message of its own
|
||||
require.NoError(t, exec.Command("ifconfig", feth, "destroy").Run())
|
||||
assert.Eventually(t, func() bool { return routeVia(t, cidr) == tn.linkAddr.Load().Index }, 5*time.Second, 50*time.Millisecond)
|
||||
}
|
||||
|
||||
// The routing socket drops what doesn't fit its buffer without a word, the sweep finds what it missed
|
||||
func TestTunSweepAddsRouteTheWatcherMissed(t *testing.T) {
|
||||
cidr := "10.251.5.0/24"
|
||||
routeThroughLo0(t, cidr)
|
||||
tn, _, _ := newRouteTestTun(t, 200*time.Millisecond, cidr)
|
||||
|
||||
tn.routesMu.Lock()
|
||||
require.NoError(t, tn.routeWatch.Close())
|
||||
tn.routesMu.Unlock()
|
||||
|
||||
routeCmd(t, "delete", cidr)
|
||||
assert.Eventually(t, func() bool { return routeVia(t, cidr) == tn.linkAddr.Load().Index }, 5*time.Second, 50*time.Millisecond)
|
||||
}
|
||||
|
||||
// Only naming a different utun asks for a restart. Empty, plain utun and names that aren't utunN take whichever is free
|
||||
func TestTunDevNeedsRestart(t *testing.T) {
|
||||
for name, want := range map[string]bool{
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//go:build !ios && !e2e_testing
|
||||
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTun_WriteFraming(t *testing.T) {
|
||||
r, w, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
defer r.Close()
|
||||
defer w.Close()
|
||||
tn := &tun{f: w}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
pkt []byte
|
||||
af byte
|
||||
}{
|
||||
// Literal families rather than syscall.AF_*, so a wrong constant in Write can't also fix the expectation.
|
||||
{"ipv4", []byte{0x45, 1, 2, 3, 4, 5}, 2},
|
||||
{"ipv6", []byte{0x60, 1, 2, 3, 4, 5}, 30},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
n, err := tn.Write(tc.pkt)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(tc.pkt), n)
|
||||
|
||||
got := make([]byte, 64)
|
||||
n, err = r.Read(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, append([]byte{0, 0, 0, tc.af}, tc.pkt...), got[:n])
|
||||
})
|
||||
}
|
||||
|
||||
_, err = tn.Write([]byte{0x10, 1, 2, 3})
|
||||
require.Error(t, err)
|
||||
_, err = tn.Write([]byte{})
|
||||
require.ErrorIs(t, err, syscall.EIO)
|
||||
|
||||
// The rejected writes must not have put anything on the fd, so the next read sees only this packet.
|
||||
pkt := []byte{0x45, 9, 9}
|
||||
_, err = tn.Write(pkt)
|
||||
require.NoError(t, err)
|
||||
got := make([]byte, 64)
|
||||
n, err := r.Read(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, append([]byte{0, 0, 0, 2}, pkt...), got[:n])
|
||||
}
|
||||
|
||||
func TestTun_ReadStripsHeader(t *testing.T) {
|
||||
r, w, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
defer r.Close()
|
||||
defer w.Close()
|
||||
tn := &tun{f: r}
|
||||
|
||||
pkt := []byte{0x45, 1, 2, 3, 4, 5}
|
||||
_, err = w.Write(append([]byte{0, 0, 0, syscall.AF_INET}, pkt...))
|
||||
require.NoError(t, err)
|
||||
|
||||
got := make([]byte, 64)
|
||||
n, err := tn.Read(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, pkt, got[:n])
|
||||
}
|
||||
|
||||
func TestTun_ReadShort(t *testing.T) {
|
||||
r, w, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
defer r.Close()
|
||||
defer w.Close()
|
||||
tn := &tun{f: r}
|
||||
|
||||
// Fewer bytes than the protocol header is not a packet.
|
||||
_, err = w.Write([]byte{0, 0})
|
||||
require.NoError(t, err)
|
||||
n, err := tn.Read(make([]byte, 64))
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, n)
|
||||
|
||||
// The next packet reads cleanly only if the short read consumed exactly what was written.
|
||||
pkt := []byte{0x45, 1, 2, 3}
|
||||
_, err = w.Write(append([]byte{0, 0, 0, syscall.AF_INET}, pkt...))
|
||||
require.NoError(t, err)
|
||||
got := make([]byte, 64)
|
||||
n, err = tn.Read(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, pkt, got[:n])
|
||||
}
|
||||
|
||||
// A heap allocation per packet rarely shows in a short throughput run, only across GC pauses, so
|
||||
// this pins Read and Write to zero allocations directly.
|
||||
func TestTun_ReadWriteDoNotAllocate(t *testing.T) {
|
||||
r, w, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
defer r.Close()
|
||||
defer w.Close()
|
||||
tw := &tun{f: w}
|
||||
tr := &tun{f: r}
|
||||
|
||||
pkts := [][]byte{bytes.Repeat([]byte{0x45}, 1300), bytes.Repeat([]byte{0x60}, 1300)}
|
||||
buf := make([]byte, 1500)
|
||||
i := 0
|
||||
allocs := testing.AllocsPerRun(1000, func() {
|
||||
i++
|
||||
if _, err := tw.Write(pkts[i%len(pkts)]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tr.Read(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
require.Zero(t, allocs)
|
||||
}
|
||||
@@ -832,6 +832,11 @@ func (t *tun) updateRoutes(r netlink.RouteUpdate) {
|
||||
t.routeTree.Store(newTree)
|
||||
}
|
||||
|
||||
// Shutdown wakes the tun readers without releasing their fds, Close releases them
|
||||
func (t *tun) Shutdown() error {
|
||||
return t.readers.Shutdown()
|
||||
}
|
||||
|
||||
func (t *tun) Close() error {
|
||||
t.closeLock.Lock()
|
||||
defer t.closeLock.Unlock()
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
//go:build !ios && !e2e_testing
|
||||
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/util"
|
||||
netroute "golang.org/x/net/route"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// Darwin has no route metrics, the routing table holds one unscoped route per prefix. When another interface already
|
||||
// routes an unsafe_route's prefix, like the lan we started on, theirs stays and ours is added once theirs is removed.
|
||||
// Our own route removed by someone else, with nothing in its place, was removed on purpose and stays gone until a reload
|
||||
// or until another interface takes the prefix, after which ours follows theirs like any other.
|
||||
|
||||
const (
|
||||
// routeRetryDelay is how long the system routing table must be quiet before we judge who holds a prefix. configd
|
||||
// replaces a route by deleting and adding, looking in between would find the prefix free
|
||||
routeRetryDelay = time.Second
|
||||
|
||||
// routeSweepInterval bounds how long a freed unsafe_route can go unnoticed. The routing socket drops messages that
|
||||
// don't fit its receive buffer without telling the reader, and detaching an interface deletes its routes without
|
||||
// a message for each
|
||||
routeSweepInterval = time.Minute
|
||||
|
||||
// routeSocketRcvBuf is well past the 8KiB default, which a burst of neighbor routes expiring can fill
|
||||
routeSocketRcvBuf = 1 << 20
|
||||
)
|
||||
|
||||
type routeStateKind int
|
||||
|
||||
const (
|
||||
routeUnknown routeStateKind = iota
|
||||
// routeInstalled is our route holding the prefix
|
||||
routeInstalled
|
||||
// routeYielded is another interface holding the prefix, ours is added once it lets go
|
||||
routeYielded
|
||||
// routeRemoved is our route deleted by someone else with nothing in its place, it is left alone until a reload or
|
||||
// another interface takes the prefix
|
||||
routeRemoved
|
||||
// routeFailed is adding our route failing for some other reason, it is retried
|
||||
routeFailed
|
||||
)
|
||||
|
||||
type routeState struct {
|
||||
kind routeStateKind
|
||||
// holder is the index of the interface holding the prefix when kind is routeYielded
|
||||
holder int
|
||||
}
|
||||
|
||||
// routeMover is the process that last added, changed or deleted a route for an unsafe_route's prefix, for logs. Its name
|
||||
// is looked up as the message arrives, route(8) has exited by the time the table settles
|
||||
type routeMover struct {
|
||||
pid int32
|
||||
name string
|
||||
}
|
||||
|
||||
// logArgs appends m to a log line's args, when we know who it was
|
||||
func (m routeMover) logArgs(args ...any) []any {
|
||||
if m.pid == 0 {
|
||||
return args
|
||||
}
|
||||
args = append(args, "pid", m.pid)
|
||||
if m.name != "" {
|
||||
args = append(args, "process", m.name)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// processName is the name of process pid, truncated to 16 bytes, or empty when it has already exited
|
||||
func processName(pid int32) string {
|
||||
kp, err := unix.SysctlKinfoProc("kern.proc.pid", int(pid))
|
||||
if err != nil || kp.Proc.P_pid != pid {
|
||||
return ""
|
||||
}
|
||||
return unix.ByteSliceToString(kp.Proc.P_comm[:])
|
||||
}
|
||||
|
||||
// installRoutes returns the routes we put in the system routing table, one per prefix
|
||||
func installRoutes(routes []Route) []Route {
|
||||
seen := make(map[netip.Prefix]struct{}, len(routes))
|
||||
var out []Route
|
||||
for _, r := range routes {
|
||||
if len(r.Via) == 0 || !r.Install {
|
||||
// We don't allow route MTUs so only install routes with a via
|
||||
continue
|
||||
}
|
||||
p := r.Cidr.Masked()
|
||||
if _, ok := seen[p]; ok {
|
||||
continue
|
||||
}
|
||||
seen[p] = struct{}{}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// addRoutes puts every unsafe_route in the system routing table, including ones someone deleted, unless another
|
||||
// interface holds its prefix. It runs on start and on every reload.
|
||||
func (t *tun) addRoutes(logErrors bool, rl *config.Reload) error {
|
||||
// The route tree is still ours, the system routing table is not
|
||||
if t.hostOwned {
|
||||
return nil
|
||||
}
|
||||
|
||||
t.routesMu.Lock()
|
||||
defer t.routesMu.Unlock()
|
||||
|
||||
// Activate hasn't run yet, it will install the routes
|
||||
linkAddr := t.linkAddr.Load()
|
||||
if linkAddr == nil || t.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
var msgs []netroute.Message
|
||||
var msgsErr error
|
||||
fetched := false
|
||||
states := make(map[netip.Prefix]routeState)
|
||||
for _, r := range installRoutes(*t.Routes.Load()) {
|
||||
p := r.Cidr.Masked()
|
||||
prev := t.routeStates[p]
|
||||
|
||||
err := addRoute(p, linkAddr)
|
||||
if err == nil {
|
||||
t.l.Info("Added route", "route", r)
|
||||
states[p] = routeState{kind: routeInstalled}
|
||||
continue
|
||||
}
|
||||
|
||||
if !errors.Is(err, unix.EEXIST) {
|
||||
retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
|
||||
if !logErrors {
|
||||
return retErr
|
||||
}
|
||||
retErr.Log(t.l)
|
||||
rl.Failed()
|
||||
states[p] = routeState{kind: routeFailed}
|
||||
continue
|
||||
}
|
||||
|
||||
// Every route we added already exists on a reload, only warn about someone else's
|
||||
if !fetched {
|
||||
msgs, msgsErr = fetchRoutes()
|
||||
fetched = true
|
||||
}
|
||||
if msgsErr != nil {
|
||||
t.l.Warn("unable to add unsafe_route, a route already exists but its interface could not be determined", "route", r.Cidr, "error", msgsErr)
|
||||
states[p] = prev
|
||||
continue
|
||||
}
|
||||
|
||||
switch holder := routeInterfaceIn(msgs, p); holder {
|
||||
case linkAddr.Index:
|
||||
states[p] = routeState{kind: routeInstalled}
|
||||
case 0:
|
||||
// Removed since the add, the watcher will see to it
|
||||
states[p] = prev
|
||||
default:
|
||||
if prev.kind != routeYielded || prev.holder != holder {
|
||||
t.l.Warn("unable to add unsafe_route, the destination is already routed through another interface, it will be added once that route is removed", "route", r.Cidr, "interface", interfaceName(holder))
|
||||
}
|
||||
states[p] = routeState{kind: routeYielded, holder: holder}
|
||||
}
|
||||
}
|
||||
|
||||
t.routeStates = states
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *tun) removeRoutes(routes []Route, rl *config.Reload) error {
|
||||
if t.hostOwned {
|
||||
return nil
|
||||
}
|
||||
|
||||
t.routesMu.Lock()
|
||||
defer t.routesMu.Unlock()
|
||||
|
||||
linkAddr := t.linkAddr.Load()
|
||||
if linkAddr == nil || t.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The kernel deletes a route by its prefix alone, whichever interface holds it. Only delete the ones that are ours
|
||||
msgs, err := fetchRoutes()
|
||||
if err != nil {
|
||||
var left []netip.Prefix
|
||||
for _, r := range installRoutes(routes) {
|
||||
left = append(left, r.Cidr)
|
||||
}
|
||||
return fmt.Errorf("failed to read the system routing table, leaving routes %v installed: %w", left, err)
|
||||
}
|
||||
|
||||
for _, r := range installRoutes(routes) {
|
||||
p := r.Cidr.Masked()
|
||||
// Whatever happens next, the prefix is no longer one we know about
|
||||
delete(t.routeStates, p)
|
||||
if routeInterfaceIn(msgs, p) != linkAddr.Index {
|
||||
continue
|
||||
}
|
||||
|
||||
err = delRoute(p, linkAddr)
|
||||
if errors.Is(err, unix.ESRCH) {
|
||||
// Already gone, which is what we wanted
|
||||
t.l.Info("Route was already removed", "route", r)
|
||||
} else if err != nil {
|
||||
t.l.Error("Failed to remove route", "error", err, "route", r)
|
||||
rl.Failed()
|
||||
} else {
|
||||
t.l.Info("Removed route", "route", r)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconcileRoutes brings the unsafe_routes in line with who holds their prefix now. It is quiet unless something
|
||||
// changed since it last looked, it runs every routeSweepEvery.
|
||||
func (t *tun) reconcileRoutes() {
|
||||
t.routesMu.Lock()
|
||||
defer t.routesMu.Unlock()
|
||||
|
||||
linkAddr := t.linkAddr.Load()
|
||||
if linkAddr == nil || t.closed {
|
||||
return
|
||||
}
|
||||
|
||||
t.routeMoversMu.Lock()
|
||||
movers := t.routeMovers
|
||||
t.routeMovers = nil
|
||||
t.routeMoversMu.Unlock()
|
||||
|
||||
msgs, err := fetchRoutes()
|
||||
if err != nil {
|
||||
t.l.Error("Failed to read the system routing table", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
states := make(map[netip.Prefix]routeState)
|
||||
for _, r := range installRoutes(*t.Routes.Load()) {
|
||||
p := r.Cidr.Masked()
|
||||
prev := t.routeStates[p]
|
||||
by := movers[p]
|
||||
|
||||
holder := routeInterfaceIn(msgs, p)
|
||||
switch {
|
||||
case holder == linkAddr.Index:
|
||||
states[p] = routeState{kind: routeInstalled}
|
||||
|
||||
case holder != 0:
|
||||
// Another interface taking a prefix we left alone puts ours back in line behind theirs
|
||||
if prev.kind != routeYielded || prev.holder != holder {
|
||||
t.l.Info("unsafe_route is routed through another interface, it will be added back when that route is removed", by.logArgs("route", r.Cidr, "interface", interfaceName(holder))...)
|
||||
}
|
||||
states[p] = routeState{kind: routeYielded, holder: holder}
|
||||
|
||||
case prev.kind == routeInstalled:
|
||||
t.l.Warn("unsafe_route was removed outside nebula, leaving it until a reload or another interface takes its destination", by.logArgs("route", r.Cidr)...)
|
||||
states[p] = routeState{kind: routeRemoved}
|
||||
|
||||
case prev.kind == routeRemoved:
|
||||
states[p] = prev
|
||||
|
||||
default:
|
||||
err := addRoute(p, linkAddr)
|
||||
switch {
|
||||
case err == nil:
|
||||
if prev.kind == routeYielded {
|
||||
t.l.Info("unsafe_route's destination is free again, added it", by.logArgs("route", r)...)
|
||||
} else {
|
||||
t.l.Info("Added route", "route", r)
|
||||
}
|
||||
states[p] = routeState{kind: routeInstalled}
|
||||
case errors.Is(err, unix.EEXIST):
|
||||
// Taken since the fetch, the next look will see by whom
|
||||
states[p] = prev
|
||||
default:
|
||||
if prev.kind != routeFailed {
|
||||
util.NewContextualError("Failed to add route", map[string]any{"route": r}, err).Log(t.l)
|
||||
}
|
||||
states[p] = routeState{kind: routeFailed}
|
||||
}
|
||||
}
|
||||
}
|
||||
t.routeStates = states
|
||||
}
|
||||
|
||||
// startRouteWatch starts reconciling the unsafe_routes, every routeSweepEvery and, when watch isn't nil, once the
|
||||
// routing table settles after anything that may have moved a prefix
|
||||
func (t *tun) startRouteWatch(watch *os.File) {
|
||||
t.routesMu.Lock()
|
||||
defer t.routesMu.Unlock()
|
||||
if t.closed {
|
||||
if watch != nil {
|
||||
_ = watch.Close()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
t.routeSweep = time.AfterFunc(t.routeSweepEvery, t.sweepRoutes)
|
||||
if watch != nil {
|
||||
t.routeWatch = watch
|
||||
go t.watchRoutes(watch)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tun) sweepRoutes() {
|
||||
// A table still changing gets reconciled once it settles
|
||||
if time.Since(time.Unix(0, t.lastRouteEvent.Load())) >= routeRetryDelay {
|
||||
t.reconcileRoutes()
|
||||
}
|
||||
|
||||
t.routesMu.Lock()
|
||||
defer t.routesMu.Unlock()
|
||||
if !t.closed {
|
||||
t.routeSweep.Reset(t.routeSweepEvery)
|
||||
}
|
||||
}
|
||||
|
||||
func openRouteSocket() (*os.File, error) {
|
||||
fd, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to create AF_ROUTE socket: %w", err)
|
||||
}
|
||||
// Fewer drops, the sweep catches the rest
|
||||
_ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF, routeSocketRcvBuf)
|
||||
// Non-blocking puts it on the poller, so Close interrupts a Read
|
||||
if err = unix.SetNonblock(fd, true); err != nil {
|
||||
_ = unix.Close(fd)
|
||||
return nil, fmt.Errorf("failed to set the AF_ROUTE socket to non-blocking mode: %w", err)
|
||||
}
|
||||
return os.NewFile(uintptr(fd), "route"), nil
|
||||
}
|
||||
|
||||
// watchRoutes reconciles the unsafe_routes once the routing table has been quiet for routeRetryDelay after a message
|
||||
// that may have moved a prefix. A table that keeps changing is reconciled every routeSweepEvery regardless.
|
||||
func (t *tun) watchRoutes(f *os.File) {
|
||||
var reconciled atomic.Int64
|
||||
settle := time.AfterFunc(time.Hour, func() {
|
||||
reconciled.Store(time.Now().UnixNano())
|
||||
t.reconcileRoutes()
|
||||
})
|
||||
settle.Stop()
|
||||
defer settle.Stop()
|
||||
|
||||
var burst time.Time
|
||||
self := int32(os.Getpid())
|
||||
b := make([]byte, os.Getpagesize())
|
||||
for {
|
||||
n, err := f.Read(b)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrClosed) {
|
||||
t.l.Error("Stopped watching the system routing table, unsafe_routes held by another interface are only retried every minute", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
moved, p, pid := routesMayHaveMoved(b[:n], *t.Routes.Load())
|
||||
if !moved {
|
||||
continue
|
||||
}
|
||||
// Our own are already in routeStates
|
||||
if p.IsValid() && pid != self {
|
||||
t.routeMoversMu.Lock()
|
||||
if t.routeMovers == nil {
|
||||
t.routeMovers = make(map[netip.Prefix]routeMover)
|
||||
}
|
||||
t.routeMovers[p] = routeMover{pid: pid, name: processName(pid)}
|
||||
t.routeMoversMu.Unlock()
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
t.lastRouteEvent.Store(now.UnixNano())
|
||||
if burst.IsZero() || reconciled.Load() >= burst.UnixNano() {
|
||||
burst = now
|
||||
}
|
||||
settle.Reset(max(0, min(routeRetryDelay, time.Until(burst.Add(t.routeSweepEvery)))))
|
||||
}
|
||||
}
|
||||
|
||||
// routesMayHaveMoved reports whether b, one routing socket message, may have freed a prefix one of routes installs or
|
||||
// handed it to another interface. That's a route for it added, changed or removed, or an interface that lost an address
|
||||
// or changed state, since detaching an interface deletes its routes without a message of their own. The header is read
|
||||
// directly, x/net/route skips the RTM_IFINFO the socket sends, which has no interface address, and misreads the
|
||||
// unpadded sockaddrs in messages the kernel makes itself. A request naming one of the prefixes also returns that prefix
|
||||
// and the pid of the process that made it.
|
||||
func routesMayHaveMoved(b []byte, routes []Route) (moved bool, p netip.Prefix, pid int32) {
|
||||
if len(b) < 4 {
|
||||
return false, p, 0
|
||||
}
|
||||
switch int(b[3]) {
|
||||
case unix.RTM_IFINFO, unix.RTM_DELADDR:
|
||||
return true, p, 0
|
||||
case unix.RTM_ADD, unix.RTM_CHANGE, unix.RTM_DELETE:
|
||||
default:
|
||||
return false, p, 0
|
||||
}
|
||||
|
||||
if len(b) < unix.SizeofRtMsghdr {
|
||||
return false, p, 0
|
||||
}
|
||||
hdr := (*unix.RtMsghdr)(unsafe.Pointer(&b[0]))
|
||||
// A failed request is reported too, and a scoped route never held the prefix
|
||||
if hdr.Errno != 0 || hdr.Flags&unix.RTF_IFSCOPE != 0 {
|
||||
return false, p, 0
|
||||
}
|
||||
|
||||
if hdr.Pid == 0 {
|
||||
// The kernel's own, which x/net/route can't parse. Neighbors coming and going are host routes, anything else
|
||||
// could be holding a prefix
|
||||
return hdr.Flags&(unix.RTF_HOST|unix.RTF_LLINFO) == 0, p, 0
|
||||
}
|
||||
|
||||
// Replies to a request carry the requester's padded sockaddrs
|
||||
msgs, err := netroute.ParseRIB(unix.NET_RT_DUMP, b)
|
||||
if err != nil || len(msgs) != 1 {
|
||||
return false, p, 0
|
||||
}
|
||||
m, ok := msgs[0].(*netroute.RouteMessage)
|
||||
if !ok || len(m.Addrs) <= unix.RTAX_NETMASK {
|
||||
return false, p, 0
|
||||
}
|
||||
p, ok = routePrefix(m.Addrs[unix.RTAX_DST], m.Addrs[unix.RTAX_NETMASK])
|
||||
if !ok {
|
||||
return false, netip.Prefix{}, 0
|
||||
}
|
||||
p = p.Masked()
|
||||
for _, r := range installRoutes(routes) {
|
||||
if r.Cidr.Masked() == p {
|
||||
return true, p, hdr.Pid
|
||||
}
|
||||
}
|
||||
return false, netip.Prefix{}, 0
|
||||
}
|
||||
|
||||
// interfaceName is the name of the interface with index i, for logs
|
||||
func interfaceName(i int) string {
|
||||
if ifc, err := net.InterfaceByIndex(i); err == nil {
|
||||
return ifc.Name
|
||||
}
|
||||
return strconv.Itoa(i)
|
||||
}
|
||||
@@ -528,6 +528,10 @@ func (rm *relayManager) handleCreateRelayRequest(v cert.Version, h *HostInfo, f
|
||||
if !rm.GetAmRelay() {
|
||||
return
|
||||
}
|
||||
if !slices.Contains(h.vpnAddrs, from) {
|
||||
logMsg.Info("Discarding relay request where relayFrom is not the sending peer")
|
||||
return
|
||||
}
|
||||
peer := rm.hostmap.QueryVpnAddr(target)
|
||||
if peer == nil {
|
||||
// Try to establish a connection to this host. If we get a future relay request,
|
||||
|
||||
@@ -7,8 +7,10 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gaissmai/bart"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestStartRelaysLogDedupe verifies that repeated attempts with the same relay set drop the log
|
||||
@@ -95,3 +97,58 @@ func TestStartRelaysLogDedupe(t *testing.T) {
|
||||
assert.NotContains(t, buf.String(), msg, "should not log when we shortcut out")
|
||||
})
|
||||
}
|
||||
|
||||
// TestHandleCreateRelayRequestRejectsSpoofedFrom verifies that a relay only forwards a CreateRelayRequest
|
||||
// when relayFrom is the peer that sent it. Otherwise any peer could reset another host's established
|
||||
// relay back to Requested, or allocate unbounded relay entries on the target's hostinfo.
|
||||
func TestHandleCreateRelayRequestRejectsSpoofedFrom(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
relayAddr := netip.MustParseAddr("10.128.0.128")
|
||||
malloryAddr := netip.MustParseAddr("10.128.0.3")
|
||||
victimAddr := netip.MustParseAddr("10.128.0.1")
|
||||
targetAddr := netip.MustParseAddr("10.128.0.2")
|
||||
|
||||
addrTable := new(bart.Lite)
|
||||
addrTable.Insert(netip.PrefixFrom(relayAddr, relayAddr.BitLen()))
|
||||
hm := newHostMap(l)
|
||||
f := &Interface{myVpnAddrsTable: addrTable, hostMap: hm}
|
||||
rm := &relayManager{l: l, hostmap: hm}
|
||||
rm.amRelay.Store(true)
|
||||
|
||||
newRelayState := func() RelayState {
|
||||
return RelayState{relayForByAddr: map[netip.Addr]*Relay{}, relayForByIdx: map[uint32]*Relay{}}
|
||||
}
|
||||
mallory := &HostInfo{vpnAddrs: []netip.Addr{malloryAddr}, localIndexId: 1, relayState: newRelayState()}
|
||||
target := &HostInfo{
|
||||
vpnAddrs: []netip.Addr{targetAddr},
|
||||
localIndexId: 2,
|
||||
remotes: NewRemoteList([]netip.Addr{targetAddr}, nil),
|
||||
relayState: newRelayState(),
|
||||
}
|
||||
target.SetRemote(netip.MustParseAddrPort("192.0.2.2:4242"))
|
||||
hm.unlockedAddHostInfo(mallory, f)
|
||||
hm.unlockedAddHostInfo(target, f)
|
||||
|
||||
// The victim already has a working relay to the target through us.
|
||||
_, err := AddRelay(l, target, hm, victimAddr, nil, ForwardingType, Established)
|
||||
require.NoError(t, err)
|
||||
relaysBefore := len(hm.Relays)
|
||||
|
||||
for i := range 10 {
|
||||
spoofed := netip.AddrFrom4([4]byte{10, 128, 1, byte(i)})
|
||||
for _, from := range []netip.Addr{victimAddr, spoofed} {
|
||||
rm.handleCreateRelayRequest(cert.Version2, mallory, f, &NebulaControl{
|
||||
Type: NebulaControl_CreateRelayRequest,
|
||||
InitiatorRelayIndex: uint32(100 + i),
|
||||
RelayFromAddr: netAddrToProtoAddr(from),
|
||||
RelayToAddr: netAddrToProtoAddr(targetAddr),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
r, ok := target.relayState.QueryRelayForByIp(victimAddr)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, Established, r.State, "victim's relay must not be reset by a request from another peer")
|
||||
assert.Len(t, hm.Relays, relaysBefore, "spoofed requests must not allocate relay entries")
|
||||
assert.Empty(t, mallory.relayState.CopyAllRelayFor(), "spoofed requests must not create state on the sender")
|
||||
}
|
||||
+12
-4
@@ -460,10 +460,14 @@ func (r *RemoteList) unlockedSetV4(ownerVpnIp, vpnIp netip.Addr, to []*V4AddrPor
|
||||
// Reset the slice
|
||||
c.reported = c.reported[:0]
|
||||
|
||||
// We can't take their array but we can take their pointers
|
||||
for _, v := range to[:minInt(len(to), MaxRemotes)] {
|
||||
// We can't take their array but we can take their pointers.
|
||||
// Filter before capping so denied addrs do not crowd out allowed ones reported later in the list.
|
||||
for _, v := range to {
|
||||
if check(vpnIp, v) {
|
||||
c.reported = append(c.reported, v)
|
||||
if len(c.reported) == MaxRemotes {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -508,10 +512,14 @@ func (r *RemoteList) unlockedSetV6(ownerVpnIp, vpnIp netip.Addr, to []*V6AddrPor
|
||||
// Reset the slice
|
||||
c.reported = c.reported[:0]
|
||||
|
||||
// We can't take their array but we can take their pointers
|
||||
for _, v := range to[:minInt(len(to), MaxRemotes)] {
|
||||
// We can't take their array but we can take their pointers.
|
||||
// Filter before capping so denied addrs do not crowd out allowed ones reported later in the list.
|
||||
for _, v := range to {
|
||||
if check(vpnIp, v) {
|
||||
c.reported = append(c.reported, v)
|
||||
if len(c.reported) == MaxRemotes {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package nebula
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
@@ -346,3 +347,38 @@ func newIp6AndPortFromString(s string) *V6AddrPort {
|
||||
Port: uint32(a.Port()),
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteList_SetFiltersBeforeCap(t *testing.T) {
|
||||
owner := netip.MustParseAddr("0.0.0.0")
|
||||
rl := NewRemoteList([]netip.Addr{owner}, nil)
|
||||
|
||||
// MaxRemotes denied addrs first, then the only allowed one, then enough allowed to exceed the cap
|
||||
var v4 []*V4AddrPort
|
||||
for i := 0; i < MaxRemotes; i++ {
|
||||
v4 = append(v4, newIp4AndPortFromString(fmt.Sprintf("172.17.0.%d:4242", i+1)))
|
||||
}
|
||||
for i := 0; i < MaxRemotes+1; i++ {
|
||||
v4 = append(v4, newIp4AndPortFromString(fmt.Sprintf("70.199.182.%d:4242", i+1)))
|
||||
}
|
||||
rl.unlockedSetV4(owner, owner, v4, func(_ netip.Addr, a *V4AddrPort) bool {
|
||||
return protoV4AddrPortToNetAddrPort(a).Addr().As4()[0] != 172
|
||||
})
|
||||
|
||||
var v6 []*V6AddrPort
|
||||
for i := 0; i < MaxRemotes; i++ {
|
||||
v6 = append(v6, newIp6AndPortFromString(fmt.Sprintf("[fd00::%d]:4242", i+1)))
|
||||
}
|
||||
for i := 0; i < MaxRemotes+1; i++ {
|
||||
v6 = append(v6, newIp6AndPortFromString(fmt.Sprintf("[2001:db8::%d]:4242", i+1)))
|
||||
}
|
||||
rl.unlockedSetV6(owner, owner, v6, func(_ netip.Addr, a *V6AddrPort) bool {
|
||||
return protoV6AddrPortToNetAddrPort(a).Addr().As16()[0] != 0xfd
|
||||
})
|
||||
|
||||
rl.Rebuild([]netip.Prefix{})
|
||||
assert.Len(t, rl.addrs, MaxRemotes*2)
|
||||
for _, a := range rl.addrs {
|
||||
assert.NotEqual(t, byte(172), a.Addr().As16()[12], "denied v4 addr %v was kept", a)
|
||||
assert.NotEqual(t, byte(0xfd), a.Addr().As16()[0], "denied v6 addr %v was kept", a)
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -36,11 +36,13 @@ func (l *tcpListener) Accept() (net.Conn, error) {
|
||||
|
||||
func (l *tcpListener) Close() error {
|
||||
l.closeOnce.Do(func() {
|
||||
// Close before leaving the map so a concurrent closeListeners that
|
||||
// no longer sees this listener knows Accept is already released.
|
||||
close(l.closed)
|
||||
|
||||
l.s.mu.Lock()
|
||||
delete(l.s.mu.listeners, l.port)
|
||||
l.s.mu.Unlock()
|
||||
|
||||
close(l.closed)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
+70
-7
@@ -32,13 +32,18 @@ import (
|
||||
const nicID = 1
|
||||
|
||||
type Service struct {
|
||||
eg *errgroup.Group
|
||||
control *nebula.Control
|
||||
ipstack *stack.Stack
|
||||
|
||||
// done is closed once the forwarding goroutines have exited and the
|
||||
// netstack is torn down, at which point err holds the first fatal error.
|
||||
done chan struct{}
|
||||
err error
|
||||
|
||||
mu struct {
|
||||
sync.Mutex
|
||||
|
||||
closed bool
|
||||
listeners map[uint16]*tcpListener
|
||||
}
|
||||
}
|
||||
@@ -65,7 +70,6 @@ func New(control *nebula.Control) (_ *Service, reterr error) {
|
||||
ctx := control.Context()
|
||||
eg, ctx := errgroup.WithContext(ctx)
|
||||
s := Service{
|
||||
eg: eg,
|
||||
control: control,
|
||||
}
|
||||
s.mu.listeners = map[uint16]*tcpListener{}
|
||||
@@ -74,6 +78,12 @@ func New(control *nebula.Control) (_ *Service, reterr error) {
|
||||
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
|
||||
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
|
||||
})
|
||||
// The teardown goroutine only owns the stack once New succeeds
|
||||
defer func() {
|
||||
if reterr != nil {
|
||||
s.ipstack.Destroy()
|
||||
}
|
||||
}()
|
||||
sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default
|
||||
tcpipErr := s.ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt)
|
||||
if tcpipErr != nil {
|
||||
@@ -123,6 +133,12 @@ func New(control *nebula.Control) (_ *Service, reterr error) {
|
||||
// this will read exactly one packet
|
||||
n, err := reader.Read(buf)
|
||||
if err != nil {
|
||||
// An error after shutdown began is noise from the device pipes
|
||||
// closing, anything else is fatal and must stop nebula too
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
s.control.Stop()
|
||||
return err
|
||||
}
|
||||
packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||
@@ -130,8 +146,8 @@ func New(control *nebula.Control) (_ *Service, reterr error) {
|
||||
})
|
||||
linkEP.InjectInbound(header.IPv4ProtocolNumber, packetBuf)
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -139,13 +155,18 @@ func New(control *nebula.Control) (_ *Service, reterr error) {
|
||||
for {
|
||||
packet := linkEP.ReadContext(ctx)
|
||||
if packet == nil {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
bufView := packet.ToView()
|
||||
if _, err := bufView.WriteTo(writer); err != nil {
|
||||
// Same shutdown noise handling as the inbound reader
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
s.control.Stop()
|
||||
return err
|
||||
}
|
||||
bufView.Release()
|
||||
@@ -158,6 +179,22 @@ func New(control *nebula.Control) (_ *Service, reterr error) {
|
||||
return control.Wait()
|
||||
})
|
||||
|
||||
// Tear down here rather than in Close so it also happens when nebula stops
|
||||
// on its own. The forwarding goroutines must exit before the stack they feed
|
||||
// is destroyed.
|
||||
s.done = make(chan struct{})
|
||||
go func() {
|
||||
s.err = eg.Wait()
|
||||
s.closeListeners()
|
||||
// Destroy aborts the endpoints that exist when it starts, then waits on
|
||||
// every endpoint, so a Dial registering in between would hold Wait until
|
||||
// its connect timed out. Without the NIC new dials fail route lookup.
|
||||
// RemoveNIC also closes linkEP.
|
||||
_ = s.ipstack.RemoveNIC(nicID)
|
||||
s.ipstack.Destroy()
|
||||
close(s.done)
|
||||
}()
|
||||
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
@@ -237,6 +274,9 @@ func (s *Service) Listen(network, address string) (net.Listener, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.mu.closed {
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
if _, ok := s.mu.listeners[port]; ok {
|
||||
return nil, fmt.Errorf("already listening on port %d", port)
|
||||
}
|
||||
@@ -245,15 +285,38 @@ func (s *Service) Listen(network, address string) (net.Listener, error) {
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Wait blocks until the service has fully stopped, either via Close or a fatal
|
||||
// error, and returns the first fatal error if there was one.
|
||||
func (s *Service) Wait() error {
|
||||
return s.eg.Wait()
|
||||
<-s.done
|
||||
return s.err
|
||||
}
|
||||
|
||||
// Close closes all listeners and stops nebula. Use Wait to block until
|
||||
// shutdown has completed.
|
||||
func (s *Service) Close() error {
|
||||
s.closeListeners()
|
||||
s.control.Stop()
|
||||
return nil
|
||||
}
|
||||
|
||||
// closeListeners unblocks pending Accept calls and rejects new listeners.
|
||||
func (s *Service) closeListeners() {
|
||||
// Every caller closes every listener rather than returning early once
|
||||
// closed is set, so none returns while another is still closing them.
|
||||
s.mu.Lock()
|
||||
s.mu.closed = true
|
||||
listeners := make([]*tcpListener, 0, len(s.mu.listeners))
|
||||
for _, l := range s.mu.listeners {
|
||||
listeners = append(listeners, l)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
for _, l := range listeners {
|
||||
_ = l.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) tcpHandler(r *tcp.ForwarderRequest) {
|
||||
endpointID := r.ID()
|
||||
|
||||
|
||||
@@ -327,3 +327,162 @@ func TestListenerAcceptAfterClose(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close must release blocked Accept calls and let Wait report a clean shutdown.
|
||||
func TestServiceClose(t *testing.T) {
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
a := newSimpleService(ca, caKey, "a", netip.MustParseAddr("10.0.0.1"), m{
|
||||
"static_host_map": m{},
|
||||
"listen": m{
|
||||
"host": "127.0.0.1",
|
||||
"port": 0,
|
||||
},
|
||||
})
|
||||
|
||||
ln, err := a.Listen("tcp", ":1234")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accepted := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := ln.Accept()
|
||||
accepted <- err
|
||||
}()
|
||||
|
||||
if err := a.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-accepted:
|
||||
if !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("expected net.ErrClosed from Accept, got %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Accept still blocked after Close")
|
||||
}
|
||||
|
||||
waited := make(chan error, 1)
|
||||
go func() { waited <- a.Wait() }()
|
||||
select {
|
||||
case err := <-waited:
|
||||
if err != nil {
|
||||
t.Fatalf("expected clean shutdown from Wait, got %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Wait still blocked after Close")
|
||||
}
|
||||
|
||||
if a.ipstack.HasNIC(nicID) {
|
||||
t.Fatal("netstack not torn down after Wait")
|
||||
}
|
||||
if err := a.Close(); err != nil {
|
||||
t.Fatalf("second close: %v", err)
|
||||
}
|
||||
if _, err := a.Listen("tcp", ":1235"); !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("expected net.ErrClosed from Listen after Close, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// If nebula stops without Close being called, the service must still release
|
||||
// Accept and tear down the netstack.
|
||||
func TestServiceNebulaStopped(t *testing.T) {
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
a := newSimpleService(ca, caKey, "a", netip.MustParseAddr("10.0.0.1"), m{
|
||||
"static_host_map": m{},
|
||||
"listen": m{
|
||||
"host": "127.0.0.1",
|
||||
"port": 0,
|
||||
},
|
||||
})
|
||||
|
||||
ln, err := a.Listen("tcp", ":1234")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accepted := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := ln.Accept()
|
||||
accepted <- err
|
||||
}()
|
||||
|
||||
a.control.Stop()
|
||||
|
||||
waited := make(chan error, 1)
|
||||
go func() { waited <- a.Wait() }()
|
||||
select {
|
||||
case err := <-waited:
|
||||
if err != nil {
|
||||
t.Fatalf("expected clean shutdown from Wait, got %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Wait still blocked after nebula stopped")
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-accepted:
|
||||
if !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("expected net.ErrClosed from Accept, got %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Accept still blocked after nebula stopped")
|
||||
}
|
||||
|
||||
if a.ipstack.HasNIC(nicID) {
|
||||
t.Fatal("netstack not torn down after Wait")
|
||||
}
|
||||
}
|
||||
|
||||
// Dials racing Close must not hold Wait until their connect times out.
|
||||
func TestServiceDialDuringClose(t *testing.T) {
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
a := newSimpleService(ca, caKey, "a", netip.MustParseAddr("10.0.0.1"), m{
|
||||
"static_host_map": m{},
|
||||
"listen": m{
|
||||
"host": "127.0.0.1",
|
||||
"port": 0,
|
||||
},
|
||||
})
|
||||
|
||||
stop := make(chan struct{})
|
||||
var eg errgroup.Group
|
||||
for range 8 {
|
||||
eg.Go(func() error {
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
// 10.0.0.2 has no tunnel, so each dial sits in SYN-SENT until aborted
|
||||
if c, err := a.Dial("tcp", "10.0.0.2:80"); err == nil {
|
||||
_ = c.Close()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
if err := a.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waited := make(chan error, 1)
|
||||
go func() { waited <- a.Wait() }()
|
||||
select {
|
||||
case err := <-waited:
|
||||
if err != nil {
|
||||
t.Fatalf("expected clean shutdown from Wait, got %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Wait blocked behind a dial that raced Close")
|
||||
}
|
||||
|
||||
close(stop)
|
||||
dialersDone := make(chan error, 1)
|
||||
go func() { dialersDone <- eg.Wait() }()
|
||||
select {
|
||||
case <-dialersDone:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Dial still blocked after Wait")
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,17 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/logging"
|
||||
"github.com/slackhq/nebula/sshd"
|
||||
)
|
||||
|
||||
type sshListHostMapFlags struct {
|
||||
Json bool
|
||||
Pretty bool
|
||||
ByIndex bool
|
||||
}
|
||||
|
||||
type sshPrintCertFlags struct {
|
||||
Json bool
|
||||
Pretty bool
|
||||
Raw bool
|
||||
}
|
||||
|
||||
type sshPrintTunnelFlags struct {
|
||||
Pretty bool
|
||||
}
|
||||
|
||||
type sshChangeRemoteFlags struct {
|
||||
Address string
|
||||
}
|
||||
|
||||
type sshCloseTunnelFlags struct {
|
||||
LocalOnly bool
|
||||
}
|
||||
|
||||
type sshCreateTunnelFlags struct {
|
||||
Address string
|
||||
}
|
||||
|
||||
type sshDeviceInfoFlags struct {
|
||||
Json bool
|
||||
Pretty bool
|
||||
}
|
||||
|
||||
func wireSSHReload(l *slog.Logger, ssh *sshd.SSHServer, c *config.C) {
|
||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||
if c.GetBool("sshd.enabled", false) {
|
||||
@@ -227,704 +185,3 @@ func configSSH(l *slog.Logger, ssh *sshd.SSHServer, c *config.C, r *config.Reloa
|
||||
|
||||
return runner, nil
|
||||
}
|
||||
|
||||
func attachCommands(l *slog.Logger, c *config.C, ssh *sshd.SSHServer, f *Interface) {
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "list-hostmap",
|
||||
ShortDescription: "List all known previously connected hosts",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshListHostMapFlags{}
|
||||
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||
fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshListHostMap(f.hostMap, fs, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "list-pending-hostmap",
|
||||
ShortDescription: "List all handshaking hosts",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshListHostMapFlags{}
|
||||
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||
fl.BoolVar(&s.ByIndex, "by-index", false, "gets all hosts in the hostmap from the index table")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshListHostMap(f.handshakeManager, fs, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "list-lighthouse-addrmap",
|
||||
ShortDescription: "List all lighthouse map entries",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshListHostMapFlags{}
|
||||
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshListLighthouseMap(f.lightHouse, fs, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "reload",
|
||||
ShortDescription: "Reloads configuration from disk, same as sending HUP to the process",
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshReload(l, c, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "log-level",
|
||||
ShortDescription: "Gets or sets the current log level",
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshLogLevel(l, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "log-format",
|
||||
ShortDescription: "Gets or sets the current log format",
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshLogFormat(l, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "version",
|
||||
ShortDescription: "Prints the currently running version of nebula",
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshVersion(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "device-info",
|
||||
ShortDescription: "Prints information about the network device.",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshDeviceInfoFlags{}
|
||||
fl.BoolVar(&s.Json, "json", false, "outputs as json with more information")
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshDeviceInfo(f, fs, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "print-cert",
|
||||
ShortDescription: "Prints the current certificate being used or the certificate for the provided vpn addr",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshPrintCertFlags{}
|
||||
fl.BoolVar(&s.Json, "json", false, "outputs as json")
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json, assumes -json")
|
||||
fl.BoolVar(&s.Raw, "raw", false, "raw prints the PEM encoded certificate, not compatible with -json or -pretty")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshPrintCert(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "print-tunnel",
|
||||
ShortDescription: "Prints json details about a tunnel for the provided vpn addr",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshPrintTunnelFlags{}
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshPrintTunnel(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "print-relays",
|
||||
ShortDescription: "Prints json details about all relay info",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshPrintTunnelFlags{}
|
||||
fl.BoolVar(&s.Pretty, "pretty", false, "pretty prints json")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshPrintRelays(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "change-remote",
|
||||
ShortDescription: "Changes the remote address used in the tunnel for the provided vpn addr",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshChangeRemoteFlags{}
|
||||
fl.StringVar(&s.Address, "address", "", "The new remote address, ip:port")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshChangeRemote(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "close-tunnel",
|
||||
ShortDescription: "Closes a tunnel for the provided vpn addr",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshCloseTunnelFlags{}
|
||||
fl.BoolVar(&s.LocalOnly, "local-only", false, "Disables notifying the remote that the tunnel is shutting down")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshCloseTunnel(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "create-tunnel",
|
||||
ShortDescription: "Creates a tunnel for the provided vpn address",
|
||||
Help: "The lighthouses will be queried for real addresses but you can provide one as well.",
|
||||
Flags: func() (*flag.FlagSet, any) {
|
||||
fl := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
s := sshCreateTunnelFlags{}
|
||||
fl.StringVar(&s.Address, "address", "", "Optionally provide a real remote address, ip:port ")
|
||||
return fl, &s
|
||||
},
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshCreateTunnel(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
|
||||
ssh.RegisterCommand(&sshd.Command{
|
||||
Name: "query-lighthouse",
|
||||
ShortDescription: "Query the lighthouses for the provided vpn address",
|
||||
Help: "This command is asynchronous. Only currently known udp addresses will be printed.",
|
||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
||||
return sshQueryLighthouse(f, fs, a, w)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func sshListHostMap(hl controlHostLister, a any, w sshd.StringWriter) error {
|
||||
fs, ok := a.(*sshListHostMapFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
var hm []ControlHostInfo
|
||||
if fs.ByIndex {
|
||||
hm = listHostMapIndexes(hl)
|
||||
} else {
|
||||
hm = listHostMapHosts(hl)
|
||||
}
|
||||
|
||||
sort.Slice(hm, func(i, j int) bool {
|
||||
return hm[i].VpnAddrs[0].Compare(hm[j].VpnAddrs[0]) < 0
|
||||
})
|
||||
|
||||
if fs.Json || fs.Pretty {
|
||||
js := json.NewEncoder(w.GetWriter())
|
||||
if fs.Pretty {
|
||||
js.SetIndent("", " ")
|
||||
}
|
||||
|
||||
err := js.Encode(hm)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
} else {
|
||||
for _, v := range hm {
|
||||
err := w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddrs, v.RemoteAddrs))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func sshListLighthouseMap(lightHouse *LightHouse, a any, w sshd.StringWriter) error {
|
||||
fs, ok := a.(*sshListHostMapFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
type lighthouseInfo struct {
|
||||
VpnAddr string `json:"vpnAddr"`
|
||||
Addrs *CacheMap `json:"addrs"`
|
||||
}
|
||||
|
||||
lightHouse.RLock()
|
||||
addrMap := make([]lighthouseInfo, len(lightHouse.addrMap))
|
||||
x := 0
|
||||
for k, v := range lightHouse.addrMap {
|
||||
addrMap[x] = lighthouseInfo{
|
||||
VpnAddr: k.String(),
|
||||
Addrs: v.CopyCache(),
|
||||
}
|
||||
x++
|
||||
}
|
||||
lightHouse.RUnlock()
|
||||
|
||||
sort.Slice(addrMap, func(i, j int) bool {
|
||||
return strings.Compare(addrMap[i].VpnAddr, addrMap[j].VpnAddr) < 0
|
||||
})
|
||||
|
||||
if fs.Json || fs.Pretty {
|
||||
js := json.NewEncoder(w.GetWriter())
|
||||
if fs.Pretty {
|
||||
js.SetIndent("", " ")
|
||||
}
|
||||
|
||||
err := js.Encode(addrMap)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
} else {
|
||||
for _, v := range addrMap {
|
||||
b, err := json.Marshal(v.Addrs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = w.WriteLine(fmt.Sprintf("%s: %s", v.VpnAddr, string(b)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func sshVersion(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
return w.WriteLine(fmt.Sprintf("%s", ifce.version))
|
||||
}
|
||||
|
||||
func sshQueryLighthouse(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine("No vpn address was provided")
|
||||
}
|
||||
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
if !vpnAddr.IsValid() {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
var cm *CacheMap
|
||||
rl := ifce.lightHouse.Query(vpnAddr)
|
||||
if rl != nil {
|
||||
cm = rl.CopyCache()
|
||||
}
|
||||
return json.NewEncoder(w.GetWriter()).Encode(cm)
|
||||
}
|
||||
|
||||
func sshCloseTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
flags, ok := fs.(*sshCloseTunnelFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine("No vpn address was provided")
|
||||
}
|
||||
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
if !vpnAddr.IsValid() {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo == nil {
|
||||
return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
|
||||
}
|
||||
|
||||
if !flags.LocalOnly {
|
||||
ifce.send(
|
||||
header.CloseTunnel,
|
||||
0,
|
||||
hostInfo.ConnectionState,
|
||||
hostInfo,
|
||||
[]byte{},
|
||||
make([]byte, 12, 12),
|
||||
make([]byte, mtu),
|
||||
)
|
||||
}
|
||||
|
||||
ifce.closeTunnel(hostInfo)
|
||||
return w.WriteLine("Closed")
|
||||
}
|
||||
|
||||
func sshCreateTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
flags, ok := fs.(*sshCreateTunnelFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine("No vpn address was provided")
|
||||
}
|
||||
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
if !vpnAddr.IsValid() {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo != nil {
|
||||
return w.WriteLine(fmt.Sprintf("Tunnel already exists"))
|
||||
}
|
||||
|
||||
hostInfo = ifce.handshakeManager.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo != nil {
|
||||
return w.WriteLine(fmt.Sprintf("Tunnel already handshaking"))
|
||||
}
|
||||
|
||||
var addr netip.AddrPort
|
||||
if flags.Address != "" {
|
||||
addr, err = netip.ParseAddrPort(flags.Address)
|
||||
if err != nil {
|
||||
return w.WriteLine("Address could not be parsed")
|
||||
}
|
||||
}
|
||||
|
||||
// Set the remote from the callback, which StartHandshake runs under the handshake manager lock
|
||||
// before the hostinfo reaches the handshake loop or the static-host trigger, so the address is
|
||||
// in the RemoteList before the first handshake is sent.
|
||||
ifce.handshakeManager.StartHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
|
||||
if addr.IsValid() {
|
||||
hh.hostinfo.SetRemote(addr)
|
||||
}
|
||||
})
|
||||
|
||||
return w.WriteLine("Created")
|
||||
}
|
||||
|
||||
func sshChangeRemote(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
flags, ok := fs.(*sshChangeRemoteFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine("No vpn address was provided")
|
||||
}
|
||||
|
||||
if flags.Address == "" {
|
||||
return w.WriteLine("No address was provided")
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddrPort(flags.Address)
|
||||
if err != nil {
|
||||
return w.WriteLine("Address could not be parsed")
|
||||
}
|
||||
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
if !vpnAddr.IsValid() {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn address could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo == nil {
|
||||
return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn address: %v", a[0]))
|
||||
}
|
||||
|
||||
hostInfo.SetRemote(addr)
|
||||
return w.WriteLine("Changed")
|
||||
}
|
||||
|
||||
func sshLogLevel(l *slog.Logger, fs any, a []string, w sshd.StringWriter) error {
|
||||
ctrl, ok := l.Handler().(interface {
|
||||
GetLevel() slog.Level
|
||||
SetLevel(slog.Level)
|
||||
})
|
||||
if !ok {
|
||||
return w.WriteLine("Log level is not reconfigurable on this logger")
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
|
||||
}
|
||||
|
||||
level, err := logging.ParseLevel(strings.ToLower(a[0]))
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("Unknown log level %s. Possible log levels: trace, debug, info, warn, error", a))
|
||||
}
|
||||
|
||||
ctrl.SetLevel(level)
|
||||
return w.WriteLine(fmt.Sprintf("Log level is: %s", logging.LevelName(ctrl.GetLevel())))
|
||||
}
|
||||
|
||||
func sshLogFormat(l *slog.Logger, fs any, a []string, w sshd.StringWriter) error {
|
||||
ctrl, ok := l.Handler().(interface {
|
||||
GetFormat() string
|
||||
SetFormat(string) error
|
||||
})
|
||||
if !ok {
|
||||
return w.WriteLine("Log format is not reconfigurable on this logger")
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
|
||||
}
|
||||
|
||||
if err := ctrl.SetFormat(strings.ToLower(a[0])); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteLine(fmt.Sprintf("Log format is: %s", ctrl.GetFormat()))
|
||||
}
|
||||
|
||||
func sshPrintCert(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
args, ok := fs.(*sshPrintCertFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
cert := ifce.pki.getCertState().GetDefaultCertificate()
|
||||
if len(a) > 0 {
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
if !vpnAddr.IsValid() {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo == nil {
|
||||
return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
|
||||
}
|
||||
|
||||
cert = hostInfo.GetCert().Certificate
|
||||
}
|
||||
|
||||
if args.Json || args.Pretty {
|
||||
b, err := cert.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if args.Pretty {
|
||||
buf := new(bytes.Buffer)
|
||||
err := json.Indent(buf, b, "", " ")
|
||||
b = buf.Bytes()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return w.WriteBytes(b)
|
||||
}
|
||||
|
||||
if args.Raw {
|
||||
b, err := cert.MarshalPEM()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return w.WriteBytes(b)
|
||||
}
|
||||
|
||||
return w.WriteLine(cert.String())
|
||||
}
|
||||
|
||||
func sshPrintRelays(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
args, ok := fs.(*sshPrintTunnelFlags)
|
||||
if !ok {
|
||||
w.WriteLine(fmt.Sprintf("sshPrintRelays failed to convert args type"))
|
||||
return nil
|
||||
}
|
||||
|
||||
relays := map[uint32]*HostInfo{}
|
||||
ifce.hostMap.Lock()
|
||||
maps.Copy(relays, ifce.hostMap.Relays)
|
||||
ifce.hostMap.Unlock()
|
||||
|
||||
type RelayFor struct {
|
||||
Error error
|
||||
Type string
|
||||
State string
|
||||
PeerAddr netip.Addr
|
||||
LocalIndex uint32
|
||||
RemoteIndex uint32
|
||||
RelayedThrough []netip.Addr
|
||||
}
|
||||
|
||||
type RelayOutput struct {
|
||||
NebulaAddr netip.Addr
|
||||
RelayForAddrs []RelayFor
|
||||
}
|
||||
|
||||
type CmdOutput struct {
|
||||
Relays []*RelayOutput
|
||||
}
|
||||
|
||||
co := CmdOutput{}
|
||||
|
||||
enc := json.NewEncoder(w.GetWriter())
|
||||
|
||||
if args.Pretty {
|
||||
enc.SetIndent("", " ")
|
||||
}
|
||||
|
||||
for k, v := range relays {
|
||||
ro := RelayOutput{NebulaAddr: v.vpnAddrs[0]}
|
||||
co.Relays = append(co.Relays, &ro)
|
||||
relayHI := ifce.hostMap.QueryVpnAddr(v.vpnAddrs[0])
|
||||
if relayHI == nil {
|
||||
ro.RelayForAddrs = append(ro.RelayForAddrs, RelayFor{Error: errors.New("could not find hostinfo")})
|
||||
continue
|
||||
}
|
||||
for _, vpnAddr := range relayHI.relayState.CopyRelayForIps() {
|
||||
rf := RelayFor{Error: nil}
|
||||
r, ok := relayHI.relayState.GetRelayForByAddr(vpnAddr)
|
||||
if ok {
|
||||
t := ""
|
||||
switch r.Type {
|
||||
case ForwardingType:
|
||||
t = "forwarding"
|
||||
case TerminalType:
|
||||
t = "terminal"
|
||||
default:
|
||||
t = "unknown"
|
||||
}
|
||||
|
||||
s := ""
|
||||
switch r.State {
|
||||
case Requested:
|
||||
s = "requested"
|
||||
case Established:
|
||||
s = "established"
|
||||
default:
|
||||
s = "unknown"
|
||||
}
|
||||
|
||||
rf.LocalIndex = r.LocalIndex
|
||||
rf.RemoteIndex = r.RemoteIndex
|
||||
rf.PeerAddr = r.PeerAddr
|
||||
rf.Type = t
|
||||
rf.State = s
|
||||
if rf.LocalIndex != k {
|
||||
rf.Error = fmt.Errorf("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)
|
||||
}
|
||||
}
|
||||
err := enc.Encode(co)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sshPrintTunnel(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||
args, ok := fs.(*sshPrintTunnelFlags)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
return w.WriteLine("No vpn address was provided")
|
||||
}
|
||||
|
||||
vpnAddr, err := netip.ParseAddr(a[0])
|
||||
if err != nil {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
if !vpnAddr.IsValid() {
|
||||
return w.WriteLine(fmt.Sprintf("The provided vpn addr could not be parsed: %s", a[0]))
|
||||
}
|
||||
|
||||
hostInfo := ifce.hostMap.QueryVpnAddr(vpnAddr)
|
||||
if hostInfo == nil {
|
||||
return w.WriteLine(fmt.Sprintf("Could not find tunnel for vpn addr: %v", a[0]))
|
||||
}
|
||||
|
||||
enc := json.NewEncoder(w.GetWriter())
|
||||
if args.Pretty {
|
||||
enc.SetIndent("", " ")
|
||||
}
|
||||
|
||||
return enc.Encode(copyHostInfo(hostInfo, ifce.hostMap.GetPreferredRanges()))
|
||||
}
|
||||
|
||||
func sshDeviceInfo(ifce *Interface, fs any, w sshd.StringWriter) error {
|
||||
|
||||
data := struct {
|
||||
Name string `json:"name"`
|
||||
Cidr []netip.Prefix `json:"cidr"`
|
||||
}{
|
||||
Name: ifce.inside.Name(),
|
||||
Cidr: make([]netip.Prefix, len(ifce.inside.Networks())),
|
||||
}
|
||||
|
||||
copy(data.Cidr, ifce.inside.Networks())
|
||||
|
||||
flags, ok := fs.(*sshDeviceInfoFlags)
|
||||
if !ok {
|
||||
return fmt.Errorf("internal error: expected flags to be sshDeviceInfoFlags but was %+v", fs)
|
||||
}
|
||||
|
||||
if flags.Json || flags.Pretty {
|
||||
js := json.NewEncoder(w.GetWriter())
|
||||
if flags.Pretty {
|
||||
js.SetIndent("", " ")
|
||||
}
|
||||
|
||||
return js.Encode(data)
|
||||
} else {
|
||||
return w.WriteLine(fmt.Sprintf("name=%v cidr=%v", data.Name, data.Cidr))
|
||||
}
|
||||
}
|
||||
|
||||
// sshReload reloads the config and writes the result to the client. It reloads even if the client has gone away
|
||||
func sshReload(l *slog.Logger, c *config.C, w sshd.StringWriter) error {
|
||||
writeErr := w.WriteLine("Reloading config")
|
||||
res := c.ReloadConfig()
|
||||
res.Log(l)
|
||||
if err := w.WriteLine(res.String()); writeErr == nil {
|
||||
writeErr = err
|
||||
}
|
||||
return writeErr
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/slackhq/nebula/commands"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestSSHCommandSurface is a characterization test for the ssh command surface.
|
||||
// It pins the registered command set, their descriptions, help text and flag definitions
|
||||
// so that moving the registry to a transport neutral package is provably a relocation
|
||||
// rather than a rewrite. Regenerate with `go test . -run TestSSHCommandSurface -update`.
|
||||
|
||||
func TestSSHCommandSurface(t *testing.T) {
|
||||
got := renderCommandSurface(registeredCommands(t).Schema())
|
||||
test.Golden(t, filepath.Join("testdata", "ssh_commands.golden"), got)
|
||||
}
|
||||
|
||||
// registeredCommands returns a registry holding every command nebula serves. The
|
||||
// Interface is never dereferenced: attachCommands only closes over it.
|
||||
func registeredCommands(t *testing.T) *commands.Registry {
|
||||
t.Helper()
|
||||
l := test.NewLogger()
|
||||
reg := commands.New()
|
||||
attachCommands(l, config.NewC(l), reg, &Interface{})
|
||||
return reg
|
||||
}
|
||||
|
||||
// renderCommandSurface prints what a client actually sees, which is the schema rather
|
||||
// than the Command structs: the presentation flags are offered on every command that
|
||||
// returns a value, so reading Command.Flags alone would under-report the surface.
|
||||
func renderCommandSurface(cmds []commands.CommandSchema) string {
|
||||
lines := make([]string, 0, len(cmds))
|
||||
for _, cmd := range cmds {
|
||||
b := &bytes.Buffer{}
|
||||
fmt.Fprintf(b, "%s\n", cmd.Name)
|
||||
fmt.Fprintf(b, " short: %s\n", cmd.Short)
|
||||
fmt.Fprintf(b, " help: %s\n", cmd.Help)
|
||||
|
||||
if len(cmd.Flags) > 0 {
|
||||
fmt.Fprintf(b, " flags:\n")
|
||||
for _, f := range cmd.Flags {
|
||||
kind := " string"
|
||||
if f.Bool {
|
||||
kind = ""
|
||||
}
|
||||
fmt.Fprintf(b, " -%s%s\n \t%s\n", f.Name, kind, f.Usage)
|
||||
}
|
||||
}
|
||||
|
||||
lines = append(lines, b.String())
|
||||
}
|
||||
|
||||
sort.Strings(lines)
|
||||
return joinLines(lines)
|
||||
}
|
||||
|
||||
func joinLines(in []string) string {
|
||||
b := &bytes.Buffer{}
|
||||
for _, l := range in {
|
||||
b.WriteString(l)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// TestLocalSocketSurface pins which of nebula's commands the always-on local socket
|
||||
// serves: every one registered. Adding a command fails here until the list below says
|
||||
// so, which turns "somebody forgot to think about it" into a visible decision.
|
||||
func TestLocalSocketSurface(t *testing.T) {
|
||||
var served []commands.Name
|
||||
for _, c := range registeredCommands(t).All() {
|
||||
served = append(served, c.Name)
|
||||
}
|
||||
|
||||
assert.ElementsMatch(t, []commands.Name{
|
||||
commands.Help,
|
||||
commands.ListHostmap,
|
||||
commands.ListPendingHostmap,
|
||||
commands.ListLighthouseAddrmap,
|
||||
commands.PrintCert,
|
||||
commands.PrintTunnel,
|
||||
commands.PrintRelays,
|
||||
commands.DeviceInfo,
|
||||
commands.Version,
|
||||
commands.QueryLighthouse,
|
||||
commands.Reload,
|
||||
commands.LogLevel,
|
||||
commands.LogFormat,
|
||||
commands.ChangeRemote,
|
||||
commands.CloseTunnel,
|
||||
commands.CreateTunnel,
|
||||
}, served)
|
||||
}
|
||||
+13
-42
@@ -1,8 +1,6 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -13,20 +11,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type lineWriter struct {
|
||||
lines []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (w *lineWriter) WriteLine(s string) error {
|
||||
w.lines = append(w.lines, s)
|
||||
return w.err
|
||||
}
|
||||
func (w *lineWriter) Write(s string) error { return w.WriteLine(s) }
|
||||
func (w *lineWriter) WriteBytes(b []byte) error { return w.WriteLine(string(b)) }
|
||||
func (w *lineWriter) GetWriter() io.Writer { return io.Discard }
|
||||
|
||||
func TestSSHReloadReportsTheResult(t *testing.T) {
|
||||
func TestReloadCommandReportsTheResult(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(body string) {
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yml"), []byte(body), 0o600))
|
||||
@@ -43,41 +28,27 @@ func TestSSHReloadReportsTheResult(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
reload := func() []string {
|
||||
w := &lineWriter{}
|
||||
require.NoError(t, sshReload(l, c, w))
|
||||
return w.lines
|
||||
// reload reports what happened. A reload that failed is a refusal, exit 1 over ssh;
|
||||
// one that merely needs a restart is not.
|
||||
reload := func(failed bool) string {
|
||||
res := runReload(l, c)
|
||||
assert.Equal(t, !failed, res.OK)
|
||||
return res.Reason
|
||||
}
|
||||
|
||||
write("a: 2\nb: 1")
|
||||
assert.Equal(t, []string{"Reloading config", "Config reload complete"}, reload())
|
||||
assert.Equal(t, "Config reload complete", reload(false))
|
||||
|
||||
fail = true
|
||||
write("a: 3\nb: 1")
|
||||
assert.Equal(t, []string{"Reloading config", "Config reload completed with errors, review the logs"}, reload())
|
||||
assert.Equal(t, "Config reload completed with errors, review the logs", reload(true))
|
||||
|
||||
fail = false
|
||||
write("a: 3\nb: 2")
|
||||
assert.Equal(t, []string{"Reloading config", "Config reload was completed but requires a restart to fully apply, keys [b]"}, reload())
|
||||
assert.Equal(t, "Config reload was completed but requires a restart to fully apply, keys [b]", reload(false))
|
||||
|
||||
write("a: [")
|
||||
lines := reload()
|
||||
require.Len(t, lines, 2)
|
||||
assert.Contains(t, lines[1], "Config reload failed, the new config did not load")
|
||||
assert.Contains(t, lines[1], dir, "names the config that did not load")
|
||||
}
|
||||
|
||||
// A client that went away still gets the reload it asked for
|
||||
func TestSSHReloadReloadsWhenTheClientIsGone(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yml"), []byte("a: 1"), 0o600))
|
||||
l := test.NewLogger()
|
||||
c := config.NewC(l)
|
||||
require.NoError(t, c.Load(dir))
|
||||
reloaded := false
|
||||
c.RegisterReloadCallback(func(*config.C, *config.Reload) { reloaded = true })
|
||||
|
||||
gone := errors.New("client is gone")
|
||||
require.ErrorIs(t, sshReload(l, c, &lineWriter{err: gone}), gone)
|
||||
assert.True(t, reloaded)
|
||||
reason := reload(true)
|
||||
assert.Contains(t, reason, "Config reload failed, the new config did not load")
|
||||
assert.Contains(t, reason, dir, "names the config that did not load")
|
||||
}
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user