ipcauth

package
v0.83.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 25 Imported by: 0

Documentation

Overview

Package ipcauth provides the kernel-authenticated identity of a local IPC (gRPC) caller and the transport credentials that surface it into the gRPC context, so the daemon can authorize individual RPCs by caller identity.

On Unix the identity is read from the kernel via SO_PEERCRED (Linux) or LOCAL_PEERCRED (Darwin/FreeBSD). On Windows it is derived from the named-pipe client token. Platforms without a peer-identity primitive get no credentials, and every consumer must fail closed when no identity is available.

Index

Constants

View Source
const (
	// ErrorReasonPrivilegeRequired identifies the detail.
	ErrorReasonPrivilegeRequired = "PRIVILEGE_REQUIRED"
	// ErrorDomain scopes the reason to the NetBird daemon.
	ErrorDomain = "daemon.netbird.io"
	// ErrorMetaSummary is the one-sentence explanation of what was refused.
	ErrorMetaSummary = "summary"
	// ErrorMetaCommand is the command that performs the same operation with the
	// privileges it needs, ready to copy and run.
	ErrorMetaCommand = "command"

	// ErrorReasonSessionHeld identifies a refusal caused by another user's live
	// connection.
	ErrorReasonSessionHeld = "SESSION_HELD"

	// ErrorReasonNotProfileOwner identifies a refusal caused by the profile
	// belonging to another account. It carries no command either: privilege is
	// not what the method asked for, so telling the caller to elevate would send
	// them the wrong way.
	ErrorReasonNotProfileOwner = "NOT_PROFILE_OWNER"

	// ErrorReasonProfileUnowned identifies a refusal caused by the profile
	// recording no owner. It carries the command that records one.
	ErrorReasonProfileUnowned = "PROFILE_UNOWNED"
)

Fields of the ErrorInfo detail the daemon attaches to a PermissionDenied it raises for an operation that requires root/administrator. Clients match on Reason and Domain rather than on the message text, and render the summary and command themselves so the user gets guidance instead of a gRPC error dump.

View Source
const (
	ActorKeyAdministrator = "administrator"
	ActorKeyRoot          = "root"
)

The values PrivilegedActorKey returns.

View Source
const EnvDisableProfileOwnership = "NB_DISABLE_PROFILE_OWNERSHIP"

Variables

This section is empty.

Functions

func ClaimCommand added in v0.83.0

func ClaimCommand(handle string) string

ClaimCommand renders the elevated command that records an owner for a profile. With no profile to name it keeps the placeholder for the caller to fill in.

func ContextWithTarget added in v0.83.0

func ContextWithTarget(ctx context.Context, path string) context.Context

ContextWithTarget carries the profile the gate resolved, so a handler acts on the profile that was authorized rather than resolving the caller's handle a second time.

func DownCommand added in v0.83.0

func DownCommand() string

DownCommand renders the elevated command that ends the live session.

func ElevatedCommand

func ElevatedCommand(command string) string

ElevatedCommand renders a command so that running it grants the privileges the operation needs. Windows has no in-line equivalent of sudo, so the command is returned unchanged and the user is expected to run it from an elevated terminal.

func ForwardIdentityMetadata

func ForwardIdentityMetadata(id Identity, known bool) metadata.MD

ForwardIdentityMetadata encodes an HTTP client's identity for the JSON gateway to forward to the daemon. When known is false only the marker is set, which makes the daemon treat the caller as unidentified rather than as the daemon itself.

func GIDPrincipal added in v0.83.0

func GIDPrincipal(gid uint32) string

GIDPrincipal builds the principal string for a Unix group ID.

func IsConsoleUser added in v0.83.0

func IsConsoleUser(id Identity) bool

IsConsoleUser reports whether a caller is sitting at one of this machine's consoles right now.

It is false on a headless machine, which has no seat to sit at, on a platform that exposes no console-user lookup at all, and whenever the lookup fails. Callers must read that as "cannot confirm" rather than as proof of absence. It gates handing out ownership, so a lookup that cannot answer withholds a claim, and never grants one.

func IsDaemonSelf

func IsDaemonSelf(id Identity) bool

IsDaemonSelf reports whether an identity is this very process. The JSON gateway runs inside the daemon and re-dials it locally, so this is what distinguishes the gateway from any other caller, whatever user the daemon runs as.

func IsPrivilegedCaller

func IsPrivilegedCaller(id Identity) bool

IsPrivilegedCaller reports whether an identity may make the changes the daemon restricts to the platform administrator. This is the daemon's own rule and cannot be evaluated by a client, which does not know what the daemon runs as.

Beyond root/administrator it accepts a caller running as the daemon's own identity when the daemon is itself unprivileged. That keeps a rootless container working, where there is no uid 0 at all, and a Windows daemon in netstack mode, which needs no administrator rights. In those setups a caller sharing the daemon's identity can already rewrite the config files it reads and replace the binary it runs, so refusing it a config change would protect nothing; and an unprivileged daemon cannot hand out a root shell in the first place.

func IsReservedForwardKey

func IsReservedForwardKey(key string) bool

IsReservedForwardKey reports whether a gRPC metadata key belongs to the gateway's identity forwarding, and therefore must be dropped when it arrives from outside.

grpc-gateway maps "Grpc-Metadata-<key>" request headers into gRPC metadata and joins them ahead of the values its own annotators add. Without dropping these, an HTTP client could hand the daemon "x-netbird-fwd-uid: 0" and be believed, because the daemon trusts forwarded metadata when the transport peer is the (privileged) gateway.

func NewTransportCredentials

func NewTransportCredentials() credentials.TransportCredentials

NewTransportCredentials returns gRPC transport credentials that expose the caller's kernel-authenticated identity via IdentityFromContext. It returns nil on platforms that have no peer-identity primitive, which the caller must treat as "authorization cannot be enforced".

The handshake exchanges no bytes on the wire, so a client dialing with insecure credentials interoperates with a server using these. That keeps older CLI and UI binaries working against an upgraded daemon.

func NotOwnerError added in v0.83.0

func NotOwnerError(action string) error

NotOwnerError refuses an operation because the profile it addresses belongs to somebody else.

func OpenOwnedFile added in v0.76.1

func OpenOwnedFile(id Identity, path string) (*os.File, error)

OpenOwnedFile opens path for reading on behalf of the IPC caller identified by id, and fails unless the opened file is a regular file that id owns.

It exists for the paths a local caller hands to the daemon over the IPC. The daemon runs as root, so opening such a path unchecked lets any local user read any file through it. Ownership is the invariant that keeps the daemon from reading, with its own privileges, a file the caller could not read itself: a symlink or hard link planted at the path resolves to a file someone else owns and is refused.

The check is made against the open descriptor rather than the path, so swapping the path between the check and the read cannot change the answer.

A privileged caller is exempt: it can read the file directly, so refusing it here would protect nothing. The regular-file requirement still applies to everyone, since a fifo or device planted at the path is never a log file.

func OwnerPrincipalForIdentity added in v0.83.0

func OwnerPrincipalForIdentity(id Identity) string

OwnerPrincipalForIdentity returns the self-ownership principal for an identity: the user's UID on Unix, or the user's SID on Windows.

func PrivilegeError added in v0.83.0

func PrivilegeError(summary, command string) error

PrivilegeError builds the PermissionDenied carrying summary and command.

func PrivilegeSummary added in v0.83.0

func PrivilegeSummary(action, actor string) string

PrivilegeSummary states what is refused and what it needs, in one sentence that reads the same in a dialog and in a terminal.

func PrivilegedActor

func PrivilegedActor() string

PrivilegedActor names the principal a privileged operation requires, for use in messages shown to the user.

func PrivilegedActorKey added in v0.78.0

func PrivilegedActorKey() string

PrivilegedActorKey identifies that principal without wording it, for a client that writes its own message in the user's language. The words PrivilegedActor returns are English, and a translated sentence cannot borrow them.

func ProfileOwnershipDisabled added in v0.83.0

func ProfileOwnershipDisabled() bool

ProfileOwnershipDisabled reports whether profile ownership is turned off, so every identified caller reaches every profile and controls its session.

Mobile records no owners. The app is the only caller and the platform sandbox already isolates one install from another.

func RequireHolderForFullStatus added in v0.83.0

func RequireHolderForFullStatus(r Request) error

RequireHolderForFullStatus escalates a StatusRequest that asks for peer detail or for probes to be run.

func RequiredActor added in v0.83.0

func RequiredActor(command string) (string, string)

RequiredActor names who may perform the operation and adjusts the command to match.

func SIDPrincipal added in v0.83.0

func SIDPrincipal(sid string) string

SIDPrincipal builds the owner string for a Windows SID.

func SessionHeldError added in v0.83.0

func SessionHeldError(action string) error

SessionHeldError refuses an operation because another user has the machine connected.

func TargetFromContext added in v0.83.0

func TargetFromContext(ctx context.Context) (string, bool)

TargetFromContext returns the file of the profile the gate resolved for this request. It reports false when nothing resolved, which a handler acting on a named profile must treat as a refusal rather than as the active profile.

func UIDPrincipal added in v0.83.0

func UIDPrincipal(uid uint32) string

UIDPrincipal builds the owner string for a Unix user ID.

func UnownedError added in v0.83.0

func UnownedError(action, handle string, atConsole bool) error

UnownedError refuses an operation because the profile it addresses has no owner on record, and names the command that gives it one. atConsole is whether the caller sits at one of this machine's consoles.

func UpCommand

func UpCommand(flags string) string

UpCommand renders an elevated `netbird up` with the given flags, preceded by a `down`. The down is what makes the command work on a connected client: `netbird up` prints "Already connected" and returns without applying any config flag, so on its own the command would appear to do nothing. It is a no-op, exit 0, when the client is not connected.

";" rather than "&&" so the line can be pasted into any of the shells a user might have: PowerShell 5.1, still the default on Windows Server, rejects "&&" as a syntax error.

func WithForwardedIdentity

func WithForwardedIdentity(ctx context.Context, id Identity, known bool) context.Context

WithForwardedIdentity stamps id onto a context's outgoing metadata for the JSON gateway's call to the daemon, replacing any forwarding keys already present so values supplied from outside cannot survive alongside it.

This is deliberately not done with runtime.WithMetadata: grpc-gateway skips its annotators entirely when no request header maps to metadata ("if len(pairs) == 0 { return ctx, nil, nil }", runtime/context.go), which an HTTP/1.0 request with no Host header over a unix socket achieves. The daemon would then see an unmarked call whose transport peer is the daemon's own identity, and authorize it as the daemon. A client interceptor runs for every RPC regardless of headers.

Types

type AuthInfo

type AuthInfo struct {
	credentials.CommonAuthInfo
	Identity Identity
}

AuthInfo carries the peer Identity as a gRPC credentials.AuthInfo so handlers can retrieve it from the request context via IdentityFromContext.

func (AuthInfo) AuthType

func (AuthInfo) AuthType() string

AuthType identifies the authentication scheme.

type AuthzGate added in v0.83.0

type AuthzGate struct {
	// contains filtered or unexported fields
}

AuthzGate authorizes every RPC call before its handler run.

func NewAuthzGate added in v0.83.0

func NewAuthzGate() *AuthzGate

NewAuthzGate returns a gate with no state attached.

func (*AuthzGate) SetState added in v0.83.0

func (g *AuthzGate) SetState(st DaemonState)

SetState attaches the daemon state. Must be called before serving RPCs.

func (*AuthzGate) StreamPolicyInterceptor added in v0.83.0

func (g *AuthzGate) StreamPolicyInterceptor() grpc.StreamServerInterceptor

StreamPolicyInterceptor authorizes each streaming RPC before the handler runs. The request payload is not yet available, so no streaming method may be target-scoped.

func (*AuthzGate) UnaryPolicyInterceptor added in v0.83.0

func (g *AuthzGate) UnaryPolicyInterceptor() grpc.UnaryServerInterceptor

UnaryPolicyInterceptor authorizes each unary RPC before the handler runs.

type AuthzLevel added in v0.83.0

type AuthzLevel uint8

AuthzLevel is the authority a caller holds over the daemon's current state. The values are ordered, and each level can do everything the levels below it can. A MethodPolicy is satisfied when the caller's level is at least the level the method requires.

const (
	// AuthzLevelNone is a caller whose kernel identity could not be established.
	AuthzLevelNone AuthzLevel = iota

	// AuthzLevelIdentified is any caller the kernel could verify.
	AuthzLevelIdentified

	// AuthzLevelProfileOwner is a caller being the owner of the current targeted
	// profile
	AuthzLevelProfileOwner

	// AuthzLevelSessionHolder is a caller that owns the current active profile
	// and the session is currently connected (after running UP).
	AuthzLevelSessionHolder

	// AuthzLevelPrivileged is root, an elevated administrator or the daemon's
	// own identity (if running as less privileges than root).
	AuthzLevelPrivileged
)

func (AuthzLevel) String added in v0.83.0

func (l AuthzLevel) String() string

String() resolves a AuthzLevel to a human readable debug string.

type DaemonState added in v0.83.0

type DaemonState interface {
	// SessionHolder returns the principal entitled to the live connection and
	// whether one is held.
	SessionHolder() (Principal, bool)

	// ResolveTarget resolves the profile a request names to a concrete profile
	// and reports whether the caller may address it. An empty handle is the
	// active profile.
	//
	// The error says what was wrong with the handle itself.
	ResolveTarget(id Identity, handle string) (Target, error)
}

DaemonState is used to surface the server state needed for determining authorization.

type Denial added in v0.83.0

type Denial struct {
	Reason  string
	Summary string
	Command string
}

Denial is a refusal the daemon explained, read back off the error it raised. The reason identifies which refusal it was, so a consumer can present each one in its own way without matching on message text.

func DenialFrom added in v0.83.0

func DenialFrom(err error) (Denial, bool)

DenialFrom returns the refusal a daemon error explains, if it explains one.

type Identity

type Identity struct {
	// UID and GID are the caller's Unix user ID and primary group ID. Both are
	// zero on Windows, where SID is authoritative instead.
	UID uint32
	GID uint32

	// SID is the caller's Windows security identifier, empty on Unix.
	SID string

	// Groups holds the caller's Windows group SIDs, captured from the client
	// token at handshake time. Only groups that are enabled and not
	// deny-only are captured, so a group listed here is one the caller can
	// actually exercise. Empty on Unix.
	Groups []string

	// Elevated reports whether the Windows client token is elevated (running
	// as administrator, or an administrator with UAC turned off). Always false
	// on Unix, where privilege is uid 0.
	Elevated bool

	// PID is the caller's process ID where the platform reports it (Linux's
	// SO_PEERCRED), and 0 where it does not. It identifies the daemon's own
	// process dialling itself, which is what the JSON gateway does, and is never
	// used to grant anything.
	PID int32
	// contains filtered or unexported fields
}

Identity is the kernel-authenticated identity of a local IPC caller. The zero value is not a valid identity: consumers must only use one obtained with a true ok/nil error return.

func CallerIdentity

func CallerIdentity(ctx context.Context) (Identity, bool)

CallerIdentity returns the identity to authorize a request against. For a direct connection that is the transport peer's kernel identity. For a request relayed by the local JSON gateway it is the identity the gateway forwarded, since the transport peer is then the daemon itself.

A forwarded identity is only honoured when the transport peer is the daemon's own identity and the metadata carries this process's forwarding proof, so forged forwarding metadata gains a caller nothing. A forwarded request that carries no identity is reported as unidentified, never as the daemon.

The second return value is false when no identity could be established, and callers MUST fail closed in that case.

func ConnIdentity

func ConnIdentity(conn net.Conn) (Identity, error)

ConnIdentity extracts the caller's identity from an accepted local IPC connection. It is shared by the gRPC transport credentials and by the JSON gateway, which reads the identity of its own HTTP clients.

func CurrentProcessIdentity

func CurrentProcessIdentity() (Identity, error)

CurrentProcessIdentity returns this process's identity as the daemon would see it if this process connected to the local IPC. It lets a client (the UI) decide up front whether a privileged operation can succeed, without a round-trip and without duplicating the rules: the answer comes from the same Identity.IsPrivileged the daemon applies.

func IdentityFromContext

func IdentityFromContext(ctx context.Context) (Identity, bool)

IdentityFromContext extracts the caller's kernel-authenticated identity from the gRPC peer context. The second return value is false when no IPC transport credentials were negotiated, which happens on a TCP daemon socket and on platforms without a peer-identity primitive. Callers MUST fail closed in that case.

func KnownForTest added in v0.83.0

func KnownForTest(id Identity) Identity

KnownForTest returns a copy of id marked as kernel-attested, so packages outside ipcauth can build identity fixtures. A real Identity is only ever produced by a peer-credential read, nothing outside a test should call this.

func PeerIdentity

func PeerIdentity(conn net.Conn) (Identity, error)

PeerIdentity reads the kernel-authenticated identity of the process on the other end of a Unix socket via SO_PEERCRED. The credentials are recorded by the kernel at connect() time and cannot be changed for the life of the connection, so they are not spoofable by the caller.

func SelfDelegatesTo

func SelfDelegatesTo() (Identity, bool)

SelfDelegatesTo returns the identity this process delegates its authority to, and whether it delegates at all. Only an unprivileged daemon does: see IsPrivilegedCaller. It exists so a refusal can name who may actually perform the operation, because on such a host root is neither required nor necessarily available.

func (Identity) IsPrivileged

func (i Identity) IsPrivileged() bool

IsPrivileged reports whether the caller is the platform's administrative principal, which is what the daemon requires for changes that cross the user-to-root boundary.

On Windows the decision comes from the caller's token rather than from account names or group RIDs: an elevated token, the LocalSystem SID, or a token with BUILTIN\Administrators enabled. LocalService and NetworkService are not privileged by SID. A UAC-filtered administrator has that group marked deny-only, and deny-only groups are dropped when the identity is captured, so such a caller is correctly reported as unprivileged. Domain group memberships (Domain Admins and friends) are deliberately not consulted: they say nothing about what this token may do on this machine.

func (Identity) IsWindows

func (i Identity) IsWindows() bool

IsWindows reports whether this identity is a Windows principal (SID-based) rather than a Unix uid/gid principal.

func (Identity) Known added in v0.83.0

func (i Identity) Known() bool

Known reports whether this identity came from a kernel credential read.

func (Identity) SameUser added in v0.78.0

func (i Identity) SameUser(other Identity) bool

SameUser reports whether two identities are the same local principal. Only the account is compared: the group set and the elevation flag describe what a token may do, not who it belongs to. A SID on either side decides the comparison, so a Windows principal never matches a Unix one on the UID both happen to leave at zero. An identity the kernel did not vouch for matches nobody, so the zero Identity never matches uid 0.

func (Identity) String

func (i Identity) String() string

String renders the identity for audit logs and denial messages.

type MethodPolicy added in v0.83.0

type MethodPolicy struct {
	Level          AuthzLevel
	Rules          []Rule
	Audit          bool
	TargetsProfile bool

	// Action reads as the subject of a refusal message ("claiming a profile").
	Action string
}

MethodPolicy is what a method requires to be authorized and then handled.

type Principal added in v0.83.0

type Principal struct {
	Kind  PrincipalKind
	Value string
}

Principal is a parsed owner entry from a profile's Owners list.

func ParsePrincipal added in v0.83.0

func ParsePrincipal(s string) (Principal, bool)

ParsePrincipal parses a "kind:value" owner string. Returns false for empty values or unknown kinds so malformed entries are ignored rather than trusted.

func ValidatePrincipal added in v0.83.0

func ValidatePrincipal(s string) (Principal, error)

ValidatePrincipal checks an owner principal typed by a user, as opposed to one read back off disk.

func (Principal) Matches added in v0.83.0

func (p Principal) Matches(id Identity) bool

Matches reports whether a kernel-attested caller satisfies this stored owner principal.

A principal is a config value, not a caller, so it is never converted into an Identity.

func (Principal) String added in v0.83.0

func (p Principal) String() string

String renders the principal as the kind:value form it is stored in.

func (Principal) Validate added in v0.83.0

func (p Principal) Validate() error

Validate reports whether a principal is one a caller on this platform could ever hold.

type PrincipalKind added in v0.83.0

type PrincipalKind string

PrincipalKind is the type of an owner principal.

const (
	KindUID PrincipalKind = "uid" // Unix user ID
	KindGID PrincipalKind = "gid" // Unix group ID
	KindSID PrincipalKind = "sid" // Windows user or group SID
)

type Request added in v0.83.0

type Request struct {
	Identity Identity
	State    DaemonState
	Level    AuthzLevel
	Target   string
	Method   string
	Msg      any
}

Request is what a rule decides on: the authorization plus the state and the message, which only the gate needs.

type Rule added in v0.83.0

type Rule func(Request) error

Rule is an additional constraint beyond the method's level, for example checking permissions on a field of a message. Every rule on a method must pass.

func RequireLevel added in v0.83.0

func RequireLevel(want AuthzLevel) Rule

RequireLevel builds a rule from a level, for composing inside another rule.

type Target added in v0.83.0

type Target struct {
	Path  string
	Owned bool
	// UnOwned reports that the resolved profile records no owner.
	UnOwned bool
	// Handle is the resolved profile's ID, which a refusal names in the command
	// it hands the caller. A request that named nothing still has one.
	Handle string
}

Target is the profile a request resolved to.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL