397 lines
17 KiB
Go
397 lines
17 KiB
Go
// Command rvbox is the RVBox client daemon and Windows service executable.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"runtime"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1"
|
|
"github.com/rvbox/rvbox/internal/agentproto"
|
|
"github.com/rvbox/rvbox/internal/client/agent"
|
|
"github.com/rvbox/rvbox/internal/client/spool"
|
|
clientwindows "github.com/rvbox/rvbox/internal/client/supervisor/windows"
|
|
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
|
"github.com/rvbox/rvbox/internal/config"
|
|
"github.com/rvbox/rvbox/internal/domain"
|
|
"github.com/rvbox/rvbox/internal/observability"
|
|
"google.golang.org/protobuf/types/known/timestamppb"
|
|
)
|
|
|
|
// buildVersion is set by scripts/release for published artifacts.
|
|
var buildVersion = "dev"
|
|
|
|
func main() {
|
|
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
|
|
fmt.Fprintln(os.Stderr, "rvbox:", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
var nativeTestContextFailures map[clientwindows.ExecutionContext]bool
|
|
|
|
// A single daemon process owns this reconciled-session fact. The local tray
|
|
// reads it without requiring the optional observability HTTP listener.
|
|
var clientSessionReady atomic.Bool
|
|
|
|
// bootstrapServerURL is set only for a packaged Windows installer. A fresh
|
|
// machine has no service connection from which it could discover this value,
|
|
// so release packaging must deliberately supply the intended WSS endpoint.
|
|
var bootstrapServerURL string
|
|
|
|
// run is deliberately a small mode dispatcher. The SCM service invokes only
|
|
// --service with an explicit config path; tray/helper modes cannot silently
|
|
// turn an ordinary process invocation into a privileged service.
|
|
func run(args []string, output, diagnostics io.Writer) error {
|
|
if len(args) == 1 && args[0] == "--version" {
|
|
_, err := fmt.Fprintln(output, buildVersion)
|
|
return err
|
|
}
|
|
if len(args) == 0 {
|
|
return runInteractiveInstaller(output, diagnostics)
|
|
}
|
|
if args[0] == "--help" || args[0] == "-h" {
|
|
_, err := io.WriteString(output, "usage: rvbox [--install-default]|--service|--tray|--launcher|--signal-helper|--check-config|--install-service|--uninstall-service|--configure-service|--start-service|--stop-service|--restart-service --config PATH\n")
|
|
return err
|
|
}
|
|
flags := flag.NewFlagSet("rvbox", flag.ContinueOnError)
|
|
flags.SetOutput(io.Discard)
|
|
configPath := flags.String("config", defaultClientConfigPath(), "absolute client TOML configuration path")
|
|
serviceMode := flags.Bool("service", false, "run under the Windows Service Control Manager")
|
|
trayMode := flags.Bool("tray", false, "run the current user's notification-area frontend")
|
|
launcherMode := flags.Bool("launcher", false, "run one private authenticated command launcher")
|
|
signalHelperMode := flags.Bool("signal-helper", false, "run one private authenticated signal helper")
|
|
channel := flags.String("channel", "", "private launcher channel (internal use only)")
|
|
checkConfig := flags.Bool("check-config", false, "validate client configuration and exit")
|
|
install := flags.Bool("install-service", false, "install or update the machine-wide service")
|
|
installDefault := flags.Bool("install-default", false, "install the packaged default configuration (internal installer use)")
|
|
configUserSID := flags.String("config-user-sid", "", "original interactive installer user SID (internal installer use)")
|
|
uninstall := flags.Bool("uninstall-service", false, "remove the machine-wide service")
|
|
configure := flags.Bool("configure-service", false, "configure machine-wide service startup mode")
|
|
startup := flags.String("startup", string(windowsservice.StartupAutomatic), "service startup mode: automatic or manual")
|
|
start := flags.Bool("start-service", false, "start the machine-wide service")
|
|
stop := flags.Bool("stop-service", false, "stop the machine-wide service")
|
|
restart := flags.Bool("restart-service", false, "restart the machine-wide service")
|
|
testFailContexts := flags.String("test-fail-contexts", "", "fixture-only pre-launch Windows context failures")
|
|
if err := flags.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
if flags.NArg() != 0 {
|
|
return fmt.Errorf("unexpected argument %q", flags.Arg(0))
|
|
}
|
|
selected := 0
|
|
for _, value := range []bool{*serviceMode, *trayMode, *launcherMode, *signalHelperMode, *checkConfig, *install, *installDefault, *uninstall, *configure, *start, *stop, *restart} {
|
|
if value {
|
|
selected++
|
|
}
|
|
}
|
|
if selected != 1 {
|
|
return errors.New("select exactly one rvbox mode")
|
|
}
|
|
if *configUserSID != "" && !*installDefault {
|
|
return errors.New("--config-user-sid is only valid with --install-default")
|
|
}
|
|
if *checkConfig {
|
|
configured, err := loadClientConfig(*configPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = fmt.Fprintf(output, "valid client configuration: path=%s server_url=%s state_dir=%s daemon_cwd=%s observability_listen=%s\n", *configPath, configured.Client.ServerURL, configured.Client.StateDir, configured.Client.DaemonCWD, configured.Observability.Listen)
|
|
return err
|
|
}
|
|
if *install {
|
|
executable, err := os.Executable()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return windowsservice.Install(windowsservice.InstallSpec{ExecutablePath: executable, ConfigPath: *configPath, Startup: windowsservice.StartupAutomatic})
|
|
}
|
|
if *installDefault {
|
|
return installPackagedDefault(*configUserSID, diagnostics)
|
|
}
|
|
if *uninstall {
|
|
return windowsservice.Uninstall()
|
|
}
|
|
if *configure {
|
|
return windowsservice.Configure(windowsservice.StartupMode(*startup))
|
|
}
|
|
if *start {
|
|
return windowsservice.Start()
|
|
}
|
|
if *stop {
|
|
return windowsservice.Stop(30)
|
|
}
|
|
if *restart {
|
|
return windowsservice.Restart(30)
|
|
}
|
|
if *trayMode {
|
|
return runTray(*configPath, diagnostics)
|
|
}
|
|
if *launcherMode {
|
|
if *channel == "" {
|
|
return errors.New("--launcher requires an internal channel")
|
|
}
|
|
return runLauncher(*channel, diagnostics)
|
|
}
|
|
if *signalHelperMode {
|
|
if *channel == "" {
|
|
return errors.New("--signal-helper requires an internal channel")
|
|
}
|
|
return runSignalHelper(*channel, diagnostics)
|
|
}
|
|
var testFaultErr error
|
|
nativeTestContextFailures, testFaultErr = clientwindows.NativeTestContextFailures(*testFailContexts)
|
|
if testFaultErr != nil {
|
|
return testFaultErr
|
|
}
|
|
return runService(*configPath, diagnostics)
|
|
}
|
|
|
|
func loadClientConfig(path string) (*config.Client, error) {
|
|
platform := config.PlatformUnix
|
|
checkFilesystem := false
|
|
if runtime.GOOS == "windows" {
|
|
platform = config.PlatformWindows
|
|
checkFilesystem = true
|
|
}
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read client config: %w", err)
|
|
}
|
|
return config.DecodeClient(data, config.ClientOptions{Platform: platform, CheckFilesystem: checkFilesystem})
|
|
}
|
|
|
|
func runClientDaemon(ctx context.Context, configPath string, diagnostics io.Writer) error {
|
|
clientSessionReady.Store(false)
|
|
defer clientSessionReady.Store(false)
|
|
configured, err := loadClientConfig(configPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
runtimeLog, err := observability.OpenRotatingFile(configured.Observability.LogFile, configured.Observability.LogMaxBytes, configured.Observability.LogMaxFiles)
|
|
if err != nil {
|
|
return fmt.Errorf("open client rotating log: %w", err)
|
|
}
|
|
defer runtimeLog.Close()
|
|
formattedRuntimeLog := observability.FormatLog(runtimeLog, configured.Observability.LogFormat)
|
|
if diagnostics == nil {
|
|
diagnostics = formattedRuntimeLog
|
|
} else {
|
|
diagnostics = io.MultiWriter(formattedRuntimeLog, diagnostics)
|
|
}
|
|
health := observability.New()
|
|
if configured.Observability.Listen != "" {
|
|
go func() {
|
|
if serveErr := health.Serve(ctx, configured.Observability.Listen, observability.Paths{Liveness: configured.Observability.LivenessPath, Readiness: configured.Observability.ReadinessPath, Metrics: configured.Observability.MetricsPath}); serveErr != nil && ctx.Err() == nil && diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox client observability endpoint stopped: %v\n", serveErr)
|
|
}
|
|
}()
|
|
}
|
|
state, err := spool.Open(ctx, spool.Options{DataDir: configured.Client.StateDir, BusyTimeout: 5 * time.Second, TombstoneLimit: configured.Storage.TombstoneMaxEntries, MaxScriptBytes: configured.Execution.MaxScriptBytes, MaxExecutionSpecBytes: configured.Execution.MaxExecutionSpecBytes, QuotaLimits: spool.QuotaLimits{HardAllocationBytes: 1 << 20, CommandOutputBytes: configured.Storage.CommandOutputLimitBytes, CommandTotalBytes: configured.Storage.CommandTotalLimitBytes, ClientTotalBytes: configured.Storage.ClientTotalLimitBytes, CloseoutReserveBytes: configured.Storage.CommandCloseoutReserveBytes}})
|
|
if err != nil {
|
|
health.SetDirty(true)
|
|
return fmt.Errorf("open client durable state: %w", err)
|
|
}
|
|
defer state.Close()
|
|
go publishClientTelemetry(ctx, state, health)
|
|
if diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox client service initialized for %s\n", configured.Client.ServerURL)
|
|
}
|
|
hello := clientHello(configured, state.ClientInstanceID())
|
|
httpClient, err := clientHTTPClient(configured.TLS)
|
|
if err != nil {
|
|
return fmt.Errorf("configure client TLS: %w", err)
|
|
}
|
|
limits := agentproto.Limits{MaxEnvelopeBytes: configured.Execution.MaxAgentEnvelopeBytes, MaxExecutionSpecBytes: configured.Execution.MaxExecutionSpecBytes, MaxRawChunkBytes: configured.Execution.MaxRawChunkBytes, MaxScriptBytes: configured.Execution.MaxScriptBytes, MaxDetailBytes: configured.Execution.ProtocolDetailMaxBytes}
|
|
if limits.MaxEnvelopeBytes == 0 {
|
|
limits = agentproto.DefaultLimits()
|
|
}
|
|
eventReady := make(chan domain.UUID, 256)
|
|
supervised, err := clientwindows.NewSupervisor(clientwindows.NativeOptions{Shells: clientwindows.ShellPaths{CMD: configured.Shells.CMD, PowerShell: configured.Shells.PowerShell}, WorkRoot: configured.Client.DaemonCWD, JobProfiles: clientJobProfiles(configured.Profiles), MaxWrapperBytes: configured.Execution.MaxScriptBytes, MaxOutputChunk: configured.Execution.MaxRawChunkBytes, WindowsTermGrace: configured.Execution.WindowsTermGrace, TestContextFailures: nativeTestContextFailures})
|
|
if err != nil {
|
|
return fmt.Errorf("configure command supervisor: %w", err)
|
|
}
|
|
executor, err := agent.NewExecutor(agent.ExecutorOptions{Store: state, Supervisor: supervised, WorkDir: configured.Client.DaemonCWD, Metrics: health, Notify: func(issue domain.UUID) {
|
|
select {
|
|
case eventReady <- issue:
|
|
default:
|
|
}
|
|
}})
|
|
if err != nil {
|
|
return fmt.Errorf("configure command executor: %w", err)
|
|
}
|
|
runner := func() {
|
|
if _, checkErr := state.Check(ctx); checkErr != nil {
|
|
health.SetDirty(true)
|
|
if diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox client spool is dirty: %v\n", checkErr)
|
|
}
|
|
return
|
|
}
|
|
if recovered, recoverErr := state.RecoverLaunchUncertainty(ctx, time.Now().UTC()); recoverErr != nil {
|
|
health.SetDirty(true)
|
|
if diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox launch recovery failed: %v\n", recoverErr)
|
|
}
|
|
return
|
|
} else if len(recovered) > 0 && diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox recovered %d uncertain launch(es)\n", len(recovered))
|
|
}
|
|
if runErr := agent.Run(ctx, agent.RunnerOptions{
|
|
Store: state,
|
|
Dial: func(dialContext context.Context) (agent.Transport, error) {
|
|
return agent.DialWebSocketWithLimits(dialContext, configured.Client.ServerURL, httpClient, limits)
|
|
},
|
|
Hello: hello, Limits: limits,
|
|
Backoff: agent.BackoffOptions{Initial: configured.Network.ReconnectInitial, Maximum: configured.Network.ReconnectMax, StableReset: configured.Network.StableSessionReset},
|
|
Jitter: agent.CryptoJitter, Now: func() time.Time { return time.Now().UTC() },
|
|
OnDispatch: executor.Dispatch, OnScriptReady: executor.ScriptReady, OnStdin: executor.Stdin,
|
|
OnCloseStdin: executor.CloseStdin, OnSignal: executor.Signal, OnTerminate: executor.Terminate, EventReady: eventReady,
|
|
Metrics: health,
|
|
OnSessionActive: func(ready bool) {
|
|
clientSessionReady.Store(ready)
|
|
health.SetReady(ready)
|
|
},
|
|
OnSessionError: func(sessionErr error) {
|
|
if diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox client session retry: %v\n", sessionErr)
|
|
}
|
|
},
|
|
}); runErr != nil && ctx.Err() == nil && diagnostics != nil {
|
|
_, _ = fmt.Fprintf(diagnostics, "rvbox client session stopped: %v\n", runErr)
|
|
}
|
|
}
|
|
go runner()
|
|
<-ctx.Done()
|
|
_ = executor.StopAll(context.Background())
|
|
return nil
|
|
}
|
|
|
|
func publishClientTelemetry(ctx context.Context, state *spool.Store, health *observability.Health) {
|
|
ticker := time.NewTicker(10 * time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
publishClientTelemetrySample(ctx, state.Telemetry, health)
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
// publishClientTelemetrySample performs one intentionally bounded, best-effort
|
|
// telemetry read. An unavailable spool metric must not interrupt reconnect or
|
|
// command supervision.
|
|
func publishClientTelemetrySample(ctx context.Context, read func(context.Context) (spool.Telemetry, error), health *observability.Health) {
|
|
sampleContext, cancel := context.WithTimeout(ctx, time.Second)
|
|
telemetry, err := read(sampleContext)
|
|
cancel()
|
|
if err != nil {
|
|
health.Inc("telemetry_read_failure")
|
|
return
|
|
}
|
|
health.SetGauge("queue_depth", float64(telemetry.QueuedCommands))
|
|
health.SetGauge("client_spool_bytes", float64(telemetry.ChargedBytes))
|
|
}
|
|
|
|
func clientJobProfiles(profiles config.Profiles) map[string]clientwindows.JobProfile {
|
|
return map[string]clientwindows.JobProfile{
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_LIGHT.String(): toJobProfile(profiles.Light),
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_CPU_MEDIUM.String(): toJobProfile(profiles.CPUMedium),
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_CPU_HEAVY.String(): toJobProfile(profiles.CPUHeavy),
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_MEM_MEDIUM.String(): toJobProfile(profiles.MemMedium),
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_MEM_HEAVY.String(): toJobProfile(profiles.MemHeavy),
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_DISK_MEDIUM.String(): toJobProfile(profiles.DiskMedium),
|
|
rvboxv1.ExecutionProfile_EXECUTION_PROFILE_DISK_HEAVY.String(): toJobProfile(profiles.DiskHeavy),
|
|
}
|
|
}
|
|
|
|
func toJobProfile(profile config.Profile) clientwindows.JobProfile {
|
|
return clientwindows.JobProfile{RequiredControls: append([]string(nil), profile.RequiredControls...), CPUPercent: profile.CPUPercent, MemoryMaxBytes: profile.MemoryMaxBytes, PIDsMax: profile.PIDsMax, IOReadBPS: profile.WindowsIOReadBPS, IOWriteBPS: profile.WindowsIOWriteBPS}
|
|
}
|
|
|
|
func clientHTTPClient(settings config.TLS) (*http.Client, error) {
|
|
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: settings.ServerName} // #nosec G402 -- TLS 1.2 is the v1 floor.
|
|
if settings.CAFile != "" {
|
|
pem, err := os.ReadFile(settings.CAFile)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pool, err := x509.SystemCertPool()
|
|
if err != nil || pool == nil {
|
|
pool = x509.NewCertPool()
|
|
}
|
|
if !pool.AppendCertsFromPEM(pem) {
|
|
return nil, errors.New("TLS CA file contains no certificates")
|
|
}
|
|
tlsConfig.RootCAs = pool
|
|
} else {
|
|
// v1 deliberately permits a self-signed endpoint certificate without a
|
|
// separately distributed CA. Keep hostname checking: this retains the
|
|
// useful routing guard while making no claim that the peer is trusted or
|
|
// authenticated. A configured CA file opts back into normal PKI-only
|
|
// verification above.
|
|
tlsConfig.InsecureSkipVerify = true // #nosec G402 -- verified below to admit matching self-signed leaves for v1.
|
|
tlsConfig.VerifyConnection = verifySystemOrSelfSignedServer
|
|
}
|
|
return &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}, nil
|
|
}
|
|
|
|
func verifySystemOrSelfSignedServer(state tls.ConnectionState) error {
|
|
if len(state.PeerCertificates) == 0 {
|
|
return errors.New("TLS peer sent no certificates")
|
|
}
|
|
leaf := state.PeerCertificates[0]
|
|
roots, err := x509.SystemCertPool()
|
|
if err != nil || roots == nil {
|
|
roots = x509.NewCertPool()
|
|
}
|
|
intermediates := x509.NewCertPool()
|
|
for _, certificate := range state.PeerCertificates[1:] {
|
|
intermediates.AddCert(certificate)
|
|
}
|
|
_, verifyErr := leaf.Verify(x509.VerifyOptions{
|
|
DNSName: state.ServerName,
|
|
Roots: roots,
|
|
Intermediates: intermediates,
|
|
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
})
|
|
if verifyErr == nil {
|
|
return nil
|
|
}
|
|
if err := leaf.CheckSignatureFrom(leaf); err != nil {
|
|
return verifyErr
|
|
}
|
|
return leaf.VerifyHostname(state.ServerName)
|
|
}
|
|
|
|
func clientHello(configured *config.Client, instance domain.UUID) *rvboxv1.ClientHello {
|
|
platform := rvboxv1.Platform_PLATFORM_LINUX
|
|
shells := []rvboxv1.ShellType{rvboxv1.ShellType_SHELL_CMD, rvboxv1.ShellType_SHELL_POWERSHELL}
|
|
if runtime.GOOS == "windows" {
|
|
platform = rvboxv1.Platform_PLATFORM_WINDOWS
|
|
} else {
|
|
shells = []rvboxv1.ShellType{rvboxv1.ShellType_SHELL_SH, rvboxv1.ShellType_SHELL_BASH}
|
|
}
|
|
clientID := configured.Client.ClientID
|
|
if clientID == "" {
|
|
clientID, _ = os.Hostname()
|
|
}
|
|
return &rvboxv1.ClientHello{
|
|
ClientId: clientID, SupportedProtocol: &rvboxv1.ProtocolRange{Major: 1, MinMinor: 0, MaxMinor: 0},
|
|
DaemonVersion: buildVersion, Platform: platform, Architecture: runtime.GOARCH, DaemonCwd: configured.Client.DaemonCWD,
|
|
SupportedShells: shells, ClientInstanceId: instance.String(), MaxRunningCommands: configured.Client.MaxRunningCommands,
|
|
MaxQueuedCommands: configured.Client.MaxQueuedCommands, SentAt: timestamppb.New(time.Now().UTC()),
|
|
}
|
|
}
|