aboutsummaryrefslogtreecommitdiff
path: root/cmd/root.go
blob: 116ed21fee99f0026583f65437714aa1222319a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package cmd

import (
	"context"
	"fmt"
	"github.com/RedTeamPentesting/adauth"
	"github.com/rs/zerolog"
	"github.com/spf13/cobra"
	"os"
	"regexp"
	"strings"
)

var (
	//logFile string
	log      zerolog.Logger
	ctx      context.Context
	authOpts *adauth.Options

	debug            bool
	command          string
	executable       string
	executablePath   string
	executableArgs   string
	workingDirectory string
	windowState      string

	rootCmd = &cobra.Command{
		Use: "goexec",
		PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
			// For modules that require a full executable path
			if executablePath != "" && !regexp.MustCompile(`^([a-zA-Z]:)?\\`).MatchString(executablePath) {
				return fmt.Errorf("executable path (-e) must be an absolute Windows path, i.e. C:\\Windows\\System32\\cmd.exe")
			}
			if command != "" {
				p := strings.SplitN(command, " ", 2)
				executable = p[0]
				if len(p) > 1 {
					executableArgs = p[1]
				}
			}
			log = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).Level(zerolog.InfoLevel).With().Timestamp().Logger()
			if debug {
				log = log.Level(zerolog.DebugLevel)
			}
			return
		},
	}
)

func needsTarget(proto string) func(cmd *cobra.Command, args []string) error {
	return func(cmd *cobra.Command, args []string) (err error) {
		if len(args) != 1 {
			return fmt.Errorf("command require exactly one positional argument: [target]")
		}
		if creds, target, err = authOpts.WithTarget(ctx, proto, args[0]); err != nil {
			return fmt.Errorf("failed to parse target: %w", err)
		}
		if creds == nil {
			return fmt.Errorf("no credentials supplied")
		}
		if target == nil {
			return fmt.Errorf("no target supplied")
		}
		return
	}
}

func init() {
	ctx = context.Background()

	cobra.EnableCommandSorting = false

	rootCmd.InitDefaultVersionFlag()
	rootCmd.InitDefaultHelpCmd()
	rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "Enable debug logging")

	authOpts = &adauth.Options{Debug: log.Debug().Msgf}
	authOpts.RegisterFlags(rootCmd.PersistentFlags())

	scmrCmdInit()
	rootCmd.AddCommand(scmrCmd)
	tschCmdInit()
	rootCmd.AddCommand(tschCmd)
	wmiCmdInit()
	rootCmd.AddCommand(wmiCmd)
	dcomCmdInit()
	rootCmd.AddCommand(dcomCmd)
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}