systemd-resolved: serve uplink-names, writing the host names file (issue 960)

The verb checks each host name (root, wildcard, trailing dot, a label over
63 bytes, the mesh's own domain or under it, more than 8), writes
/var/lib/node-resolver/uplink-names whole through sudo -n install then
sudo -n mv -f, and answers the names with the link carrying the default
route (the lowest-metric kernel default route that is neither routed nor
the private network's interface) and when they were set.

Builds: design 08 sign-in-page §2, §5, §6
This commit is contained in:
jochen
2026-11-24 21:19:35 +01:00
parent 03bf70a22b
commit a40d7fb1c4
5 changed files with 394 additions and 5 deletions
@@ -14,6 +14,7 @@ package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
@@ -91,13 +92,26 @@ type Resolver struct {
Answers func(ctx context.Context, server string) bool
// AnswerWithinFile holds how long one of them is given to answer (the config value answer-within).
AnswerWithinFile string
// PrivateInterfaceFile holds the private network's own interface name, rendered beside SuffixFile
// (design 08 sign-in-page §7, DQ-1): never the private network's interface is the uplink's link.
PrivateInterfaceFile string
// UplinkNamesFile is where the uplink's holder's names are kept, one a line (design 08 sign-in-page §6).
UplinkNamesFile string
// UplinkNamesAppliedFile is what the guard last gave the link carrying the default route (§8).
UplinkNamesAppliedFile string
// WriteUplinkNames writes UplinkNamesFile whole, as root (§6); stood in for in tests.
WriteUplinkNames func(ctx context.Context, content []byte) error
// Now is the clock the uplink-names verb stamps its answer with; stood in for in tests.
Now func() time.Time
}
// ThisResolver is the machine's.
func ThisResolver() *Resolver {
r := &Resolver{Change: execRunner, Read: readRunner, NetDir: "/sys/class/net", SuffixFile: SuffixPath,
AnswerWithinFile: AnswerWithinPath}
AnswerWithinFile: AnswerWithinPath, PrivateInterfaceFile: PrivateInterfacePath,
UplinkNamesFile: UplinkNamesPath, UplinkNamesAppliedFile: UplinkNamesAppliedPath, Now: time.Now}
r.Answers = r.asks
r.WriteUplinkNames = r.writeUplinkNamesFile
return r
}
@@ -144,6 +158,25 @@ func (r *Resolver) asks(ctx context.Context, server string) bool {
// SuffixPath is the file the mesh renders the mesh's own domain into (the manifest's fact `suffix`).
const SuffixPath = "/etc/node-resolver/suffix"
// PrivateInterfacePath is the file the mesh renders the private network's own interface name into,
// beside SuffixPath (the manifest's fact `private-interface`; design 08 sign-in-page §7, DQ-1).
const PrivateInterfacePath = "/etc/node-resolver/private-interface"
// UplinkNamesPath is where `uplink-names` keeps the host names, one a line, whole (design 08 sign-in-page
// §6): root's, mode 0644, written through `sudo -n install` then `sudo -n mv -f`.
const UplinkNamesPath = "/var/lib/node-resolver/uplink-names"
// UplinkNamesAppliedPath is what the guard last gave the link carrying the default route (§8): the list,
// the link, when, and resolved's refusal or empty.
const UplinkNamesAppliedPath = "/var/lib/node-resolver/uplink-names.applied"
// privateInterface is the private network's own interface name, as the mesh rendered it; empty before it
// has (DQ-1).
func (r *Resolver) privateInterface() string {
raw, _ := os.ReadFile(r.PrivateInterfaceFile)
return strings.TrimSpace(string(raw))
}
// Scope is one place resolved sends names: the machine's global servers (the mesh's resolvers), or a link.
type Scope struct {
Link string `json:"link,omitempty"`
@@ -364,6 +397,209 @@ func Servers(given []string) ([]string, error) {
return out, nil
}
// hostNameLabel matches one label of a host name: letters, digits and hyphens.
var hostNameLabel = regexp.MustCompile(`^[a-z0-9-]+$`)
// HostNames checks the names given to `uplink-names` (design 08 sign-in-page §2): 0 to 8 host names, each
// 1 to 253 bytes of letters, digits, hyphens and dots, lower-cased. Refused, naming the name and the
// reason: a name that is not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root,
// the mesh's own domain or a name under it (ADR 0247 §12's rule for `route`, for the same reason), or more
// than 8 names.
func (r *Resolver) HostNames(given []string) ([]string, error) {
suffix := r.suffix()
out := make([]string, 0, len(given))
for _, n := range given {
n = strings.ToLower(strings.TrimSpace(n))
if n == "" || n == "." {
return nil, errors.New("the root is not a host name: only the mesh's resolvers answer every name")
}
if strings.Contains(n, "*") {
return nil, fmt.Errorf("%q is not a host name: a wildcard", n)
}
if strings.HasSuffix(n, ".") {
return nil, fmt.Errorf("%q is not a host name: a trailing dot", n)
}
if len(n) > 253 {
return nil, fmt.Errorf("%q is not a host name: over 253 bytes", n)
}
for _, label := range strings.Split(n, ".") {
if len(label) > 63 {
return nil, fmt.Errorf("%q is not a host name: a label over 63 bytes", n)
}
if !hostNameLabel.MatchString(label) {
return nil, fmt.Errorf("%q is not a host name", n)
}
}
if n == suffix || strings.HasSuffix(n, "."+suffix) {
return nil, fmt.Errorf("%q is the mesh's own domain: the mesh's names are answered by the mesh's resolvers alone", n)
}
out = append(out, n)
}
if len(out) > 8 {
return nil, fmt.Errorf("%d names; at most 8", len(out))
}
return out, nil
}
// writeUplinkNamesFile writes UplinkNamesFile whole (design 08 sign-in-page §6): `sudo -n install -m 0644
// -o root -g root /dev/stdin <file>.new` with the lines on its input, then `sudo -n mv -f <file>.new
// <file>`, so a reader never sees it half-written. As root (the guard never calls this; only the verb,
// over the bus, does), both run unescalated.
func (r *Resolver) writeUplinkNamesFile(ctx context.Context, content []byte) error {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
newPath := r.UplinkNamesFile + ".new"
program, args := escalated(os.Getuid(), "install", []string{"-m", "0644", "-o", "root", "-g", "root", "/dev/stdin", newPath})
cmd := exec.CommandContext(ctx, program, args...)
cmd.Stdin = bytes.NewReader(content)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
if said := strings.TrimSpace(stderr.String()); said != "" {
return fmt.Errorf("install: %s", said)
}
return fmt.Errorf("install failed: %w", err)
}
_, err := r.Change(ctx, "mv", "-f", newPath, r.UplinkNamesFile)
return err
}
// UplinkNames is `uplink-names`'s answer (design 08 sign-in-page §2): the names now given, the link they
// are answered over now (empty when no link carries a default route), and when the list was set.
type UplinkNames struct {
Names []string `json:"names"`
Link string `json:"link"`
SetAt time.Time `json:"set_at"`
}
// SetUplinkNames writes the host names the uplink's holder gives for its network's own check, through
// UplinkNamesFile (§6), and answers them with the link carrying the default route now (§2, DQ-2): empty
// when there is no such link.
func (r *Resolver) SetUplinkNames(ctx context.Context, given []string) (*UplinkNames, error) {
names, err := r.HostNames(given)
if err != nil {
return nil, err
}
content := []byte(strings.Join(names, "\n"))
if len(names) > 0 {
content = append(content, '\n')
}
if err := r.WriteUplinkNames(ctx, content); err != nil {
return nil, err
}
link := ""
if routes, rerr := r.Routes(ctx); rerr == nil {
link, _ = r.DefaultRouteLink(ctx, routes)
}
return &UplinkNames{Names: names, Link: link, SetAt: r.Now()}, nil
}
// ReadUplinkNames reads the host names `uplink-names` last wrote, one a line; empty before it has.
func ReadUplinkNames(path string) []string {
raw, err := os.ReadFile(path)
if err != nil {
return []string{}
}
out := []string{}
for _, line := range strings.Split(string(raw), "\n") {
if line = strings.TrimSpace(line); line != "" {
out = append(out, line)
}
}
return out
}
// UplinkApplied is what the guard last gave the link carrying the default route (design 08 sign-in-page
// §8): the list, the link, when, and resolved's refusal or empty.
type UplinkApplied struct {
Names []string `json:"names"`
Link string `json:"link"`
At time.Time `json:"at"`
Refused string `json:"refused,omitempty"`
}
// ReadUplinkApplied reads what the guard applied last; the zero value before its first round, or after a
// restart with nothing written yet.
func ReadUplinkApplied(path string) UplinkApplied {
raw, err := os.ReadFile(path)
if err != nil {
return UplinkApplied{}
}
var a UplinkApplied
if json.Unmarshal(raw, &a) != nil {
return UplinkApplied{}
}
return a
}
// kernelDefaultRoute is one of the kernel's default routes: its link and metric (the lowest wins).
type kernelDefaultRoute struct {
link string
metric int
}
// kernelDefaultRoutes reads the kernel's default routes for one family ("-4" or "-6"); a route the kernel
// names no metric for gets 0, its own highest priority.
func (r *Resolver) kernelDefaultRoutes(ctx context.Context, family string) ([]kernelDefaultRoute, error) {
out, err := r.Read(ctx, "ip", family, "route", "show", "default")
if err != nil {
return nil, fmt.Errorf("the kernel's default routes: %w", err)
}
var routes []kernelDefaultRoute
for _, line := range strings.Split(out, "\n") {
fields := strings.Fields(line)
if len(fields) == 0 || fields[0] != "default" {
continue
}
var kr kernelDefaultRoute
for i := 0; i+1 < len(fields); i++ {
switch fields[i] {
case "dev":
kr.link = fields[i+1]
case "metric":
if n, err := strconv.Atoi(fields[i+1]); err == nil {
kr.metric = n
}
}
}
if kr.link != "" {
routes = append(routes, kr)
}
}
return routes, nil
}
// DefaultRouteLink is the link that carries the default route now (design 08 sign-in-page §7, §9; DQ-1,
// DQ-2): among the kernel's IPv4 default routes, or the IPv6 ones when there is no IPv4 one, the one with
// the lowest metric whose link is neither one `route` routed (a VPN's, read from resolved) nor the private
// network's own interface; empty when there is no such link.
func (r *Resolver) DefaultRouteLink(ctx context.Context, routes *Routes) (string, error) {
private := r.privateInterface()
routed := map[string]bool{}
for _, l := range routes.Links {
routed[l.Link] = l.routed
}
candidates, err := r.kernelDefaultRoutes(ctx, "-4")
if err != nil {
return "", err
}
if len(candidates) == 0 {
if candidates, err = r.kernelDefaultRoutes(ctx, "-6"); err != nil {
return "", err
}
}
best, bestMetric := "", 0
for _, c := range candidates {
if c.link == private || routed[c.link] {
continue
}
if best == "" || c.metric < bestMetric {
best, bestMetric = c.link, c.metric
}
}
return best, nil
}
// Route sends these domains, and every name under them, to these servers over this link — and only them.
// Whatever the link was given before is replaced. resolved forgets it when the link goes.
func (r *Resolver) Route(ctx context.Context, link string, domains, servers []string) (*Routed, error) {