orthrus

package
v0.0.0-...-faf1238 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 42 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 orthrus implements the Orthrus reverse-proxy agent server. It manages WebSocket connections from remote Orthrus agents, multiplexes streams via Yamux, and provides the Muzzle Docker socket filter.

Index

Constants

View Source
const BcryptCost = 12

BcryptCost is the work factor used for every agent key hash.

Variables

This section is empty.

Functions

func BcryptInput

func BcryptInput(token string) []byte

BcryptInput returns the bytes fed to bcrypt for a key. Keys of 72 bytes or more are truncated so the stored hash and the verification use the same input.

func HostSideAddrs

func HostSideAddrs() []netip.Addr

HostSideAddrs returns the addresses that name the host side of the networks this process is attached to: each IPv4 default gateway from the route table, and the first address of each directly attached IPv4 network, where Docker places its bridge gateway. It returns nil when neither source can be read.

func LocalNetworks

func LocalNetworks() ([]LocalNetwork, netip.Addr, BindSource)

LocalNetworks is LocalNetworks on the real host.

Types

type AgentSession

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

AgentSession represents a single connected Orthrus agent's active WebSocket and Yamux session.

func NewAgentSession

func NewAgentSession(agentUUID, agentName string, writeEnabled bool, auditLogger AuditLogger, conn *websocket.Conn) (*AgentSession, error)

NewAgentSession wraps the WebSocket connection in a Yamux server session. The session owns conn: Close tears the WebSocket down.

func (*AgentSession) Close

func (s *AgentSession) Close() error

Close terminates the proxy listener, cancels the context, and closes the Yamux session (which also closes the underlying WebSocket via wsNetConn).

func (*AgentSession) GetExternalProxyStatus

func (s *AgentSession) GetExternalProxyStatus() ExternalProxyStatus

GetExternalProxyStatus returns the runtime state of the external proxy for this session.

func (*AgentSession) GetProxyAddr

func (s *AgentSession) GetProxyAddr() string

GetProxyAddr returns the local address of the proxy listener for this session. Returns an empty string when no proxy port has been allocated (PR 5).

func (*AgentSession) IsAlive

func (s *AgentSession) IsAlive() bool

IsAlive returns true if the Yamux session has not been closed.

func (*AgentSession) StartDockerProxy

func (s *AgentSession) StartDockerProxy() error

StartDockerProxy allocates an ephemeral loopback TCP listener and starts accepting connections. Each accepted connection is tunnelled to the agent's Docker socket via a new yamux stream of type streamTypeDocker (0x01). Returns an error if the OS cannot allocate a port, if the proxy is already running for this session (idempotency guard), or if the session is closed.

func (*AgentSession) StartExternalProxy

func (s *AgentSession) StartExternalProxy(port int, bind string) error

StartExternalProxy binds an HTTP listener on the address selected by bind (see ResolveBind) and port. Requests reverse-proxy through the existing loopback proxy to the agent's Docker socket, filtered by Muzzle. A port of 0 is a no-op (returns nil). Returns an error if the loopback proxy is not yet running, if an external proxy is already active, if the session is closed, if bind cannot be resolved to a local address, or if the OS cannot bind it.

type AuditLogger

type AuditLogger interface {
	LogAudit(a *models.SecurityAudit) error
}

AuditLogger is the narrow interface Muzzle depends on for write-path audit logging. Satisfied by *services.SecurityService at the call site in session.go, where the concrete type is available. Muzzle cannot import services directly: services/orthrus_service.go already imports "github.com/Wikid82/charon/backend/internal/orthrus", so an orthrus → services import would create a cycle.

type BindMode

type BindMode string

BindMode is the kind of listen setting an agent's external proxy uses.

const (
	// BindModeAuto picks Charon's primary network address (see automaticBind).
	BindModeAuto BindMode = "auto"
	// BindModeAll listens on every interface (0.0.0.0 or ::).
	BindModeAll BindMode = "all"
	// BindModeAddress listens on one exact local address.
	BindModeAddress BindMode = "address"
	// BindModeSubnet listens on the first local address inside a prefix.
	BindModeSubnet BindMode = "subnet"
)

func ParseBindSetting

func ParseBindSetting(s string) (mode BindMode, addr netip.Addr, prefix netip.Prefix, err error)

ParseBindSetting validates a stored or submitted listen setting. "" is automatic; "0.0.0.0" and "::" are all interfaces; an IP literal is one address; a prefix is a subnet and is returned masked.

type BindSource

type BindSource string

BindSource records how the listen address was chosen.

const (
	BindSourceDefaultRoute     BindSource = "default_route"
	BindSourceSingleInterface  BindSource = "single_interface"
	BindSourceLoopbackFallback BindSource = "loopback_fallback"
	BindSourceConfigured       BindSource = "configured"
)

type ExternalProxyStatus

type ExternalProxyStatus struct {
	ConfiguredPort int      `json:"configured_port"` // port passed to StartExternalProxy
	ActivePort     int      `json:"active_port"`     // actual bound port (0 if not active)
	BoundAddress   string   `json:"bind_address"`    // actual listener address, e.g. "172.18.0.4:9999"
	ActiveBind     string   `json:"active_bind"`     // listen setting the session was started with
	BindMode       BindMode `json:"bind_mode"`       // how ActiveBind was interpreted; "" if unresolved
	BindFallback   bool     `json:"bind_fallback"`   // automatic mode fell back to loopback
	Active         bool     `json:"active"`
	WriteEnabled   bool     `json:"write_enabled"`   // negotiated value for this live session
	Error          string   `json:"error,omitempty"` // last start error, if any
}

ExternalProxyStatus describes the runtime state of the external Docker proxy for this agent session. It intentionally carries no connection-string/hostname field: AgentSession is a long-lived per-tunnel object with no request-scoped data (no *gin.Context), so it cannot resolve a caller-appropriate hostname. That resolution happens one layer up, in OrthrusHandler.GetProxyStatus, which does have request context.

type InstallSnippets

type InstallSnippets struct {
	DockerCompose       string `json:"docker_compose"`
	KubernetesDaemonSet string `json:"kubernetes_daemonset"`
}

InstallSnippets contains per-platform install templates for an Orthrus agent. Each snippet uses the literal placeholder "<AUTH_KEY>" wherever the real key must be substituted by the user. The real key is only returned once at provisioning time and is never embedded in snippet responses.

type InternalCA

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

InternalCA is Charon's lightweight certificate authority used to issue mTLS certificates to registered Orthrus agents.

func NewInternalCA

func NewInternalCA(dataRoot string) (*InternalCA, error)

NewInternalCA loads an existing CA from disk or generates a new one. Key and certificate are stored under {dataRoot}/keys/.

func (*InternalCA) CACertPEM

func (ca *InternalCA) CACertPEM() []byte

CACertPEM returns the PEM-encoded CA certificate.

func (*InternalCA) SignCSR

func (ca *InternalCA) SignCSR(csrPEM []byte, validity time.Duration) ([]byte, error)

SignCSR parses the PEM-encoded CSR, signs it with the CA key, and returns the PEM-encoded certificate valid for the given duration.

type LocalNetwork

type LocalNetwork struct {
	Interface string `json:"interface"`
	Address   string `json:"address"`
	CIDR      string `json:"cidr"`
	Primary   bool   `json:"primary"`
}

LocalNetwork is one address Charon can bind the external proxy to.

type Muzzle

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

Muzzle is an http.Handler wrapper around the Docker socket proxy. Read-only sessions (writeEnabled false) are restricted to a curated allowlist of read-only, non-destructive GET endpoints. Write-enabled sessions get the full, unrestricted Docker Engine API: every request is forwarded as-is (rate-limited and audited), with no per-endpoint or per-field restriction.

This is a deliberate operator trust model, not an oversight: write mode is opt-in per agent (OrthrusAgent.WriteEnabled), gated behind an explicit typed-confirmation UI step that documents this is equivalent to giving the connected tool full control of the Docker host — see AgentWriteModeDialog on the frontend. Every write-mode request is still audited (auditAllowed/auditRateLimited), so an operator who enables write mode retains a full trace of what was done, even though nothing about the request content itself is inspected or restricted.

func NewMuzzle

func NewMuzzle(next http.Handler, writeEnabled bool, writeLimiter *rate.Limiter, auditLogger AuditLogger, agentUUID string) *Muzzle

NewMuzzle wraps handler with the Docker socket proxy filter.

writeEnabled, writeLimiter, auditLogger, and agentUUID govern write-mode behavior (see the Muzzle doc comment). writeEnabled is captured once, at construction time, and never re-checked against the database on a per-request basis — StartExternalProxy constructs a new Muzzle per AgentSession using the value negotiated at connect time, so toggling the DB flag only takes effect on the agent's next reconnect. Re-reading it per-request would both reintroduce a TOCTOU-like inconsistency with that reconnect-to-apply guarantee and add a DB round-trip to the hot proxy path.

func (*Muzzle) ServeHTTP

func (m *Muzzle) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

Read-only sessions (m.writeEnabled false) only forward GET requests to allowlisted paths, with HEAD permitted for /_ping (Docker client health checks) — every other request receives 403 Forbidden. This half is unchanged from before write mode existed.

Write-enabled sessions forward every request unconditionally — no endpoint or request-body restriction (see the Muzzle doc comment for why) — but only mutating methods (POST/PUT/PATCH/DELETE) go through the rate limiter and audit log (see forwardWrite). GET/HEAD are forwarded directly, same as a read-only session, un-rate-limited and unaudited: m.writeLimiter is sized for occasional mutation bursts (see writeLimiterBurst's doc comment in session.go — "one full update cycle is exactly 5 write calls"), not for a Docker client's routine container list/inspect polling, which can easily run many times a minute. Routing that read traffic through the same limiter starved it out entirely once the burst was spent, intermittently 429ing GET /containers/json and making containers appear to vanish from any tool polling this proxy — a real regression this fixes, not a hypothetical one.

type OrthrusServer

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

OrthrusServer manages incoming agent WebSocket connections and tracks active sessions indexed by agent UUID.

func NewOrthrusServer

func NewOrthrusServer(db *gorm.DB, ca *InternalCA) (*OrthrusServer, error)

NewOrthrusServer creates an OrthrusServer with the given database and internal CA.

func (*OrthrusServer) DisconnectAgent

func (s *OrthrusServer) DisconnectAgent(agentUUID string) error

DisconnectAgent closes the active session and removes it from the session map.

func (*OrthrusServer) GetExternalProxyStatus

func (s *OrthrusServer) GetExternalProxyStatus(agentUUID string) (ExternalProxyStatus, bool)

GetExternalProxyStatus returns the external proxy status for a connected agent. Returns (ExternalProxyStatus{}, false) when no active session exists.

func (*OrthrusServer) GetProxyAddr

func (s *OrthrusServer) GetProxyAddr(agentUUID string) (string, bool)

GetProxyAddr returns the proxy listener address for a connected agent. Returns ("", false) when no active session or no proxy port is allocated.

func (*OrthrusServer) GetSession

func (s *OrthrusServer) GetSession(agentUUID string) (*AgentSession, bool)

GetSession returns the active AgentSession for the given UUID.

func (*OrthrusServer) HandleWebSocket

func (s *OrthrusServer) HandleWebSocket(c *gin.Context)

HandleWebSocket is the Gin handler for GET /api/v1/ws/orthrus/connect. It authenticates the agent via bearer token, upgrades the connection to WebSocket, and starts session management goroutines.

func (*OrthrusServer) LiveListenerPorts

func (s *OrthrusServer) LiveListenerPorts() []int

LiveListenerPorts returns the ports Charon listens on for connected agents: the loopback proxy port of each session and its external proxy port while active. A nil server reports none.

func (*OrthrusServer) SetAuditLogger

func (s *OrthrusServer) SetAuditLogger(al AuditLogger)

SetAuditLogger wires the write-path audit logger used by every AgentSession this server creates from this point forward. Called once at startup (routes.go) with the concrete *services.SecurityService, which satisfies the AuditLogger interface structurally — orthrus never imports services directly (see the AuditLogger doc comment in muzzle.go for why).

func (*OrthrusServer) SetListenerStartedHook

func (s *OrthrusServer) SetListenerStartedHook(fn func())

SetListenerStartedHook registers fn to run after a connected agent's proxy listeners are registered, so that a config that depends on the live ports can be re-evaluated. It runs on the connection's goroutine and must not block. Set it at startup; nil clears it.

func (*OrthrusServer) Stop

func (s *OrthrusServer) Stop()

Stop cancels the server context, closes all active agent sessions, and waits for all background goroutines to exit. Closing sessions explicitly ensures yamux's internal goroutines terminate promptly regardless of the underlying transport state, which prevents flaky TempDir cleanup failures in tests.

Jump to

Keyboard shortcuts

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