Files
nebula/identity.go
T
Matt RichardsonandClaude Fable 5.1 613c7e3061 Add the identity command and serve it on an opt-in HTTP info API
Build slackhq/nebula#1821 ("who is this vpn address?" over a local
HTTP+JSON socket) on the command registry, so the lookup is one command
on every surface and the socket is one more local API.

identity
- `identity [-address <vpn addr>[:port]]`: no address reports this node;
  with one, this node or the peer behind an established tunnel
- Certificate fields only: name, vpn addresses, networks, unsafe
  networks, groups, fingerprint, issuer, validity, cert version; a peer's
  fingerprint is the one nebula computed when it verified the cert
- Port accepted and stripped, 4in6 unmapped, so a RemoteAddr passes
  straight through
- No tunnel is a commands.NotFound; an empty -address is refused
- Lighthouse TXT lookup shares the owner and peer lookups, keeps answering
  with the initiating certificate, and no longer panics without a default cert
- Served on ssh and nebula ctl too

Info API
- Off until `local_api.info.enabled` with `socket` and optional quoted
  octal `socket_mode` (default "0600"); nothing derived
- Serves commands declaring Command.Identity plus help; others 403 naming
  their surfaces. TestInfoAPISurface pins the set to identity
- GET /v1 is the schema; GET /v1/<cmd>?<flag>=<value> runs one; body is
  the -json rendering via commands.Render; commands.PresentationFormat
  reads json/pretty from the query the way a line is read
- 400 commands.ParamError, 403 commands.WithheldError (what Resolve now
  returns for a withheld name, so help and dispatch type-check it too),
  404 NotFound or unknown, 500 Run error, refusal with no reason, or
  recovered panic with no detail; no redirects; every miss is JSON
- listen takes a mode: bind under umask 0077 then chmod; "0660" plus a
  searchable dir opens it to a group
- The chmod, at bind and on a mode-only reload, goes through chmodSocket,
  which never follows a link: a user who can write the socket's directory
  could otherwise swap the node for a link and have a root daemon put
  0660 or 0666 on any file. Only a socket we own is chmoded. On linux the
  node is held open O_PATH|O_NOFOLLOW, checked by fstat, and chmoded
  through /proc/self/fd, so the check and the chmod land on one inode;
  fchmodat2 is the fallback without /proc. On darwin and the BSDs it is
  an Lstat check and fchmodat(AT_SYMLINK_NOFOLLOW). clearStale Lstats
  too, so a dangling link is refused rather than followed by bind on
  darwin
- One endpoint type owns bind under mutex, bind-before-release move,
  context watch and stop/unlink; each server supplies what it serves
- Reloadable through the same reconcile shape as the control socket:
  mode applied in place, unparsable section keeps what runs, control
  socket path refused by name
- Wire returns Endpoints{Control, Info} with one Stop
- Windows unsupported for now (a pipe has no mode); warned once

Tests: identity lookups and shapes; API filter, status codes, panic
recovery, socket mode, rebind, cancellation; config parsing incl. bare
0660; Wire transitions; e2e of two nebulas with the info API resolving
the peer by address and port, through shared test.HTTPDo/HTTPGet helpers.
Goldens gain identity.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 12:26:09 -04:00

236 lines
9.0 KiB
Go

package nebula
import (
"fmt"
"io"
"net/netip"
"strings"
"time"
"github.com/slackhq/nebula/cert"
"github.com/slackhq/nebula/commands"
)
type identityFlags struct {
Address string
// addressSet records that -address was given at all, so a line that left it out is
// told to pass it and one that passed it empty is told the value did not parse. Neither
// is answered with this node's identity, which is whoami's to report: a program
// passing a connection's remote address through must get an error for a value it
// failed to fill in, not the daemon's own identity to authorize against.
addressSet bool
}
// setAddress is -address's setter. flag.Func rather than StringVar so that presence is
// known; its String is empty, which is what a client building a line from the schema
// sees as the default.
func (f *identityFlags) setAddress(v string) error {
f.Address = v
f.addressSet = true
return nil
}
// hostIdentity is what identity reports: the identity a certificate asserts for a host,
// and nothing else. Every field is read from a certificate nebula verified when the
// tunnel came up, or from our own, which is what lets a program on this host make an
// authorization decision from it, within one limit. Nebula drops an inbound packet
// whose source address is not in the sender's certificate, and one with an overlay
// source address that arrived through a peer's unsafe network rather than from the node
// holding it, so for a connection that arrived on the nebula interface the source
// address is the sender's and this is the sender's identity. A connection that arrived
// on any other interface with an overlay source address was never checked by nebula at
// all, so a program authorizing on this answer should confirm the connection came in
// on the nebula interface. The field names are an API: the info API serves this shape
// to programs that were not built against nebula.
type hostIdentity struct {
Name string `json:"name"`
VpnAddrs []netip.Addr `json:"vpnAddrs"`
Networks []netip.Prefix `json:"networks"`
UnsafeNetworks []netip.Prefix `json:"unsafeNetworks"`
Groups []string `json:"groups"`
Fingerprint string `json:"fingerprint"`
Issuer string `json:"issuer"`
NotBefore time.Time `json:"notBefore"`
NotAfter time.Time `json:"notAfter"`
CertVersion int `json:"certVersion"`
}
// runIdentity answers for whoever owns the address: this node, when it is one of ours, or
// the peer behind an established tunnel. The address is required. This node's own
// identity is whoami's to report, so a caller that failed to pass an address is told so
// rather than handed an identity it could mistake for its peer's.
func runIdentity(ifce *Interface, args *identityFlags, a []string) (commands.Result, error) {
// print-cert takes its address as an operand; this takes a flag, because the query
// string of the info API names its parameters and an operand has no name there. One
// spelling on every surface, so the mistake is named rather than ignored.
if len(a) > 0 {
return commands.Failed("identity takes the vpn addr as -address, not as an operand: identity -address %s", a[0]), nil
}
if !args.addressSet {
return commands.Failed("No vpn addr was provided, use -address <vpn addr>[:port]; whoami prints this node's own identity"), nil
}
vpnAddr, err := parseVpnAddrWithOptionalPort(args.Address)
if err != nil {
return commands.Failed("The provided vpn addr could not be parsed: %s", args.Address), nil
}
crt, fingerprint := findCertificateForVpnAddr(ifce.pki.getCertState(), ifce.hostMap, vpnAddr)
if crt == nil {
return commands.NotFound("No active tunnel for vpn addr: %s", vpnAddr), nil
}
id, err := newHostIdentity(crt, fingerprint)
if err != nil {
return commands.Result{}, err
}
return commands.Value(id), nil
}
// runWhoami answers with this node's own identity, from its own certificate.
func runWhoami(ifce *Interface) (commands.Result, error) {
crt := ownCertificate(ifce.pki.getCertState())
if crt == nil {
return commands.Failed("No certificate is loaded"), nil
}
id, err := newHostIdentity(crt, "")
if err != nil {
return commands.Result{}, err
}
return commands.Value(id), nil
}
// textIdentity is the human rendering, shared by every surface.
func textIdentity(id hostIdentity, w io.Writer) error {
_, err := fmt.Fprintf(w,
"name: %s\nvpn addrs: %s\nnetworks: %s\nunsafe networks: %s\ngroups: %s\nfingerprint: %s\nissuer: %s\nnot before: %s\nnot after: %s\ncert version: %d\n",
id.Name,
joinStringers(id.VpnAddrs),
joinStringers(id.Networks),
joinStringers(id.UnsafeNetworks),
strings.Join(id.Groups, ", "),
id.Fingerprint,
id.Issuer,
id.NotBefore.Format(time.RFC3339),
id.NotAfter.Format(time.RFC3339),
id.CertVersion,
)
return err
}
func joinStringers[T fmt.Stringer](in []T) string {
parts := make([]string, 0, len(in))
for _, v := range in {
parts = append(parts, v.String())
}
return strings.Join(parts, ", ")
}
// newHostIdentity reads the identity out of a certificate. fingerprint is the
// certificate's when the caller already holds it, as a verified peer certificate does,
// and "" to have it hashed here. Slices are always allocated so a host with no groups
// reports [] rather than null.
func newHostIdentity(crt cert.Certificate, fingerprint string) (hostIdentity, error) {
if fingerprint == "" {
fp, err := crt.Fingerprint()
if err != nil {
return hostIdentity{}, err
}
fingerprint = fp
}
networks, unsafeNetworks, groups := crt.Networks(), crt.UnsafeNetworks(), crt.Groups()
id := hostIdentity{
Name: crt.Name(),
VpnAddrs: make([]netip.Addr, 0, len(networks)),
Networks: append(make([]netip.Prefix, 0, len(networks)), networks...),
UnsafeNetworks: append(make([]netip.Prefix, 0, len(unsafeNetworks)), unsafeNetworks...),
Groups: append(make([]string, 0, len(groups)), groups...),
Fingerprint: fingerprint,
Issuer: crt.Issuer(),
NotBefore: crt.NotBefore(),
NotAfter: crt.NotAfter(),
CertVersion: int(crt.Version()),
}
for _, n := range networks {
id.VpnAddrs = append(id.VpnAddrs, n.Addr())
}
return id, nil
}
// ownCertificate is this node's certificate: the v2 one when it is loaded, else the v1.
// A v2 certificate is a superset of the v1 and may carry more networks, and it is the
// one newCertState builds myVpnAddrsTable from, so an address that matched that table is
// always listed in the certificate reported here. It is nil only when no certificate is
// loaded, which a running nebula never has.
func ownCertificate(cs *CertState) cert.Certificate {
if cs == nil {
return nil
}
if crt := cs.getCertificate(cert.Version2); crt != nil {
return crt
}
return cs.getCertificate(cert.Version1)
}
// findCertificateForVpnAddr answers who owns a vpn address: this node, from its own
// certificate state, since the hostmap never carries an entry for ourselves, or the peer
// behind an established tunnel. The certificate is nil when the address is unknown,
// when the tunnel is still pending and when it is mid teardown. A peer's comes with the
// fingerprint nebula computed when it verified the certificate; our own comes with "",
// since none is kept for it. identity and print-cert go through it, and the lighthouse's
// DNS TXT lookup through the two halves, so no surface disagrees about whose address it
// is; the TXT record alone keeps answering with the certificate handshakes start with.
func findCertificateForVpnAddr(cs *CertState, hostMap *HostMap, ip netip.Addr) (crt cert.Certificate, fingerprint string) {
if ownsVpnAddr(cs, ip) {
return ownCertificate(cs), ""
}
return peerCertificateForVpnAddr(hostMap, ip)
}
// ownsVpnAddr reports whether ip is one of this node's own vpn addresses.
func ownsVpnAddr(cs *CertState, ip netip.Addr) bool {
return cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip)
}
// peerCertificateForVpnAddr is the certificate of the peer behind an established tunnel
// to ip, with the fingerprint nebula computed when it verified it, or nil when there is
// no such tunnel. See findCertificateForVpnAddr.
func peerCertificateForVpnAddr(hostMap *HostMap, ip netip.Addr) (crt cert.Certificate, fingerprint string) {
hostinfo := hostMap.QueryVpnAddr(ip)
if hostinfo == nil {
return nil, ""
}
cc := hostinfo.GetCert()
if cc == nil {
return nil, ""
}
return cc.Certificate, cc.Fingerprint
}
// parseVpnAddrWithOptionalPort reads a vpn address alone or with a port,
// 192.168.100.7:54321 or [fd00::1]:443, so a program can pass a connection's remote
// address through as its runtime reported it. A 4in6 address (::ffff:a.b.c.d) is
// unmapped, which is how an IPv4 peer arrives on a dual stack listener, and a zone is
// dropped, since no vpn address carries one.
func parseVpnAddrWithOptionalPort(s string) (netip.Addr, error) {
ip, err := netip.ParseAddr(s)
if err != nil {
ap, err := netip.ParseAddrPort(s)
if err != nil {
return netip.Addr{}, err
}
ip = ap.Addr()
}
return ip.Unmap().WithZone(""), nil
}