feat: persist and transfer script command payloads
This commit is contained in:
@@ -35,5 +35,15 @@ func PersistDispatch(ctx context.Context, store *spool.Store, session Session, d
|
||||
if err != nil {
|
||||
return spool.Acceptance{}, err
|
||||
}
|
||||
return store.AcceptCommand(ctx, spool.Command{IssueUUID: issue, ImmutableSHA256: immutable, Revision: dispatch.GetCommandRevision(), Phase: uint32(rvboxv1.CommandLifecycle_COMMAND_ACCEPTED), ExecutionSpec: spec}, now)
|
||||
acceptance, err := store.AcceptCommand(ctx, spool.Command{IssueUUID: issue, ImmutableSHA256: immutable, Revision: dispatch.GetCommandRevision(), Phase: uint32(rvboxv1.CommandLifecycle_COMMAND_ACCEPTED), ExecutionSpec: spec}, now)
|
||||
if err != nil {
|
||||
return spool.Acceptance{}, err
|
||||
}
|
||||
if descriptor := dispatch.GetSpec().GetScript(); descriptor != nil {
|
||||
_, err = store.BeginScript(ctx, issue, spool.ScriptDescriptor{SizeBytes: descriptor.GetSizeBytes(), SHA256: bytesToDigest(descriptor.GetSha256())})
|
||||
if err != nil {
|
||||
return spool.Acceptance{}, err
|
||||
}
|
||||
}
|
||||
return acceptance, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package agent
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -103,6 +104,42 @@ func TestPersistDispatchUsesImmutableHash_HP_DISPATCH_04(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptFramesApplyDurablyAndReplaySafely_HP_SCRIPT_04(t *testing.T) {
|
||||
store, err := spool.Open(context.Background(), spool.Options{DataDir: filepath.Join(t.TempDir(), "script-spool"), BusyTimeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
body := []byte("Write-Output 'hello'\r\n")
|
||||
digest := sha256.Sum256(body)
|
||||
dispatch := &rvboxv1.CommandDispatch{IssueUuid: "019c46f1-1d02-7000-8000-000000000067", CommandRevision: 1, TargetSessionGeneration: 9, IssueTime: timestamppb.Now(), ImmutableRequestSha256: []byte("12345678901234567890123456789012"), Spec: &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_POWERSHELL, Source: &rvboxv1.ExecutionSpec_Script{Script: &rvboxv1.ScriptDescriptor{Filename: "hello.ps1", SizeBytes: uint64(len(body)), Sha256: digest[:]}}}}
|
||||
accepted, err := PersistDispatch(context.Background(), store, Session{Generation: 9}, dispatch, time.Now().UTC(), agentproto.DefaultLimits())
|
||||
if err != nil || accepted.Duplicate {
|
||||
t.Fatalf("script PersistDispatch = %#v, %v", accepted, err)
|
||||
}
|
||||
chunkDigest := sha256.Sum256(body[:8])
|
||||
status, err := ApplyScriptChunk(context.Background(), store, Session{Generation: 9}, &rvboxv1.ScriptChunk{IssueUuid: dispatch.GetIssueUuid(), Offset: 0, Data: body[:8], Sha256: chunkDigest[:]}, agentproto.DefaultLimits())
|
||||
if err != nil || status.ReceivedBytes != 8 {
|
||||
t.Fatalf("first script chunk = %#v, %v", status, err)
|
||||
}
|
||||
duplicate, err := ApplyScriptChunk(context.Background(), store, Session{Generation: 9}, &rvboxv1.ScriptChunk{IssueUuid: dispatch.GetIssueUuid(), Offset: 0, Data: body[:8], Sha256: chunkDigest[:]}, agentproto.DefaultLimits())
|
||||
if err != nil || !duplicate.Duplicate || duplicate.ReceivedBytes != 8 {
|
||||
t.Fatalf("replayed script chunk = %#v, %v", duplicate, err)
|
||||
}
|
||||
restDigest := sha256.Sum256(body[8:])
|
||||
if _, err := ApplyScriptChunk(context.Background(), store, Session{Generation: 9}, &rvboxv1.ScriptChunk{IssueUuid: dispatch.GetIssueUuid(), Offset: 8, Data: body[8:], Sha256: restDigest[:]}, agentproto.DefaultLimits()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
committed, err := ApplyScriptCommit(context.Background(), store, Session{Generation: 9}, &rvboxv1.ScriptCommit{IssueUuid: dispatch.GetIssueUuid(), SizeBytes: uint64(len(body)), Sha256: digest[:]}, agentproto.DefaultLimits())
|
||||
if err != nil || !committed.Committed || committed.ReceivedBytes != uint64(len(body)) {
|
||||
t.Fatalf("script commit = %#v, %v", committed, err)
|
||||
}
|
||||
replayed, err := ApplyScriptChunk(context.Background(), store, Session{Generation: 9}, &rvboxv1.ScriptChunk{IssueUuid: dispatch.GetIssueUuid(), Offset: 8, Data: body[8:], Sha256: restDigest[:]}, agentproto.DefaultLimits())
|
||||
if err != nil || !replayed.Duplicate || !replayed.Committed {
|
||||
t.Fatalf("post-commit chunk replay = %#v, %v", replayed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendCommandEventCanonicalDigest_HP_EVENT_02(t *testing.T) {
|
||||
transport := &fakeTransport{}
|
||||
event := &rvboxv1.CommandEvent{IssueUuid: "019c46f1-1d02-7000-8000-000000000065", EventSeq: 1, ObservedAt: timestamppb.Now(), Payload: &rvboxv1.CommandEvent_Lifecycle{Lifecycle: &rvboxv1.LifecycleChange{Lifecycle: rvboxv1.CommandLifecycle_COMMAND_RUNNING, CommandRevision: 1}}}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
|
||||
rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1"
|
||||
"github.com/rvbox/rvbox/internal/agentproto"
|
||||
"github.com/rvbox/rvbox/internal/client/spool"
|
||||
"github.com/rvbox/rvbox/internal/domain"
|
||||
)
|
||||
|
||||
var ErrInvalidScriptTransfer = errors.New("invalid script transfer")
|
||||
|
||||
// ApplyScriptChunk validates one server script frame and appends it to the
|
||||
// durable client spool. The spool accepts only the next contiguous range or
|
||||
// an exact replay, so reconnects cannot create holes or duplicate bytes.
|
||||
func ApplyScriptChunk(ctx context.Context, store *spool.Store, session Session, chunk *rvboxv1.ScriptChunk, limits agentproto.Limits) (spool.ScriptStatus, error) {
|
||||
if store == nil || session.Generation == 0 || chunk == nil || chunk.GetOffset() > limits.MaxScriptBytes || uint64(len(chunk.GetData())) > limits.MaxRawChunkBytes || len(chunk.GetSha256()) != sha256.Size {
|
||||
return spool.ScriptStatus{}, ErrInvalidScriptTransfer
|
||||
}
|
||||
issue, err := domain.ParseUUIDv7(chunk.GetIssueUuid())
|
||||
if err != nil || sha256.Sum256(chunk.GetData()) != bytesToDigest(chunk.GetSha256()) {
|
||||
return spool.ScriptStatus{}, ErrInvalidScriptTransfer
|
||||
}
|
||||
return store.AppendScriptChunk(ctx, issue, chunk.GetOffset(), chunk.GetData(), bytesToDigest(chunk.GetSha256()))
|
||||
}
|
||||
|
||||
// ApplyScriptCommit marks a fully received script launch-eligible only after
|
||||
// the spool verifies the declared size and whole-body SHA-256.
|
||||
func ApplyScriptCommit(ctx context.Context, store *spool.Store, session Session, commit *rvboxv1.ScriptCommit, limits agentproto.Limits) (spool.ScriptStatus, error) {
|
||||
if store == nil || session.Generation == 0 || commit == nil || commit.GetSizeBytes() > limits.MaxScriptBytes || len(commit.GetSha256()) != sha256.Size {
|
||||
return spool.ScriptStatus{}, ErrInvalidScriptTransfer
|
||||
}
|
||||
issue, err := domain.ParseUUIDv7(commit.GetIssueUuid())
|
||||
if err != nil {
|
||||
return spool.ScriptStatus{}, ErrInvalidScriptTransfer
|
||||
}
|
||||
return store.CommitScript(ctx, issue, spool.ScriptDescriptor{SizeBytes: commit.GetSizeBytes(), SHA256: bytesToDigest(commit.GetSha256())})
|
||||
}
|
||||
|
||||
func bytesToDigest(value []byte) [sha256.Size]byte {
|
||||
var digest [sha256.Size]byte
|
||||
copy(digest[:], value)
|
||||
return digest
|
||||
}
|
||||
@@ -102,7 +102,7 @@ func (store *Store) AppendScriptChunk(ctx context.Context, issueUUID domain.UUID
|
||||
if err != nil {
|
||||
return ScriptStatus{}, err
|
||||
}
|
||||
if row.Committed {
|
||||
if row.Committed && offset >= row.ReceivedBytes {
|
||||
return ScriptStatus{}, ErrScriptTerminal
|
||||
}
|
||||
if offset > row.ReceivedBytes {
|
||||
@@ -123,8 +123,17 @@ func (store *Store) AppendScriptChunk(ctx context.Context, issueUUID domain.UUID
|
||||
if end > row.ReceivedBytes || !bytes.Equal(raw[offset:end], data) {
|
||||
return ScriptStatus{}, ErrScriptOverlap
|
||||
}
|
||||
// A reconnect can replay a chunk after the client has already committed
|
||||
// the complete script. Exact byte-for-byte replays are safe and must be
|
||||
// idempotent; a new byte after commit remains forbidden.
|
||||
if row.Committed {
|
||||
return ScriptStatus{ReceivedBytes: row.ReceivedBytes, Committed: true, Duplicate: true}, tx.Commit()
|
||||
}
|
||||
return ScriptStatus{ReceivedBytes: row.ReceivedBytes, Duplicate: true}, tx.Commit()
|
||||
}
|
||||
if row.Committed {
|
||||
return ScriptStatus{}, ErrScriptTerminal
|
||||
}
|
||||
updatedRaw := append(raw, data...)
|
||||
stored, err := compressScript(updatedRaw)
|
||||
if err != nil {
|
||||
|
||||
@@ -63,6 +63,10 @@ func TestScriptUploadDurableExactReplayAndCommit_HP_SCRIPT_01(t *testing.T) {
|
||||
if err != nil || !duplicate.Duplicate || !duplicate.Committed {
|
||||
t.Fatalf("ScriptCommit replay = %#v, %v", duplicate, err)
|
||||
}
|
||||
duplicate, err = store.AppendScriptChunk(ctx, issue, 0, raw[:len(first)], sha256.Sum256(raw[:len(first)]))
|
||||
if err != nil || !duplicate.Duplicate || !duplicate.Committed || duplicate.ReceivedBytes != uint64(len(raw)) {
|
||||
t.Fatalf("post-commit ScriptChunk replay = %#v, %v", duplicate, err)
|
||||
}
|
||||
if _, err := store.AppendScriptChunk(ctx, issue, uint64(len(raw)), []byte("!"), sha256.Sum256([]byte("!"))); !errors.Is(err, ErrScriptTerminal) {
|
||||
t.Fatalf("post-commit chunk error = %v, want ErrScriptTerminal", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1"
|
||||
)
|
||||
|
||||
// The Windows supervisor never resolves a shell through PATH. ShellPaths is
|
||||
// the already-defaulted configuration snapshot supplied by the daemon; the
|
||||
// native launch adapter re-stats the selected path immediately before use.
|
||||
type ShellPaths struct {
|
||||
CMD string
|
||||
PowerShell string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUnsupportedShell = errors.New("shell is unsupported on Windows")
|
||||
ErrInvalidShellPath = errors.New("Windows shell path must be an absolute executable path")
|
||||
ErrInvalidWrapperSource = errors.New("invalid generated wrapper source")
|
||||
ErrWrapperTooLarge = errors.New("generated wrapper exceeds the configured limit")
|
||||
ErrWrapperDigestMismatch = errors.New("script body does not match its descriptor digest")
|
||||
ErrWrapperLengthMismatch = errors.New("script body does not match its descriptor length")
|
||||
ErrInvalidWrapperPath = errors.New("generated wrapper path is invalid")
|
||||
ErrInvalidWorkingDirectory = errors.New("Windows working directory is invalid")
|
||||
)
|
||||
|
||||
// WrapperEncoding documents how the private generated file is encoded. CMD
|
||||
// receives the source bytes unchanged; PowerShell gets a UTF-8 BOM so the
|
||||
// inbox Windows PowerShell implementation does not interpret non-ASCII text
|
||||
// using the legacy system code page.
|
||||
type WrapperEncoding uint8
|
||||
|
||||
const (
|
||||
WrapperEncodingUTF8 WrapperEncoding = iota + 1
|
||||
WrapperEncodingUTF8BOM
|
||||
)
|
||||
|
||||
// ShellPlan is the immutable invocation contract for one supported Windows
|
||||
// shell. Arguments intentionally exclude the application name: the native
|
||||
// adapter passes ApplicationName separately to CreateProcessAsUser while
|
||||
// CommandLine contains the complete argv-compatible command line.
|
||||
type ShellPlan struct {
|
||||
Type rvboxv1.ShellType
|
||||
ApplicationName string
|
||||
Arguments []string
|
||||
WrapperExtension string
|
||||
Encoding WrapperEncoding
|
||||
}
|
||||
|
||||
// Wrapper is the private generated script body. Filename is never derived
|
||||
// from caller input; the native materializer appends Extension to an
|
||||
// unpredictable per-command basename.
|
||||
type Wrapper struct {
|
||||
Extension string
|
||||
Encoding WrapperEncoding
|
||||
Bytes []byte
|
||||
SHA256 [sha256.Size]byte
|
||||
}
|
||||
|
||||
// LaunchPlan contains only deterministic launch inputs. Handles, ACLs, Job
|
||||
// Objects, token selection and release barriers belong to the platform-native
|
||||
// supervisor and are deliberately absent here.
|
||||
type LaunchPlan struct {
|
||||
ApplicationName string
|
||||
Arguments []string
|
||||
CommandLine string
|
||||
WrapperPath string
|
||||
WorkingDirectory string
|
||||
Environment []uint16
|
||||
}
|
||||
|
||||
// ResolveShell chooses exactly the configured executable for shellType. It
|
||||
// does not consult PATH, COMSPEC, file associations, environment overrides,
|
||||
// or a wrapper's extension.
|
||||
func ResolveShell(shellType rvboxv1.ShellType, paths ShellPaths) (ShellPlan, error) {
|
||||
plan, err := shellTemplate(shellType)
|
||||
if err != nil {
|
||||
return ShellPlan{}, err
|
||||
}
|
||||
if shellType == rvboxv1.ShellType_SHELL_CMD {
|
||||
plan.ApplicationName = paths.CMD
|
||||
} else {
|
||||
plan.ApplicationName = paths.PowerShell
|
||||
}
|
||||
if err := ValidateWindowsExecutablePath(plan.ApplicationName); err != nil {
|
||||
return ShellPlan{}, fmt.Errorf("%w: %v", ErrInvalidShellPath, err)
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// BuildWrapper validates and copies command/script bytes. For script sources,
|
||||
// descriptor length and SHA-256 are checked before any materialization. The
|
||||
// returned bytes are safe to hand to a private generated-file writer.
|
||||
func BuildWrapper(spec *rvboxv1.ExecutionSpec, scriptBody []byte, maxBytes uint64) (Wrapper, error) {
|
||||
if spec == nil {
|
||||
return Wrapper{}, ErrInvalidWrapperSource
|
||||
}
|
||||
plan, err := shellTemplate(spec.GetShellType())
|
||||
if err != nil {
|
||||
return Wrapper{}, err
|
||||
}
|
||||
var source []byte
|
||||
switch value := spec.Source.(type) {
|
||||
case *rvboxv1.ExecutionSpec_CommandText:
|
||||
if !utf8.ValidString(value.CommandText) {
|
||||
return Wrapper{}, fmt.Errorf("%w: command text is not UTF-8", ErrInvalidWrapperSource)
|
||||
}
|
||||
source = []byte(value.CommandText)
|
||||
case *rvboxv1.ExecutionSpec_Script:
|
||||
if value.Script == nil || len(value.Script.Sha256) != sha256.Size {
|
||||
return Wrapper{}, fmt.Errorf("%w: script descriptor is incomplete", ErrInvalidWrapperSource)
|
||||
}
|
||||
if uint64(len(scriptBody)) != value.Script.SizeBytes {
|
||||
return Wrapper{}, ErrWrapperLengthMismatch
|
||||
}
|
||||
digest := sha256.Sum256(scriptBody)
|
||||
if !bytes.Equal(digest[:], value.Script.Sha256) {
|
||||
return Wrapper{}, ErrWrapperDigestMismatch
|
||||
}
|
||||
source = append([]byte(nil), scriptBody...)
|
||||
default:
|
||||
return Wrapper{}, fmt.Errorf("%w: exactly one command or script source is required", ErrInvalidWrapperSource)
|
||||
}
|
||||
if uint64(len(source)) > maxBytes && maxBytes != 0 {
|
||||
return Wrapper{}, ErrWrapperTooLarge
|
||||
}
|
||||
if bytes.IndexByte(source, 0) >= 0 {
|
||||
return Wrapper{}, fmt.Errorf("%w: source contains NUL", ErrInvalidWrapperSource)
|
||||
}
|
||||
if plan.Encoding == WrapperEncodingUTF8BOM {
|
||||
source = append([]byte{0xef, 0xbb, 0xbf}, source...)
|
||||
}
|
||||
if uint64(len(source)) > maxBytes && maxBytes != 0 {
|
||||
return Wrapper{}, ErrWrapperTooLarge
|
||||
}
|
||||
return Wrapper{Extension: plan.WrapperExtension, Encoding: plan.Encoding, Bytes: source, SHA256: sha256.Sum256(source)}, nil
|
||||
}
|
||||
|
||||
func shellTemplate(shellType rvboxv1.ShellType) (ShellPlan, error) {
|
||||
switch shellType {
|
||||
case rvboxv1.ShellType_SHELL_CMD:
|
||||
return ShellPlan{Type: shellType, Arguments: []string{"/D", "/S", "/C"}, WrapperExtension: ".cmd", Encoding: WrapperEncodingUTF8}, nil
|
||||
case rvboxv1.ShellType_SHELL_POWERSHELL:
|
||||
return ShellPlan{Type: shellType, Arguments: []string{"-NoLogo", "-NoProfile", "-NonInteractive", "-File"}, WrapperExtension: ".ps1", Encoding: WrapperEncodingUTF8BOM}, nil
|
||||
default:
|
||||
return ShellPlan{}, fmt.Errorf("%w: %s", ErrUnsupportedShell, shellType)
|
||||
}
|
||||
}
|
||||
|
||||
// BuildLaunchPlan appends the generated wrapper path to the fixed shell
|
||||
// argument vector and quotes the complete vector with the reviewed Windows
|
||||
// routine. Environment is expected to be BuildEnvironmentBlock output.
|
||||
func (plan ShellPlan) BuildLaunchPlan(wrapperPath, workingDirectory string, environment []uint16) (LaunchPlan, error) {
|
||||
if err := ValidateWindowsExecutablePath(plan.ApplicationName); err != nil {
|
||||
return LaunchPlan{}, fmt.Errorf("%w: %v", ErrInvalidShellPath, err)
|
||||
}
|
||||
if !validAbsoluteWindowsPath(wrapperPath) || strings.ToLower(strings.TrimSpace(wrapperPath)) != strings.ToLower(wrapperPath) || !strings.EqualFold(extensionOfWindowsPath(wrapperPath), plan.WrapperExtension) {
|
||||
return LaunchPlan{}, ErrInvalidWrapperPath
|
||||
}
|
||||
if !validAbsoluteWindowsPath(workingDirectory) {
|
||||
return LaunchPlan{}, ErrInvalidWorkingDirectory
|
||||
}
|
||||
arguments := append([]string(nil), plan.Arguments...)
|
||||
arguments = append(arguments, wrapperPath)
|
||||
full := append([]string{plan.ApplicationName}, arguments...)
|
||||
commandLine, err := BuildCommandLine(full)
|
||||
if err != nil {
|
||||
return LaunchPlan{}, err
|
||||
}
|
||||
return LaunchPlan{ApplicationName: plan.ApplicationName, Arguments: arguments, CommandLine: commandLine, WrapperPath: wrapperPath, WorkingDirectory: workingDirectory, Environment: append([]uint16(nil), environment...)}, nil
|
||||
}
|
||||
|
||||
// ValidateWindowsExecutablePath applies the lexical checks that are possible
|
||||
// before a native re-stat. The Windows adapter must still verify that the
|
||||
// path names the same regular executable immediately before launch.
|
||||
func ValidateWindowsExecutablePath(path string) error {
|
||||
if !validAbsoluteWindowsPath(path) || strings.TrimSpace(path) != path {
|
||||
return ErrInvalidShellPath
|
||||
}
|
||||
extension := strings.ToLower(extensionOfWindowsPath(path))
|
||||
switch extension {
|
||||
case ".exe", ".com", ".cmd", ".bat":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported executable extension %q", extension)
|
||||
}
|
||||
}
|
||||
|
||||
func validAbsoluteWindowsPath(value string) bool {
|
||||
if value == "" || strings.IndexByte(value, 0) >= 0 || !utf8.ValidString(value) || strings.ContainsAny(value, "\r\n\t") {
|
||||
return false
|
||||
}
|
||||
value = strings.ReplaceAll(value, "/", `\`)
|
||||
if strings.HasPrefix(value, `\\`) {
|
||||
parts := strings.Split(strings.TrimPrefix(value, `\\`), `\`)
|
||||
if len(parts) < 2 || parts[0] == "" || parts[1] == "" {
|
||||
return false
|
||||
}
|
||||
} else if len(value) < 3 || !((value[0] >= 'A' && value[0] <= 'Z') || (value[0] >= 'a' && value[0] <= 'z')) || value[1] != ':' || value[2] != '\\' {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(value, `\`) {
|
||||
if part == "" || part == "." || part == ".." {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(part, " ") || strings.HasSuffix(part, ".") {
|
||||
return false
|
||||
}
|
||||
for _, character := range part {
|
||||
if character < 0x20 || character == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func extensionOfWindowsPath(path string) string {
|
||||
path = strings.ReplaceAll(path, "/", `\`)
|
||||
index := strings.LastIndexByte(path, '\\')
|
||||
if index >= 0 {
|
||||
path = path[index+1:]
|
||||
}
|
||||
dot := strings.LastIndexByte(path, '.')
|
||||
if dot < 0 {
|
||||
return ""
|
||||
}
|
||||
return path[dot:]
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1"
|
||||
)
|
||||
|
||||
func TestResolveShellUsesOnlyConfiguredAbsoluteExecutable_BH_WINLAUNCH_01(t *testing.T) {
|
||||
t.Parallel()
|
||||
paths := ShellPaths{CMD: `C:\Trusted Tools\cmd.exe`, PowerShell: `C:\Trusted Tools\powershell.exe`}
|
||||
cmd, err := ResolveShell(rvboxv1.ShellType_SHELL_CMD, paths)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cmd.ApplicationName != paths.CMD || !equalStrings(cmd.Arguments, []string{"/D", "/S", "/C"}) || cmd.WrapperExtension != ".cmd" {
|
||||
t.Fatalf("cmd plan = %+v", cmd)
|
||||
}
|
||||
powershell, err := ResolveShell(rvboxv1.ShellType_SHELL_POWERSHELL, paths)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if powershell.ApplicationName != paths.PowerShell || !equalStrings(powershell.Arguments, []string{"-NoLogo", "-NoProfile", "-NonInteractive", "-File"}) || powershell.WrapperExtension != ".ps1" || powershell.Encoding != WrapperEncodingUTF8BOM {
|
||||
t.Fatalf("PowerShell plan = %+v", powershell)
|
||||
}
|
||||
// A hostile request PATH or COMSPEC is not an input to resolution. The
|
||||
// configured absolute path remains the only application name.
|
||||
if strings.Contains(cmd.ApplicationName, "untrusted") || strings.Contains(powershell.ApplicationName, "untrusted") {
|
||||
t.Fatal("request environment influenced shell resolution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveShellRejectsUnsupportedOrUnsafePaths_BH_WINLAUNCH_01(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
shell rvboxv1.ShellType
|
||||
paths ShellPaths
|
||||
}{
|
||||
{"unspecified", rvboxv1.ShellType_SHELL_TYPE_UNSPECIFIED, ShellPaths{CMD: `C:\Windows\System32\cmd.exe`}},
|
||||
{"unix shell", rvboxv1.ShellType_SHELL_BASH, ShellPaths{CMD: `C:\Windows\System32\cmd.exe`}},
|
||||
{"relative", rvboxv1.ShellType_SHELL_CMD, ShellPaths{CMD: `cmd.exe`}},
|
||||
{"drive relative", rvboxv1.ShellType_SHELL_CMD, ShellPaths{CMD: `C:cmd.exe`}},
|
||||
{"wrong extension", rvboxv1.ShellType_SHELL_CMD, ShellPaths{CMD: `C:\Windows\System32\cmd.dll`}},
|
||||
{"trailing space", rvboxv1.ShellType_SHELL_CMD, ShellPaths{CMD: "C:\\Windows\\System32\\cmd.exe "}},
|
||||
{"NUL", rvboxv1.ShellType_SHELL_CMD, ShellPaths{CMD: "C:\\Windows\\System32\\cmd.exe\x00"}},
|
||||
}
|
||||
for _, test := range cases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if _, err := ResolveShell(test.shell, test.paths); err == nil {
|
||||
t.Fatal("unsafe shell configuration accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildWrapperValidatesAndEncodesSources_HP_WINLAUNCH_02(t *testing.T) {
|
||||
t.Parallel()
|
||||
command := &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_CMD, Source: &rvboxv1.ExecutionSpec_CommandText{CommandText: "echo hello\r\n"}}
|
||||
wrapper, err := BuildWrapper(command, nil, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if wrapper.Extension != ".cmd" || wrapper.Encoding != WrapperEncodingUTF8 || !bytes.Equal(wrapper.Bytes, []byte("echo hello\r\n")) {
|
||||
t.Fatalf("cmd wrapper = %+v", wrapper)
|
||||
}
|
||||
if wrapper.SHA256 != sha256.Sum256(wrapper.Bytes) {
|
||||
t.Fatal("wrapper digest does not cover materialized bytes")
|
||||
}
|
||||
|
||||
body := []byte("Write-Output 'héllo'\n")
|
||||
digest := sha256.Sum256(body)
|
||||
powershell := &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_POWERSHELL, Source: &rvboxv1.ExecutionSpec_Script{Script: &rvboxv1.ScriptDescriptor{Filename: "display.ps1", SizeBytes: uint64(len(body)), Sha256: digest[:]}}}
|
||||
encoded, err := BuildWrapper(powershell, body, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded.Extension != ".ps1" || encoded.Encoding != WrapperEncodingUTF8BOM || !bytes.HasPrefix(encoded.Bytes, []byte{0xef, 0xbb, 0xbf}) || !bytes.HasSuffix(encoded.Bytes, body) {
|
||||
t.Fatalf("PowerShell wrapper bytes = %x", encoded.Bytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildWrapperRejectsMismatchNULAndLimit_BH_WINLAUNCH_02(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte("echo expected")
|
||||
digest := sha256.Sum256(body)
|
||||
script := func(size uint64, hash []byte, value []byte) *rvboxv1.ExecutionSpec {
|
||||
return &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_CMD, Source: &rvboxv1.ExecutionSpec_Script{Script: &rvboxv1.ScriptDescriptor{Filename: "x.cmd", SizeBytes: size, Sha256: hash}}}
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
spec *rvboxv1.ExecutionSpec
|
||||
body []byte
|
||||
want error
|
||||
}{
|
||||
{"length", script(uint64(len(body)+1), digest[:], body), body, ErrWrapperLengthMismatch},
|
||||
{"digest", script(uint64(len(body)), make([]byte, sha256.Size), body), body, ErrWrapperDigestMismatch},
|
||||
{"NUL", &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_CMD, Source: &rvboxv1.ExecutionSpec_CommandText{CommandText: "echo\x00bad"}}, nil, ErrInvalidWrapperSource},
|
||||
{"limit", &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_CMD, Source: &rvboxv1.ExecutionSpec_CommandText{CommandText: "123456"}}, nil, ErrWrapperTooLarge},
|
||||
}
|
||||
for _, test := range cases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, err := BuildWrapper(test.spec, test.body, map[bool]uint64{true: 5, false: 1024}[test.name == "limit"])
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("error = %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildLaunchPlanQuotesWrapperAndKeepsWorkingDirectory(t *testing.T) {
|
||||
t.Parallel()
|
||||
plan, err := ResolveShell(rvboxv1.ShellType_SHELL_CMD, ShellPaths{CMD: `C:\Windows\System32\cmd.exe`})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
launch, err := plan.BuildLaunchPlan(`C:\ProgramData\RVBox\work\issue one\wrapper.cmd`, `C:\ProgramData\RVBox\work\issue one`, []uint16{0})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if launch.ApplicationName != plan.ApplicationName || launch.WorkingDirectory == "" || !strings.Contains(launch.CommandLine, `"C:\ProgramData\RVBox\work\issue one\wrapper.cmd"`) {
|
||||
t.Fatalf("launch plan = %+v", launch)
|
||||
}
|
||||
if len(launch.Environment) != 1 || launch.Environment[0] != 0 {
|
||||
t.Fatalf("environment was not copied: %v", launch.Environment)
|
||||
}
|
||||
if _, err := plan.BuildLaunchPlan(`C:\ProgramData\RVBox\work\wrapper.ps1`, `C:\ProgramData\RVBox\work`, nil); !errors.Is(err, ErrInvalidWrapperPath) {
|
||||
t.Fatalf("extension mismatch error = %v", err)
|
||||
}
|
||||
if _, err := plan.BuildLaunchPlan(`relative\wrapper.cmd`, `C:\ProgramData\RVBox\work`, nil); !errors.Is(err, ErrInvalidWrapperPath) {
|
||||
t.Fatalf("relative wrapper error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func equalStrings(left, right []string) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
for index := range left {
|
||||
if left[index] != right[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user