Documentation
¶
Overview ¶
Package tunnel implements secure access tunneling for plexd mesh nodes.
Index ¶
- Constants
- Variables
- func GenerateHostKey() (ssh.Signer, error)
- func HostKeyFingerprint(signer ssh.Signer) string
- func HostKeyPath(dataDir string) string
- func LoadOrGenerateHostKey(dataDir string, logger *slog.Logger) (ssh.Signer, error)
- func ParseSessionSigningPublicKey(s string) (ed25519.PublicKey, error)
- func RunSessionHelper(conn *net.UnixConn, keys []ed25519.PublicKey, logger *slog.Logger) error
- func TerminatedByFromReason(reason string) string
- type ClosedSessionInfo
- type Config
- type Dispatcher
- type Ed25519JWTVerifier
- type JWTVerifier
- type K8sProxy
- type LaunchRequest
- type MeshServer
- type SSHCommandReporter
- type SSHServer
- type SSHServerConfig
- type SSHSessionDeps
- type Session
- type SessionActivityReporter
- type SessionConnector
- type SessionHelperClient
- type SessionLauncher
- type SessionManager
- func (m *SessionManager) ActiveCount() int
- func (m *SessionManager) ActiveSessions() map[string]time.Time
- func (m *SessionManager) CloseSession(sessionID, reason string) *ClosedSessionInfo
- func (m *SessionManager) ConnectSSHSession(sessionID, connectionID string, dial func(context.Context) (net.Conn, error)) error
- func (m *SessionManager) CreateSession(ctx context.Context, sess api.NodeStateSession) (string, error)
- func (m *SessionManager) SetOnClosed(fn func(sessionID, reason string, info *ClosedSessionInfo))
- func (m *SessionManager) SetSSHSessionDeps(deps SSHSessionDeps)
- func (m *SessionManager) Shutdown()
- type SessionTokenClaims
- type SigningKeySource
Constants ¶
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.
const DefaultMaxSSHSessions = 10
DefaultMaxSSHSessions is the default maximum number of concurrent SSH sessions.
const DefaultMaxSessions = 10
DefaultMaxSessions is the default maximum number of concurrent tunnel sessions.
const DefaultSSHIdleTimeout = 30 * time.Minute
DefaultSSHIdleTimeout is the default idle timeout for SSH connections.
const DefaultSessionHelperSocket = "/run/plexd-session-helper.sock"
DefaultSessionHelperSocket is where plexd-session-helper.socket listens. plexd starts ssh processes through it whenever it exists.
const DefaultTimeout = 30 * time.Minute
DefaultTimeout is the default session timeout.
Variables ¶
var ( // ErrSessionNotLive is returned for an id no live session carries: one that // was never provisioned here, or one that already closed. ErrSessionNotLive = errors.New("tunnel: no live session with this id") // ErrNotSSHSession is returned for a live session of another kind. ErrNotSSHSession = errors.New("tunnel: the session is not an ssh session") // ErrSSHConnectionLimit is returned while the session holds as many // connections, open or still opening, as it may. ErrSSHConnectionLimit = errors.New("tunnel: the ssh session is at its connection limit") )
The refusals of ConnectSSHSession that come before it opens anything, beside ErrTunnelingDisabled, ErrSSHSessionsUnsupported and ErrSSHSessionsDisabled.
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.
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.
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.
var ErrSessionHelperRefused = errors.New("tunnel: session helper refused")
ErrSessionHelperRefused wraps the reason the session helper gave for not starting a process.
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 ¶
GenerateHostKey generates a new Ed25519 keypair and returns it as an ssh.Signer.
func HostKeyFingerprint ¶ added in v0.4.0
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
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 ¶
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
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
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
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
SSHSessionsAllowed reports whether the node serves mediated ssh sessions: true unless ssh_sessions_enabled is explicitly false.
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) SessionConnectHandler ¶ added in v0.20.0
func (d *Dispatcher) SessionConnectHandler(connector SessionConnector) api.EventHandler
SessionConnectHandler returns the handler for the session_connect event. The SSE stream has verified the envelope's signature and freshness before any handler runs, and the payload names the ssh session a client attached to and the connection the control plane waits for, so the handler opens that connection with connector and serves the session's SSH login on it (SessionManager.ConnectSSHSession).
The open runs on its own goroutine, because it blocks on the control plane and the SSE stream dispatches its handlers one after another. It logs one line per event with its outcome. Nothing is opened for a session that is not live here, for one this node does not serve, or past the session's connection limit.
DECISION: the handler does not judge the payload's expires_at against the node's clock. The verifier admits envelopes up to DefaultStalenessWindow off, while the control plane waits seconds for the connection, so a node clock a few seconds ahead would drop every request. The control plane refuses a late connection with 404 session_connection_not_found, which the failure line carries. A failed open is not retried either: the next attach asks for a new connection.
A payload that does not decode, or that names no session or no connection, opens nothing; the handler returns the error, which the event dispatcher logs. The event carries no desired state, so it never triggers a reconcile.
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 ¶
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 ¶
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.
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 tcp session listener binds (an ssh session binds none) — 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.
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.
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) Counters ¶ added in v0.2.0
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
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 ¶
ListenAddr returns the listener address or empty string if not started.
func (*Session) Start ¶
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 session is up. For a tcp entry listenerEndpoint is the bound listener address, the operator's only route to the listener; an ssh session binds none, so it is empty, and the row tells the control plane the session is ready to serve the connections it asks for. Either way the error is returned rather than swallowed: a dropped row leaves a session nobody can reach. The matching session_ended row is emitted from the SessionManager's on-closed callback, not through here.
type SessionConnector ¶ added in v0.20.0
type SessionConnector interface {
OpenSessionConnection(ctx context.Context, sessionID, connectionID string) (net.Conn, error)
}
SessionConnector opens the connection a session_connect event asked for, to the control plane, and returns it carrying the session's SSH bytes. api.ControlPlane.OpenSessionConnection, bound to the node's id, is the production implementation.
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) ConnectSSHSession ¶ added in v0.20.0
func (m *SessionManager) ConnectSSHSession(sessionID, connectionID string, dial func(context.Context) (net.Conn, error)) error
ConnectSSHSession serves one connection of the live ssh session sessionID, the one a session_connect event named connectionID: dial opens it to the control plane, and the session runs its SSH login on it under the session's own limits and lifetime. Every refusal comes before dial runs: tunneling or ssh sessions switched off (ErrTunnelingDisabled, ErrSSHSessionsDisabled), a platform without ssh sessions (ErrSSHSessionsUnsupported), an id no live session carries (ErrSessionNotLive), a session of another kind (ErrNotSSHSession), or one already holding its connection limit (ErrSSHConnectionLimit). A failed dial is returned wrapped. Closing the session cancels a dial in flight.
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, bound on the mesh address. ssh entries become an SSH session served over the connections plexd opens to the control plane on request (see ConnectSSHSession), so they bind nothing and return an empty address, 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:
- 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);
- the header's alg is EdDSA (ErrSessionTokenAlgorithm);
- the signature verifies against one of keys; nil or empty keys verify nothing (ErrSessionTokenSignature);
- kind and target.kind are both "ssh" (ErrSessionTokenKind);
- jti equals sessionID (ErrSessionTokenSession);
- nbf <= now (ErrSessionTokenNotYetValid) and now < exp, where a missing exp counts as expired (ErrSessionTokenExpired);
- target.user equals user (ErrSessionTokenUser).
There is no clock-skew leeway: the contract states none.
type SigningKeySource ¶ added in v0.8.0
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.
Source Files
¶
- config.go
- connect.go
- dispatch.go
- hostkey.go
- jwt_ed25519.go
- k8s_proxy.go
- manager.go
- mesh_server.go
- pty_linux.go
- pty_unix.go
- reporter.go
- revoke.go
- session.go
- session_helper_client_unix.go
- session_helper_server_linux.go
- session_helper_server_unix.go
- session_token.go
- ssh_channels.go
- ssh_deps.go
- ssh_server.go
- ssh_session_unix.go