Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions cli/cmd/bastion_watchdog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package cmd

import (
"fmt"
"os"
"syscall"

"github.com/dreadnode/dreadgoad/internal/azure"
"github.com/spf13/cobra"
)

const bastionParentLifetimeFD = 3

// bastionWatchdogCmd is an internal subprocess entry point used by the Azure
// provision tunnel. It stays hidden because its inherited file descriptor is
// meaningful only when the command is launched by StartProvisionTunnel.
var bastionWatchdogCmd = &cobra.Command{
Use: "__bastion-watchdog <command> [args...]",
Hidden: true,
DisableFlagParsing: true,
Args: cobra.MinimumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
parentLifetime, err := openBastionParentLifetime(bastionParentLifetimeFD)
if err != nil {
return err
}
// ExtraFiles starts at fd 3. Keep the descriptor private to this
// watchdog; the supervised az process must not inherit it.
syscall.CloseOnExec(bastionParentLifetimeFD)
return azure.RunBastionWatchdog(parentLifetime, args)
},
}

func openBastionParentLifetime(fd uintptr) (*os.File, error) {
parentLifetime := os.NewFile(fd, "dreadgoad-parent-lifetime")
if parentLifetime == nil {
return nil, fmt.Errorf("open parent lifetime descriptor %d", fd)
}
if _, err := parentLifetime.Stat(); err != nil {
_ = parentLifetime.Close()
return nil, fmt.Errorf("validate parent lifetime descriptor %d: %w", fd, err)
}
return parentLifetime, nil
}

func init() {
rootCmd.AddCommand(bastionWatchdogCmd)
}
29 changes: 29 additions & 0 deletions cli/cmd/bastion_watchdog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package cmd

import (
"os"
"strings"
"testing"
)

func TestOpenBastionParentLifetimeRejectsClosedDescriptor(t *testing.T) {
file, err := os.CreateTemp(t.TempDir(), "closed-descriptor")
if err != nil {
t.Fatalf("create temporary file: %v", err)
}
fd := file.Fd()
if err := file.Close(); err != nil {
t.Fatalf("close temporary file: %v", err)
}

parentLifetime, err := openBastionParentLifetime(fd)
if err == nil {
if parentLifetime != nil {
_ = parentLifetime.Close()
}
t.Fatal("openBastionParentLifetime() error = nil, want invalid descriptor error")
}
if !strings.Contains(err.Error(), "validate parent lifetime descriptor") {
t.Fatalf("openBastionParentLifetime() error = %q, want validation error", err)
}
}
Loading
Loading