tunnel

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 34 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tunnel implements secure access tunneling for plexd mesh nodes.

Index

Constants

View Source
const (
	// LaunchModeShell starts the user's login shell.
	LaunchModeShell = "shell"
	// LaunchModeExec runs one command through the user's shell.
	LaunchModeExec = "exec"
)

The modes of a LaunchRequest.

View Source
const DefaultMaxSSHSessions = 10

DefaultMaxSSHSessions is the default maximum number of concurrent SSH sessions.

View Source
const DefaultMaxSessions = 10

DefaultMaxSessions is the default maximum number of concurrent tunnel sessions.

View Source
const DefaultSSHIdleTimeout = 30 * time.Minute

DefaultSSHIdleTimeout is the default idle timeout for SSH connections.

View Source
const DefaultSessionHelperSocket = "/run/plexd-session-helper.sock"

DefaultSessionHelperSocket is where plexd-session-helper.socket listens. plexd starts ssh processes through it whenever it exists.

View Source
const DefaultTimeout = 30 * time.Minute

DefaultTimeout is the default session timeout.

Variables

View Source
var (
	ErrSessionTokenMalformed   = errors.New("tunnel: session token: malformed")
	ErrSessionTokenAlgorithm   = errors.New("tunnel: session token: algorithm is not EdDSA")
	ErrSessionTokenSignature   = errors.New("tunnel: session token: signature does not verify against a trusted key")
	ErrSessionTokenKind        = errors.New("tunnel: session token: not an ssh session token")
	ErrSessionTokenSession     = errors.New("tunnel: session token: issued for another session")
	ErrSessionTokenNotYetValid = errors.New("tunnel: session token: not yet valid")
	ErrSessionTokenExpired     = errors.New("tunnel: session token: expired")
	ErrSessionTokenUser        = errors.New("tunnel: session token: issued for another user")
)

The reasons VerifySessionToken refuses a token. They are returned bare, never wrapped, so no decoder message and no byte of the token reaches an error text or a log line.

View Source
var ErrSSHSessionsDisabled = errors.New("tunnel: ssh sessions are disabled on this node")

ErrSSHSessionsDisabled is returned by CreateSession for an ssh entry when the node refuses ssh sessions (tunnel.ssh_sessions_enabled: false). Like ErrTunnelingDisabled it holds for the life of the process, so the dispatcher settles the entry instead of retrying it.

View Source
var ErrSSHSessionsUnsupported = errors.New("tunnel: ssh sessions are not supported on this platform")

ErrSSHSessionsUnsupported is returned by CreateSession for an ssh entry on a platform without an ssh session listener.

View Source
var ErrSessionHelperRefused = errors.New("tunnel: session helper refused")

ErrSessionHelperRefused wraps the reason the session helper gave for not starting a process.

View Source
var ErrTunnelingDisabled = errors.New("tunnel: tunneling is disabled")

ErrTunnelingDisabled is returned by CreateSession when tunneling is switched off in the node's configuration. It is a sentinel because that refusal is permanent for the life of the process, and a caller matching it with errors.Is can settle the session instead of retrying it on every pull.

Functions

func GenerateHostKey

func GenerateHostKey() (ssh.Signer, error)

GenerateHostKey generates a new Ed25519 keypair and returns it as an ssh.Signer.

func HostKeyFingerprint added in v0.4.0

func HostKeyFingerprint(signer ssh.Signer) string

HostKeyFingerprint renders the host key's public half as the canonical OpenSSH SHA-256 fingerprint, `SHA256:<base64>` with the padding omitted — the form `ssh-keygen -l` prints and the form the capability manifest's optional ssh_host_key_fingerprint field carries.

func HostKeyPath added in v0.4.0

func HostKeyPath(dataDir string) string

HostKeyPath returns the path LoadOrGenerateHostKey reads and writes the node's SSH host key at. The integrity verifier watches the same file, so the name has one owner rather than two spellings that can drift apart.

func LoadOrGenerateHostKey

func LoadOrGenerateHostKey(dataDir string, logger *slog.Logger) (ssh.Signer, error)

LoadOrGenerateHostKey loads an existing Ed25519 host key from dataDir, or generates and persists a new one if none exists.

func ParseSessionSigningPublicKey added in v0.8.0

func ParseSessionSigningPublicKey(s string) (ed25519.PublicKey, error)

ParseSessionSigningPublicKey parses the standard-base64 Ed25519 public key that tunnel.session_signing_public_key and the helper's pin file hold. Surrounding whitespace, a trailing newline included, is ignored.

func RunSessionHelper added in v0.8.0

func RunSessionHelper(conn *net.UnixConn, keys []ed25519.PublicKey, logger *slog.Logger) error

RunSessionHelper serves one request of the session helper protocol on conn (see SessionHelperClient) and verifies it against keys: the session token, the mode against the token's allowed commands, and the login user against the node's local accounts (loginUserLookup). It then starts the shell or command as that user, in its own session and process group, with the received descriptors as its standard streams, and answers with its exit status.

It returns nil once it wrote a response, a refusal included, and an error when it could not read a request or write the response. Every received descriptor is closed before it returns.

DECISION: the helper kills what is left of the process group once the main process exited, so a command cannot leave a process behind that outlives the session. Under socket activation systemd also kills the instance's cgroup (KillMode=control-group).

func TerminatedByFromReason added in v0.2.0

func TerminatedByFromReason(reason string) string

TerminatedByFromReason maps an internal session close reason to the wire terminated_by enum reported on a session_ended row: reasonExpired becomes ttl_expired, reasonIdle becomes idle_timeout, reasonRevoked becomes operator_revoke, and every other reason becomes plexd_close.

api.TerminatedByOperatorRevoke is produced only for reasonRevoked, which only the session_revoked handler passes: the agent contract defines operator_revoke as a close caused by that event, and the event is signed and names the session. A drain never produces it. A revocation the node learns only from the pull reaches it as the absence of the entry, which is indistinguishable from a control plane that failed to serve the block, and asserting a revocation on that evidence would write a confidently wrong answer into the audit trail on every degraded pull.

Types

type ClosedSessionInfo

type ClosedSessionInfo struct {
	Kind       string
	Duration   time.Duration
	TargetHost string
	TargetPort int
	BytesIn    int64
	BytesOut   int64
}

ClosedSessionInfo contains metadata about a session that was closed. Kind is the session's api.SessionKind* value; the target and the byte counters are set for tcp sessions only.

type Config

type Config struct {
	// Enabled controls whether tunneling is active.
	// Default: true (set by ApplyDefaults).
	Enabled bool `yaml:"enabled"`

	// MaxSessions is the maximum number of concurrent tunnel sessions.
	// Default: 10
	MaxSessions int `yaml:"max_sessions"`

	// DefaultTimeout is the default/maximum session timeout.
	// Default: 30m
	DefaultTimeout time.Duration `yaml:"default_timeout"`

	// SSHListenAddr is the address for the SSH mesh server to listen on.
	// If empty, the SSH server is not started.
	SSHListenAddr string `yaml:"ssh_listen_addr"`

	// HostKeyDir is the directory for storing the SSH host key.
	// If empty, a transient key is generated (not persisted).
	HostKeyDir string `yaml:"host_key_dir"`

	// SSHSessionsEnabled lets the node refuse mediated ssh sessions while it
	// keeps serving tcp ones. nil means allowed; read it through
	// SSHSessionsAllowed.
	SSHSessionsEnabled *bool `yaml:"ssh_sessions_enabled"`

	// SessionSigningPublicKey is the standard-base64 Ed25519 key the session
	// helper verifies ssh session tokens against. When set it wins over the
	// key the helper pins from identity.json on its first run.
	SessionSigningPublicKey string `yaml:"session_signing_public_key"`
}

Config holds the configuration for secure access tunneling.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults sets default values for zero-valued fields. On a zero-valued Config, Enabled defaults to true. To disable tunneling, set Enabled=false before or after calling ApplyDefaults.

func (*Config) SSHSessionsAllowed added in v0.8.0

func (c *Config) SSHSessionsAllowed() bool

SSHSessionsAllowed reports whether the node serves mediated ssh sessions: true unless ssh_sessions_enabled is explicitly false.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that configuration values are within acceptable ranges.

type Dispatcher added in v0.3.0

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

Dispatcher consumes the sessions block of the reconciliation pull and holds the node's mediated-access listeners level with it. The block is desired state, not a delivery queue like the executions block: an entry stands for as long as the session is valid, and its disappearance is the teardown signal. A revocation the control plane announces in a verified session_revoked event is closed first, by the handler SessionRevokedHandler returns; for every other revocation, and for a hard expiry, the absence is the only signal there is — there is no revocation callback to answer and no terminal status to report.

tcp sessions are provisioned everywhere, and ssh sessions on Linux and macOS. A k8s entry, and an ssh entry elsewhere, is decoded and settled as unsupported: one warning, no listener, no activity row.

Handle is not safe for concurrent use. It is invoked only from the reconcile goroutine, one cycle at a time, so the maps only it touches need no mutex. The handler SessionRevokedHandler returns runs on the SSE goroutine, concurrently with Handle; it touches only the SessionManager, which locks for itself, and the revoked set, which revokedMu guards.

The pass carries no dispatch budget, unlike the executions block's: it is bounded by the live sessions the manager caps at MaxSessions plus the length of the block, and its only network call is a single bounded activity post per session whose started row is still outstanding.

func NewDispatcher added in v0.3.0

func NewDispatcher(manager *SessionManager, reporter SessionActivityReporter, logger *slog.Logger) *Dispatcher

NewDispatcher creates a Dispatcher that provisions the pull's sessions block through manager and reports each started listener through reporter.

func (*Dispatcher) Handle added in v0.3.0

func (d *Dispatcher) Handle(ctx context.Context, desired *api.NodeStateSnapshot)

Handle reconciles the snapshot's sessions block: it first tears down every live session the block no longer carries, then provisions the entries it does not yet serve, in block order, and finally reports the listeners it brought up. Its signature matches reconcile.DispatchHandler.

func (*Dispatcher) SessionRevokedHandler added in v0.18.0

func (d *Dispatcher) SessionRevokedHandler(trigger api.ReconcileTrigger) api.EventHandler

SessionRevokedHandler returns the handler for the session_revoked event. The SSE stream has verified the envelope's signature and freshness before any handler runs, and the payload names the session the control plane revoked, so the handler closes that session when it is live here. Its session_ended row reports the payload's revoke_reason, mapped by closeReasonForRevocation: operator_revoke for the operator-driven reasons, ttl_expired and idle_timeout for the sweeper's.

The close runs on its own goroutine, because it blocks on the session's drain and on the bounded session_ended post, and the SSE stream dispatches its handlers one after another. trigger fires after the close returns, so the pull it starts cannot drain the session first and report it as plexd_close. The pull still runs: it is the teardown for every revocation whose event never arrives.

A payload that does not decode, or whose session_id is empty or differs from its jti, closes nothing. The handler still triggers the reconcile and returns the error, which the event dispatcher logs. A missing or unrecognised revoke_reason still closes the session and reports operator_revoke, because the agent contract defines that value as a close caused by this event.

type Ed25519JWTVerifier

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

Ed25519JWTVerifier verifies compact JWS tokens (alg=EdDSA) using an Ed25519 public key. It validates the signature and checks the "exp" claim without relying on any external JWT library.

func NewEd25519JWTVerifier

func NewEd25519JWTVerifier(publicKey ed25519.PublicKey) *Ed25519JWTVerifier

NewEd25519JWTVerifier creates a new verifier with the given Ed25519 public key.

func (*Ed25519JWTVerifier) Verify

func (v *Ed25519JWTVerifier) Verify(token string) error

Verify validates a compact JWS token (header.payload.signature). It checks the Ed25519 signature over the signing input and verifies the "exp" claim has not elapsed.

type JWTVerifier

type JWTVerifier interface {
	Verify(token string) error
}

JWTVerifier validates JWT tokens for SSH authentication.

type K8sProxy

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

K8sProxy is a reverse proxy that forwards HTTP requests to a Kubernetes API server.

func NewK8sProxy

func NewK8sProxy(targetURL string, tlsConfig *tls.Config, logger *slog.Logger) (*K8sProxy, error)

NewK8sProxy creates a K8sProxy targeting the given API server URL. If tlsConfig is non-nil, it is used for TLS connections to the API server.

func (*K8sProxy) Handler

func (p *K8sProxy) Handler() http.Handler

Handler returns the proxy as an http.Handler.

func (*K8sProxy) ServeHTTP

func (p *K8sProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler, forwarding requests to the K8s API server.

type LaunchRequest added in v0.8.0

type LaunchRequest struct {
	Version   int    `json:"v"`
	SessionID string `json:"session_id"`
	User      string `json:"user"`
	Token     string `json:"token"`
	Mode      string `json:"mode"`
	Command   string `json:"command,omitempty"`
	Term      string `json:"term,omitempty"`
	PTY       bool   `json:"pty"`
}

LaunchRequest is what plexd asks the session helper to start. It travels as one JSON line, with the process's file descriptors as SCM_RIGHTS ancillary data. Token is the session token the client logged in with; the helper verifies it again and takes the allowed commands from it, so a request plexd made up is refused.

type MeshServer

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

MeshServer composes the SSH mesh server with the existing SessionManager, managing their lifecycle together.

func NewMeshServer

func NewMeshServer(cfg Config, meshIP string, hostKey ssh.Signer, verifier JWTVerifier, logger *slog.Logger) *MeshServer

NewMeshServer creates a MeshServer that manages the SSH server and session manager. meshIP is the node's registered mesh address, which every session listener binds — it is the reachability boundary of an otherwise unauthenticated forward, so it comes from the node identity rather than being guessed from the SSH listen address, which is empty in both documented configurations and would bind every interface on the host. If cfg.SSHListenAddr is empty, the SSH server is not created.

func (*MeshServer) SSHServer

func (m *MeshServer) SSHServer() *SSHServer

SSHServer returns the underlying SSH server, or nil if not configured.

func (*MeshServer) SessionManager

func (m *MeshServer) SessionManager() *SessionManager

SessionManager returns the underlying session manager.

func (*MeshServer) Shutdown

func (m *MeshServer) Shutdown() error

Shutdown gracefully stops the mesh server. Ordering: close SSH listener first, then drain session manager.

func (*MeshServer) Start

func (m *MeshServer) Start(ctx context.Context) error

Start begins the SSH server (if configured) and returns.

type SSHCommandReporter added in v0.8.0

type SSHCommandReporter interface {
	ReportSSHCommandStarted(ctx context.Context, sessionID, command string, startedAt time.Time) error
	ReportSSHCommandExited(ctx context.Context, sessionID, command string, exitCode int, startedAt, completedAt time.Time) error
}

SSHCommandReporter posts the command rows of an ssh session: one when an exec request is about to run, and one when it exited. Both return the post's error: a command runs only once its started row was accepted.

type SSHServer

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

SSHServer is a mesh-facing SSH server that authenticates clients via JWT and provides direct-tcpip channel forwarding.

func NewSSHServer

func NewSSHServer(cfg SSHServerConfig, hostKey ssh.Signer, verifier JWTVerifier, logger *slog.Logger) *SSHServer

NewSSHServer creates a new SSHServer with the given configuration.

func (*SSHServer) Addr

func (s *SSHServer) Addr() string

Addr returns the listener address or empty string if not started.

func (*SSHServer) Shutdown

func (s *SSHServer) Shutdown() error

Shutdown gracefully stops the SSH server.

func (*SSHServer) Start

func (s *SSHServer) Start(ctx context.Context) error

Start begins listening for SSH connections on the configured address.

type SSHServerConfig

type SSHServerConfig struct {
	// MaxSessions is the maximum number of concurrent SSH sessions.
	// Default: 10
	MaxSessions int

	// IdleTimeout is the idle timeout for SSH connections.
	// Default: 30m
	IdleTimeout time.Duration

	// ListenAddr is the address to listen on (mesh IP + port).
	// Required.
	ListenAddr string
}

SSHServerConfig holds the configuration for the SSH mesh server.

func (*SSHServerConfig) ApplyDefaults

func (c *SSHServerConfig) ApplyDefaults()

ApplyDefaults sets default values for zero-valued fields.

func (*SSHServerConfig) Validate

func (c *SSHServerConfig) Validate() error

Validate checks that configuration values are within acceptable ranges.

type SSHSessionDeps added in v0.8.0

type SSHSessionDeps struct {
	HostKey  ssh.Signer
	Keys     SigningKeySource
	Commands SSHCommandReporter
	Launcher SessionLauncher
}

SSHSessionDeps is what the SessionManager needs to serve ssh sessions: the host key the listener presents, the keys session tokens verify against, the reporter for command rows, and the launcher that starts processes. ssh entries are not provisioned until every member is set.

type Session

type Session struct {
	SessionID  string
	TargetHost string
	TargetPort int
	MeshIP     string
	// contains filtered or unexported fields
}

Session represents an active tunnel session with a local TCP listener that forwards connections to a target host through the mesh.

func NewSession

func NewSession(sessionID, targetHost string, targetPort int, meshIP string, expiresAt time.Time, logger *slog.Logger) *Session

NewSession creates a Session with the given parameters.

func (*Session) Close

func (s *Session) Close() error

Close shuts down the session idempotently.

func (*Session) Counters added in v0.2.0

func (s *Session) Counters() (in, out int64)

Counters returns the bytes forwarded in each direction: in is client -> target (operator to target), out is target -> client (target to operator).

func (*Session) IdleFor added in v0.3.0

func (s *Session) IdleFor() time.Duration

IdleFor returns how long the session has gone without observed byte flow. The listener bind counts as the first activity, so a started session never reports the whole time since the process began.

func (*Session) ListenAddr

func (s *Session) ListenAddr() string

ListenAddr returns the listener address or empty string if not started.

func (*Session) Start

func (s *Session) Start(ctx context.Context) (string, error)

Start opens a TCP listener bound to the mesh IP and begins accepting connections. Everything the session runs — the accept loop and, when an idle window is armed, the idle monitor — hangs off the child context Start derives here, which Close cancels; nothing outlives the session.

type SessionActivityReporter added in v0.2.0

type SessionActivityReporter interface {
	ReportSessionStarted(ctx context.Context, entry api.NodeStateSession, listenerEndpoint string) error
}

SessionActivityReporter reports a session's session_started row to the control plane: the tcp row, which carries the target, for a tcp entry, and the ssh lifecycle row for an ssh entry. The session dispatcher posts it once the listener is up, so the row carries the bound listener address. That address is the operator's only route to the listener, so the error is returned rather than swallowed: a dropped row leaves a listener nobody can reach. The matching session_ended row is emitted from the SessionManager's on-closed callback, not through here.

type SessionHelperClient added in v0.8.0

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

SessionHelperClient is the SessionLauncher plexd starts ssh processes through. It reaches the root session helper through its socket, or runs the helper as its own child where no socket exists.

The protocol is one request and one response per connection. plexd writes the LaunchRequest as one JSON line, in a single sendmsg that carries the process's file descriptors as SCM_RIGHTS: the pty slave alone with a pty, else stdin, stdout and stderr. The helper answers with one JSON line, {"exit_status":N} or {"error":"<reason>"}, and closes. plexd shutting down its sending side before the answer means "stop the process"; the answer follows once the process is gone.

func NewSessionHelperClient added in v0.8.0

func NewSessionHelperClient(socketPath string, child func(keys []ed25519.PublicKey) *exec.Cmd, keys SigningKeySource, logger *slog.Logger) *SessionHelperClient

NewSessionHelperClient returns a client that dials socketPath when it is a Unix socket, and otherwise starts child(keys) with one end of a socketpair as its fd 3. An empty socketPath always starts the child: macOS has no helper socket. The child's stderr is plexd's own unless child set one.

func (*SessionHelperClient) Launch added in v0.8.0

func (c *SessionHelperClient) Launch(ctx context.Context, req LaunchRequest, files []*os.File) (int, error)

Launch sends req and files to the session helper and waits for its answer. Every file in files is closed before Launch returns, and right after the send on the path that reaches it.

type SessionLauncher added in v0.8.0

type SessionLauncher interface {
	Launch(ctx context.Context, req LaunchRequest, files []*os.File) (exitStatus int, err error)
}

SessionLauncher starts one shell or command of an ssh session and waits for it. files are the process's standard streams: the pty slave alone when req.PTY is set, else stdin, stdout and stderr. Launch closes every file in files once it has handed them on, on every path, so the caller's ends of the pty and the pipes reach EOF when the process is done. Cancelling ctx stops the process.

type SessionManager

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

SessionManager manages the lifecycle of tunnel sessions.

func NewSessionManager

func NewSessionManager(cfg Config, meshIP string, logger *slog.Logger) *SessionManager

NewSessionManager creates a new SessionManager with default config applied.

func (*SessionManager) ActiveCount

func (m *SessionManager) ActiveCount() int

ActiveCount returns the number of active sessions.

func (*SessionManager) ActiveSessions added in v0.3.0

func (m *SessionManager) ActiveSessions() map[string]time.Time

ActiveSessions returns the live sessions as session id to capped local expiry, in a fresh map taken under the lock. The session dispatcher's teardown pass consumes it: an id the pull's sessions block no longer carries is closed, and the expiry is what tells a revocation apart from a hard expiry — both reach the node as the same absence.

func (*SessionManager) CloseSession

func (m *SessionManager) CloseSession(sessionID, reason string) *ClosedSessionInfo

CloseSession closes and removes a session by ID. Returns session metadata if the session existed, or nil if not found.

func (*SessionManager) CreateSession

func (m *SessionManager) CreateSession(ctx context.Context, sess api.NodeStateSession) (string, error)

CreateSession creates and starts a tunnel session for one entry of the pull's sessions block and returns the bound listener address. tcp entries become a TCP forward to their target. ssh entries become an SSH listener, on Linux and macOS and once SetSSHSessionDeps wired it; they are refused with ErrSSHSessionsUnsupported elsewhere and with ErrSSHSessionsDisabled when the node refuses ssh sessions. Any other kind is not provisionable: the session dispatcher filters the block before calling in, and the kind guard here keeps the manager safe to call on its own. Sessions of both kinds count against MaxSessions together.

func (*SessionManager) SetOnClosed added in v0.2.0

func (m *SessionManager) SetOnClosed(fn func(sessionID, reason string, info *ClosedSessionInfo))

SetOnClosed registers a callback invoked after a session is successfully closed and removed, for every close reason including "shutdown". The callback carries the close reason and the session's final metadata, and is the single path by which a session_ended activity row — TTL expiry, operator revoke, and node shutdown alike — reaches the control plane. Because it is the only carrier of the session's byte counters, skipping it on shutdown would leave the control plane's audit record for every live session without bytes_in, bytes_out, or terminated_by.

func (*SessionManager) SetSSHSessionDeps added in v0.8.0

func (m *SessionManager) SetSSHSessionDeps(deps SSHSessionDeps)

SetSSHSessionDeps wires what ssh sessions need. Until it is called, or while any member is nil, CreateSession refuses ssh entries.

func (*SessionManager) Shutdown

func (m *SessionManager) Shutdown()

Shutdown closes all active sessions, reporting each one through the on-closed callback with reason "shutdown" so its byte counters and a plexd_close terminated_by reach the control plane before the node goes offline.

The on-closed callback performs a blocking, bounded report, so the sessions are closed concurrently: total shutdown latency is then the single slowest report rather than their sum. Closing serially instead would let a slow or unreachable control plane stretch teardown to MaxSessions times the per-report bound, overrunning a typical orchestrator termination grace period.

type SessionTokenClaims added in v0.8.0

type SessionTokenClaims struct {
	SessionID       string
	User            string
	AllowedCommands []string
	NotBefore       time.Time
	Expiry          time.Time
}

SessionTokenClaims is what VerifySessionToken hands back from a token it accepted. AllowedCommands is empty when the token lists no commands, which means the session may run a shell or any command.

func VerifySessionToken added in v0.8.0

func VerifySessionToken(token string, keys []ed25519.PublicKey, sessionID, user string, now time.Time) (SessionTokenClaims, error)

VerifySessionToken checks a mediated ssh session token, the compact JWS the control plane issues for one session, and returns its claims. It checks, in this order, and returns the first failure:

  1. the token is at most 8192 bytes of three non-empty, dot-separated, raw-base64url segments whose header and claims are JSON objects, and nbf and exp are less than 2^53 seconds either side of the epoch (ErrSessionTokenMalformed);
  2. the header's alg is EdDSA (ErrSessionTokenAlgorithm);
  3. the signature verifies against one of keys; nil or empty keys verify nothing (ErrSessionTokenSignature);
  4. kind and target.kind are both "ssh" (ErrSessionTokenKind);
  5. jti equals sessionID (ErrSessionTokenSession);
  6. nbf <= now (ErrSessionTokenNotYetValid) and now < exp, where a missing exp counts as expired (ErrSessionTokenExpired);
  7. target.user equals user (ErrSessionTokenUser).

There is no clock-skew leeway: the contract states none.

type SigningKeySource added in v0.8.0

type SigningKeySource interface {
	TrustedKeys(now time.Time) []ed25519.PublicKey
}

SigningKeySource yields the keys a mediated session token may be signed with at a given instant. *api.Ed25519Verifier satisfies it, so plexd follows the control plane's signing-key rotations without a second copy of the keys.

Jump to

Keyboard shortcuts

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