diff options
Diffstat (limited to 'pkg')
-rw-r--r-- | pkg/client/dcerpc/client.go | 11 | ||||
-rw-r--r-- | pkg/client/dcerpc/dcerpc.go | 106 | ||||
-rw-r--r-- | pkg/client/dcerpc/smb.go | 13 | ||||
-rw-r--r-- | pkg/exec/exec.go | 44 | ||||
-rw-r--r-- | pkg/exec/scmr/exec.go | 226 | ||||
-rw-r--r-- | pkg/exec/scmr/module.go | 31 | ||||
-rw-r--r-- | pkg/exec/scmr/scmr.go | 238 | ||||
-rw-r--r-- | pkg/exec/tsch/exec.go | 289 | ||||
-rw-r--r-- | pkg/exec/tsch/module.go | 56 | ||||
-rw-r--r-- | pkg/exec/tsch/tsch.go | 102 | ||||
-rw-r--r-- | pkg/windows/const.go | 37 |
11 files changed, 0 insertions, 1153 deletions
diff --git a/pkg/client/dcerpc/client.go b/pkg/client/dcerpc/client.go deleted file mode 100644 index d9d8d71..0000000 --- a/pkg/client/dcerpc/client.go +++ /dev/null @@ -1,11 +0,0 @@ -package dcerpc - -import ( - "context" - "github.com/RedTeamPentesting/adauth" -) - -type Client interface { - Connect(ctx context.Context, creds *adauth.Credential, target *adauth.Target) error - Close(ctx context.Context) error -} diff --git a/pkg/client/dcerpc/dcerpc.go b/pkg/client/dcerpc/dcerpc.go deleted file mode 100644 index 5c9a734..0000000 --- a/pkg/client/dcerpc/dcerpc.go +++ /dev/null @@ -1,106 +0,0 @@ -package dcerpc - -import ( - "context" - "errors" - "fmt" - "github.com/RedTeamPentesting/adauth" - "github.com/RedTeamPentesting/adauth/dcerpcauth" - "github.com/oiweiwei/go-msrpc/dcerpc" - "github.com/oiweiwei/go-msrpc/msrpc/epm/epm/v3" - "github.com/oiweiwei/go-msrpc/msrpc/scmr/svcctl/v2" - "github.com/oiweiwei/go-msrpc/smb2" - "github.com/oiweiwei/go-msrpc/ssp/gssapi" - "github.com/rs/zerolog" -) - -const ( - DceDefaultProto string = "ncacn_np" - DceDefaultPort uint16 = 445 -) - -type DCEClient struct { - Port uint16 - Proto string - - log zerolog.Logger - conn dcerpc.Conn - opts []dcerpc.Option - authOpts dcerpcauth.Options -} - -func NewDCEClient(ctx context.Context, insecure bool, smbConfig *SmbConfig) (client *DCEClient) { - client = &DCEClient{ - Port: DceDefaultPort, - Proto: DceDefaultProto, - log: zerolog.Ctx(ctx).With().Str("client", "DCE").Logger(), - authOpts: dcerpcauth.Options{}, - } - client.opts = []dcerpc.Option{dcerpc.WithLogger(client.log)} - client.authOpts = dcerpcauth.Options{Debug: client.log.Trace().Msgf} - - if smbConfig != nil { - if smbConfig.Port != 0 { - client.Port = smbConfig.Port - client.opts = append(client.opts, dcerpc.WithSMBPort(int(smbConfig.Port))) - } - } - if insecure { - client.log.Debug().Msg("Using insecure DCERPC connection") - client.opts = append(client.opts, dcerpc.WithInsecure()) - } else { - client.log.Debug().Msg("Using secure DCERPC connection") - client.authOpts.SMBOptions = append(client.authOpts.SMBOptions, smb2.WithSeal()) - } - return -} - -func (client *DCEClient) OpenSvcctl(ctx context.Context) (ctl svcctl.SvcctlClient, err error) { - if client.conn == nil { - return nil, errors.New("DCE connection not open") - } - if ctl, err = svcctl.NewSvcctlClient(ctx, client.conn, dcerpc.WithInsecure()); err != nil { - client.log.Debug().Err(err).Msg("Failed to open Svcctl client") - } - return -} - -func (client *DCEClient) DCE() dcerpc.Conn { - return client.conn -} - -func (client *DCEClient) Connect(ctx context.Context, creds *adauth.Credential, target *adauth.Target, dialOpts ...dcerpc.Option) (err error) { - if creds != nil && target != nil { - authCtx := gssapi.NewSecurityContext(ctx) - - binding := fmt.Sprintf(`%s:%s`, client.Proto, target.AddressWithoutPort()) - mapper := epm.EndpointMapper(ctx, fmt.Sprintf("%s:%d", target.AddressWithoutPort(), client.Port), dcerpc.WithLogger(client.log)) - dceOpts := []dcerpc.Option{dcerpc.WithLogger(client.log), dcerpc.WithSeal()} - - if dceOpts, err = dcerpcauth.AuthenticationOptions(authCtx, creds, target, &client.authOpts); err == nil { - dceOpts = append(dceOpts, mapper) - dceOpts = append(dceOpts, client.opts...) - dceOpts = append(dceOpts, dialOpts...) - - if client.conn, err = dcerpc.Dial(authCtx, binding, dceOpts...); err == nil { - client.log.Debug().Msg("Bind successful") - return nil - } - client.log.Debug().Err(err).Msg("DCERPC bind failed") - return errors.New("bind failed") - } - return errors.New("unable to parse DCE authentication options") - } - return errors.New("invalid arguments") -} - -func (client *DCEClient) Close(ctx context.Context) (err error) { - if client.conn == nil { - client.log.Debug().Msg("Connection already closed") - } else if err = client.conn.Close(ctx); err == nil { - client.log.Debug().Msg("Connection closed successfully") - } else { - client.log.Error().Err(err).Msg("Failed to close connection") - } - return -} diff --git a/pkg/client/dcerpc/smb.go b/pkg/client/dcerpc/smb.go deleted file mode 100644 index cab82eb..0000000 --- a/pkg/client/dcerpc/smb.go +++ /dev/null @@ -1,13 +0,0 @@ -package dcerpc - -import "github.com/oiweiwei/go-msrpc/smb2" - -const ( - SmbDefaultPort = 445 -) - -type SmbConfig struct { - Port uint16 - FullSecurity bool - ForceDialect smb2.Dialect -} diff --git a/pkg/exec/exec.go b/pkg/exec/exec.go deleted file mode 100644 index 16fa543..0000000 --- a/pkg/exec/exec.go +++ /dev/null @@ -1,44 +0,0 @@ -package exec - -import ( - "context" - "github.com/RedTeamPentesting/adauth" -) - -type CleanupConfig struct { - CleanupMethod string - CleanupMethodConfig interface{} -} - -type ExecutionConfig struct { - ExecutableName string // ExecutableName represents the name of the executable; i.e. "notepad.exe", "calc" - ExecutablePath string // ExecutablePath represents the full path to the executable; i.e. `C:\Windows\explorer.exe` - ExecutableArgs string // ExecutableArgs represents the arguments to be passed to the executable during execution; i.e. "/C whoami" - - ExecutionMethod string // ExecutionMethod represents the specific execution strategy used by the module. - ExecutionMethodConfig interface{} - ExecutionOutput string // not implemented - ExecutionOutputConfig interface{} // not implemented -} - -type ShellConfig struct { - ShellName string // ShellName specifies the name of the shell executable; i.e. "cmd.exe", "powershell" - ShellPath string // ShellPath is the full Windows path to the shell executable; i.e. `C:\Windows\System32\cmd.exe` -} - -type Module interface { - // Exec performs a single execution task without the need to call Init. - Exec(context.Context, *adauth.Credential, *adauth.Target, *ExecutionConfig) error - Cleanup(context.Context, *adauth.Credential, *adauth.Target, *CleanupConfig) error - - // Init assigns the provided TODO - //Init(ctx context.Context, creds *adauth.Credential, target *adauth.Target) - //Shell(ctx context.Context, input chan *ExecutionConfig, output chan []byte) -} - -func (cfg *ExecutionConfig) GetRawCommand() string { - if cfg.ExecutableArgs != "" { - return cfg.ExecutablePath + " " + cfg.ExecutableArgs - } - return cfg.ExecutablePath -} diff --git a/pkg/exec/scmr/exec.go b/pkg/exec/scmr/exec.go deleted file mode 100644 index ab4cfdd..0000000 --- a/pkg/exec/scmr/exec.go +++ /dev/null @@ -1,226 +0,0 @@ -package scmrexec - -import ( - "context" - "errors" - "fmt" - "github.com/FalconOpsLLC/goexec/pkg/client/dcerpc" - "github.com/FalconOpsLLC/goexec/pkg/exec" - "github.com/FalconOpsLLC/goexec/pkg/windows" - "github.com/RedTeamPentesting/adauth" - "github.com/rs/zerolog" -) - -const ( - MethodCreate string = "create" - MethodModify string = "modify" - - ServiceModifyAccess uint32 = windows.SERVICE_QUERY_CONFIG | windows.SERVICE_CHANGE_CONFIG | windows.SERVICE_STOP | windows.SERVICE_START | windows.SERVICE_DELETE - ServiceCreateAccess uint32 = windows.SC_MANAGER_CREATE_SERVICE | windows.SERVICE_START | windows.SERVICE_STOP | windows.SERVICE_DELETE - ServiceAllAccess uint32 = ServiceCreateAccess | ServiceModifyAccess -) - -func (mod *Module) createClients(ctx context.Context) (cleanup func(cCtx context.Context), err error) { - - cleanup = func(context.Context) { - if mod.dce != nil { - mod.log.Debug().Msg("Cleaning up clients") - if err := mod.dce.Close(ctx); err != nil { - mod.log.Error().Err(err).Msg("Failed to destroy DCE connection") - } - } - } - cleanup(ctx) - mod.dce = dcerpc.NewDCEClient(ctx, false, &dcerpc.SmbConfig{Port: 445}) - cleanup = func(context.Context) {} - - if err = mod.dce.Connect(ctx, mod.creds, mod.target); err != nil { - return nil, fmt.Errorf("connection to DCERPC failed: %w", err) - } - mod.ctl, err = mod.dce.OpenSvcctl(ctx) - return -} - -func (mod *Module) Exec(ctx context.Context, creds *adauth.Credential, target *adauth.Target, ecfg *exec.ExecutionConfig) (err error) { - - vctx := context.WithoutCancel(ctx) - mod.log = zerolog.Ctx(ctx).With(). - Str("module", "scmr"). - Str("method", ecfg.ExecutionMethod).Logger() - mod.creds = creds - mod.target = target - - if ecfg.ExecutionMethod == MethodCreate { - if cfg, ok := ecfg.ExecutionMethodConfig.(MethodCreateConfig); !ok || cfg.ServiceName == "" { - return errors.New("invalid configuration") - } else { - if cleanup, err := mod.createClients(ctx); err != nil { - return fmt.Errorf("failed to create client: %w", err) - } else { - mod.log.Debug().Msg("Created clients") - defer cleanup(ctx) - } - svc := &service{ - createConfig: &cfg, - name: cfg.ServiceName, - } - scm, code, err := mod.openSCM(ctx) - if err != nil { - return fmt.Errorf("failed to open SCM with code %d: %w", code, err) - } - mod.log.Debug().Msg("Opened handle to SCM") - code, err = mod.createService(ctx, scm, svc, ecfg) - if err != nil { - return fmt.Errorf("failed to create service with code %d: %w", code, err) - } - mod.log.Info().Str("service", svc.name).Msg("Service created") - // From here on out, make sure the service is properly deleted, even if the connection drops or something fails. - if !cfg.NoDelete { - defer func() { - // TODO: stop service? - if code, err = mod.deleteService(ctx, scm, svc); err != nil { - mod.log.Error().Err(err).Msg("Failed to delete service") // TODO - } - mod.log.Info().Str("service", svc.name).Msg("Service deleted successfully") - }() - } - if code, err = mod.startService(ctx, scm, svc); err != nil { - if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { - // In case of timeout or cancel, try to reestablish a connection to restore the service - mod.log.Info().Msg("Service start timeout/cancelled. Execution likely successful") - mod.log.Info().Msg("Reconnecting for cleanup procedure") - ctx = vctx - - if _, err = mod.createClients(ctx); err != nil { - mod.log.Error().Err(err).Msg("Reconnect failed") - - } else if scm, code, err = mod.openSCM(ctx); err != nil { - mod.log.Error().Err(err).Msg("Failed to reopen SCM") - - } else if svc.handle, code, err = mod.openService(ctx, scm, svc.name); err != nil { - mod.log.Error().Str("service", svc.name).Err(err).Msg("Failed to reopen service handle") - - } else { - mod.log.Debug().Str("service", svc.name).Msg("Reconnection successful") - } - } else { - mod.log.Error().Err(err).Msg("Failed to start service") - } - } else { - mod.log.Info().Str("service", svc.name).Msg("Execution successful") - } - } - } else if ecfg.ExecutionMethod == MethodModify { - // Use service modification method - if cfg, ok := ecfg.ExecutionMethodConfig.(MethodModifyConfig); !ok || cfg.ServiceName == "" { - return errors.New("invalid configuration") - - } else { - // Ensure that a command (executable full path + args) is supplied - cmd := ecfg.GetRawCommand() - if cmd == "" { - return errors.New("no command provided") - } - - // Initialize protocol clients - if cleanup, err := mod.createClients(ctx); err != nil { - return fmt.Errorf("failed to create client: %w", err) - } else { - mod.log.Debug().Msg("Created clients") - defer cleanup(ctx) - } - svc := &service{modifyConfig: &cfg, name: cfg.ServiceName} - - // Open SCM handle - scm, code, err := mod.openSCM(ctx) - if err != nil { - return fmt.Errorf("failed to create service with code %d: %w", code, err) - } - mod.log.Debug().Msg("Opened handle to SCM") - - // Open service handle - if svc.handle, code, err = mod.openService(ctx, scm, svc.name); err != nil { - return fmt.Errorf("failed to open service with code %d: %w", code, err) - } - mod.log.Debug().Str("service", svc.name).Msg("Opened service") - - // Stop service before editing - if !cfg.NoStart { - if code, err = mod.stopService(ctx, scm, svc); err != nil { - mod.log.Warn().Err(err).Msg("Failed to stop existing service") - } else if code == windows.ERROR_SERVICE_NOT_ACTIVE { - mod.log.Debug().Str("service", svc.name).Msg("Service is not running") - } else { - mod.log.Info().Str("service", svc.name).Msg("Stopped existing service") - defer func() { - if code, err = mod.startService(ctx, scm, svc); err != nil { - mod.log.Error().Err(err).Msg("Failed to restore service state to running") - } - }() - } - } - if code, err = mod.queryServiceConfig(ctx, svc); err != nil { - return fmt.Errorf("failed to query service configuration with code %d: %w", code, err) - } - mod.log.Debug(). - Str("service", svc.name). - Str("command", svc.svcConfig.BinaryPathName).Msg("Fetched existing service configuration") - - // Change service configuration - if code, err = mod.changeServiceConfigBinary(ctx, svc, cmd); err != nil { - return fmt.Errorf("failed to edit service configuration with code %d: %w", code, err) - } - defer func() { - // Revert configuration - if code, err = mod.changeServiceConfigBinary(ctx, svc, svc.svcConfig.BinaryPathName); err != nil { - mod.log.Error().Err(err).Msg("Failed to restore service configuration") - } else { - mod.log.Info().Str("service", svc.name).Msg("Restored service configuration") - } - }() - mod.log.Info(). - Str("service", svc.name). - Str("command", cmd).Msg("Changed service configuration") - - // Start service - if !cfg.NoStart { - if code, err = mod.startService(ctx, scm, svc); err != nil { - if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { - // In case of timeout or cancel, try to reestablish a connection to restore the service - mod.log.Info().Msg("Service start timeout/cancelled. Execution likely successful") - mod.log.Info().Msg("Reconnecting for cleanup procedure") - ctx = vctx - - if _, err = mod.createClients(ctx); err != nil { - mod.log.Error().Err(err).Msg("Reconnect failed") - - } else if scm, code, err = mod.openSCM(ctx); err != nil { - mod.log.Error().Err(err).Msg("Failed to reopen SCM") - - } else if svc.handle, code, err = mod.openService(ctx, scm, svc.name); err != nil { - mod.log.Error().Str("service", svc.name).Err(err).Msg("Failed to reopen service handle") - - } else { - mod.log.Debug().Str("service", svc.name).Msg("Reconnection successful") - } - } else { - mod.log.Error().Err(err).Msg("Failed to start service") - } - } else { - mod.log.Info().Str("service", svc.name).Msg("Started service") - } - defer func() { - // Stop service - if code, err = mod.stopService(ctx, scm, svc); err != nil { - mod.log.Error().Err(err).Msg("Failed to stop service") - } else { - mod.log.Info().Str("service", svc.name).Msg("Stopped service") - } - }() - } - } - } else { - return fmt.Errorf("invalid method: %s", ecfg.ExecutionMethod) - } - return err -} diff --git a/pkg/exec/scmr/module.go b/pkg/exec/scmr/module.go deleted file mode 100644 index fd57bc7..0000000 --- a/pkg/exec/scmr/module.go +++ /dev/null @@ -1,31 +0,0 @@ -package scmrexec - -import ( - "github.com/FalconOpsLLC/goexec/pkg/client/dcerpc" - "github.com/RedTeamPentesting/adauth" - "github.com/oiweiwei/go-msrpc/msrpc/scmr/svcctl/v2" - "github.com/rs/zerolog" -) - -type Module struct { - creds *adauth.Credential - target *adauth.Target - hostname string - - log zerolog.Logger - dce *dcerpc.DCEClient - ctl svcctl.SvcctlClient -} - -type MethodCreateConfig struct { - NoDelete bool - ServiceName string - DisplayName string - ServiceType uint32 - StartType uint32 -} - -type MethodModifyConfig struct { - NoStart bool - ServiceName string -} diff --git a/pkg/exec/scmr/scmr.go b/pkg/exec/scmr/scmr.go deleted file mode 100644 index e9ef53f..0000000 --- a/pkg/exec/scmr/scmr.go +++ /dev/null @@ -1,238 +0,0 @@ -package scmrexec - -import ( - "context" - "errors" - "fmt" - "github.com/FalconOpsLLC/goexec/internal/util" - "github.com/FalconOpsLLC/goexec/pkg/exec" - "github.com/FalconOpsLLC/goexec/pkg/windows" - "github.com/oiweiwei/go-msrpc/msrpc/scmr/svcctl/v2" -) - -type service struct { - name string - exec string - createConfig *MethodCreateConfig - modifyConfig *MethodModifyConfig - - svcState uint32 - svcConfig *svcctl.QueryServiceConfigW - handle *svcctl.Handle -} - -// openSCM opens a handle to SCM via ROpenSCManagerW -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/dc84adb3-d51d-48eb-820d-ba1c6ca5faf2 -func (mod *Module) openSCM(ctx context.Context) (scm *svcctl.Handle, code uint32, err error) { - if mod.ctl != nil { - - hostname := mod.hostname - if hostname == "" { - hostname = util.RandomHostname() - } - if response, err := mod.ctl.OpenSCMW(ctx, &svcctl.OpenSCMWRequest{ - MachineName: hostname + "\x00", // lpMachineName; The server's name (i.e. DC01, dc01.domain.local) - DatabaseName: "ServicesActive\x00", // lpDatabaseName; must be "ServicesActive" or "ServicesFailed" - DesiredAccess: ServiceModifyAccess, // dwDesiredAccess; requested access - appears to be ignored? - }); err != nil { - - if response != nil { - return nil, response.Return, fmt.Errorf("open scm response: %w", err) - } - return nil, 0, fmt.Errorf("open scm: %w", err) - } else { - return response.SCM, 0, nil - } - } - return nil, 0, errors.New("invalid arguments") -} - -// createService creates a service with the provided configuration via RCreateServiceW -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/6a8ca926-9477-4dd4-b766-692fab07227e -func (mod *Module) createService(ctx context.Context, scm *svcctl.Handle, scfg *service, ecfg *exec.ExecutionConfig) (code uint32, err error) { - if mod.ctl != nil && scm != nil && scfg != nil && scfg.createConfig != nil { - cfg := scfg.createConfig - if response, err := mod.ctl.CreateServiceW(ctx, &svcctl.CreateServiceWRequest{ - ServiceManager: scm, - ServiceName: cfg.ServiceName + "\x00", - DisplayName: cfg.DisplayName + "\x00", - BinaryPathName: ecfg.GetRawCommand() + "\x00", - ServiceType: cfg.ServiceType, - StartType: cfg.StartType, - DesiredAccess: ServiceCreateAccess, - }); err != nil { - - if response != nil { - return response.Return, fmt.Errorf("create service response: %w", err) - } - return 0, fmt.Errorf("create service: %w", err) - } else { - scfg.handle = response.Service - return response.Return, err - } - } - return 0, errors.New("invalid arguments") -} - -// openService opens a handle to a service given the service name (lpServiceName) -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/6d0a4225-451b-4132-894d-7cef7aecfd2d -func (mod *Module) openService(ctx context.Context, scm *svcctl.Handle, svcName string) (*svcctl.Handle, uint32, error) { - if mod.ctl != nil && scm != nil { - if openResponse, err := mod.ctl.OpenServiceW(ctx, &svcctl.OpenServiceWRequest{ - ServiceManager: scm, - ServiceName: svcName, - DesiredAccess: ServiceAllAccess, - }); err != nil { - if openResponse != nil { - if openResponse.Return == windows.ERROR_SERVICE_DOES_NOT_EXIST { - return nil, openResponse.Return, fmt.Errorf("remote service does not exist: %s", svcName) - } - return nil, openResponse.Return, fmt.Errorf("open service response: %w", err) - } - return nil, 0, fmt.Errorf("open service: %w", err) - } else { - return openResponse.Service, 0, nil - } - } - return nil, 0, errors.New("invalid arguments") -} - -// deleteService deletes an existing service with RDeleteService -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/6744cdb8-f162-4be0-bb31-98996b6495be -func (mod *Module) deleteService(ctx context.Context, scm *svcctl.Handle, svc *service) (code uint32, err error) { - if mod.ctl != nil && scm != nil && svc != nil { - if deleteResponse, err := mod.ctl.DeleteService(ctx, &svcctl.DeleteServiceRequest{Service: svc.handle}); err != nil { - defer func() {}() - if deleteResponse != nil { - return deleteResponse.Return, fmt.Errorf("delete service response: %w", err) - } - return 0, fmt.Errorf("delete service: %w", err) - } - return 0, nil - } - return 0, errors.New("invalid arguments") -} - -// controlService sets the state of the provided process -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/e1c478be-117f-4512-9b67-17c20a48af97 -func (mod *Module) controlService(ctx context.Context, scm *svcctl.Handle, svc *service, control uint32) (code uint32, err error) { - if mod.ctl != nil && scm != nil && svc != nil { - if controlResponse, err := mod.ctl.ControlService(ctx, &svcctl.ControlServiceRequest{ - Service: svc.handle, - Control: control, - }); err != nil { - if controlResponse != nil { - return controlResponse.Return, fmt.Errorf("control service response: %w", err) - } - return 0, fmt.Errorf("control service: %w", err) - } - return 0, nil - } - return 0, errors.New("invalid arguments") -} - -// stopService sends stop signal to existing service using controlService -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/e1c478be-117f-4512-9b67-17c20a48af97 -func (mod *Module) stopService(ctx context.Context, scm *svcctl.Handle, svc *service) (code uint32, err error) { - if code, err = mod.controlService(ctx, scm, svc, windows.SERVICE_CONTROL_STOP); code == windows.ERROR_SERVICE_NOT_ACTIVE { - err = nil - } - return -} - -// startService starts the specified service with RStartServiceW -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/d9be95a2-cf01-4bdc-b30f-6fe4b37ada16 -func (mod *Module) startService(ctx context.Context, scm *svcctl.Handle, svc *service) (code uint32, err error) { - if mod.ctl != nil && scm != nil && svc != nil { - if startResponse, err := mod.ctl.StartServiceW(ctx, &svcctl.StartServiceWRequest{Service: svc.handle}); err != nil { - if startResponse != nil { - // TODO: check if service is already running, return nil error if so - if startResponse.Return == windows.ERROR_SERVICE_REQUEST_TIMEOUT { - return 0, nil - } - return startResponse.Return, fmt.Errorf("start service response: %w", err) - } - return 0, fmt.Errorf("start service: %w", err) - } - return 0, nil - } - return 0, errors.New("invalid arguments") -} - -// closeService closes the specified service handle using RCloseServiceHandle -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/a2a4e174-09fb-4e55-bad3-f77c4b13245c -func (mod *Module) closeService(ctx context.Context, svc *svcctl.Handle) (code uint32, err error) { - if mod.ctl != nil && svc != nil { - if closeResponse, err := mod.ctl.CloseService(ctx, &svcctl.CloseServiceRequest{ServiceObject: svc}); err != nil { - if closeResponse != nil { - return closeResponse.Return, fmt.Errorf("close service response: %w", err) - } - return 0, fmt.Errorf("close service: %w", err) - } - return 0, nil - } - return 0, errors.New("invalid arguments") -} - -// getServiceConfig fetches the configuration details of a service given a handle passed in a service{} structure. -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/89e2d5b1-19cf-44ca-969f-38eea9fe7f3c -func (mod *Module) queryServiceConfig(ctx context.Context, svc *service) (code uint32, err error) { - if mod.ctl != nil && svc != nil && svc.handle != nil { - if getResponse, err := mod.ctl.QueryServiceConfigW(ctx, &svcctl.QueryServiceConfigWRequest{ - Service: svc.handle, - BufferLength: 1024 * 8, - }); err != nil { - if getResponse != nil { - return getResponse.Return, fmt.Errorf("get service config response: %w", err) - } - return 0, fmt.Errorf("get service config: %w", err) - } else { - svc.svcConfig = getResponse.ServiceConfig - return code, err - } - } - return 0, errors.New("invalid arguments") -} - -// queryServiceStatus fetches the state of the specified service -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/cf94d915-b4e1-40e5-872b-a9cb3ad09b46 -func (mod *Module) queryServiceStatus(ctx context.Context, svc *service) (uint32, error) { - if mod.ctl != nil && svc != nil { - if queryResponse, err := mod.ctl.QueryServiceStatus(ctx, &svcctl.QueryServiceStatusRequest{Service: svc.handle}); err != nil { - if queryResponse != nil { - return queryResponse.Return, fmt.Errorf("query service status response: %w", err) - } - return 0, fmt.Errorf("query service status: %w", err) - } else { - svc.svcState = queryResponse.ServiceStatus.CurrentState - return 0, nil - } - } - return 0, errors.New("invalid arguments") -} - -// changeServiceConfigBinary edits the provided service's lpBinaryPathName -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/61ea7ed0-c49d-4152-a164-b4830f16c8a4 -func (mod *Module) changeServiceConfigBinary(ctx context.Context, svc *service, bin string) (code uint32, err error) { - if mod.ctl != nil && svc != nil && svc.handle != nil { - if changeResponse, err := mod.ctl.ChangeServiceConfigW(ctx, &svcctl.ChangeServiceConfigWRequest{ - Service: svc.handle, - ServiceType: svc.svcConfig.ServiceType, - StartType: svc.svcConfig.StartType, - ErrorControl: svc.svcConfig.ErrorControl, - BinaryPathName: bin + "\x00", - LoadOrderGroup: svc.svcConfig.LoadOrderGroup, - TagID: svc.svcConfig.TagID, - // Dependencies: svc.svcConfig.Dependencies // TODO - ServiceStartName: svc.svcConfig.ServiceStartName, - DisplayName: svc.svcConfig.DisplayName, - }); err != nil { - if changeResponse != nil { - return changeResponse.Return, fmt.Errorf("change service config response: %w", err) - } - return 0, fmt.Errorf("change service config: %w", err) - } - return - } - return 0, errors.New("invalid arguments") -} diff --git a/pkg/exec/tsch/exec.go b/pkg/exec/tsch/exec.go deleted file mode 100644 index 868f9ea..0000000 --- a/pkg/exec/tsch/exec.go +++ /dev/null @@ -1,289 +0,0 @@ -package tschexec - -import ( - "context" - "encoding/xml" - "errors" - "fmt" - "github.com/FalconOpsLLC/goexec/internal/util" - dce "github.com/FalconOpsLLC/goexec/pkg/client/dcerpc" - "github.com/FalconOpsLLC/goexec/pkg/exec" - "github.com/RedTeamPentesting/adauth" - "github.com/oiweiwei/go-msrpc/dcerpc" - "github.com/oiweiwei/go-msrpc/msrpc/tsch/itaskschedulerservice/v1" - "github.com/rs/zerolog" - "regexp" - "time" -) - -const ( - TaskXMLDurationFormat = "2006-01-02T15:04:05.9999999Z" - TaskXMLHeader = `<?xml version="1.0" encoding="UTF-16"?>` -) - -var ( - TaskPathRegex = regexp.MustCompile(`^\\[^ :/\\][^:/]*$`) // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsch/fa8809c8-4f0f-4c6d-994a-6c10308757c1 - TaskNameRegex = regexp.MustCompile(`^[^ :/\\][^:/\\]*$`) -) - -// *very* simple implementation of xs:duration - only accepts +seconds -func xmlDuration(dur time.Duration) string { - if s := int(dur.Seconds()); s >= 0 { - return fmt.Sprintf(`PT%dS`, s) - } - return `PT0S` -} - -// Connect to the target & initialize DCE & TSCH clients -func (mod *Module) Connect(ctx context.Context, creds *adauth.Credential, target *adauth.Target) (err error) { - if mod.dce == nil { - mod.dce = dce.NewDCEClient(ctx, false, &dce.SmbConfig{}) - if err = mod.dce.Connect(ctx, creds, target); err != nil { - return fmt.Errorf("DCE connect: %w", err) - } else if mod.tsch, err = itaskschedulerservice.NewTaskSchedulerServiceClient(ctx, mod.dce.DCE(), dcerpc.WithSecurityLevel(dcerpc.AuthLevelPktPrivacy)); err != nil { - return fmt.Errorf("init MS-TSCH client: %w", err) - } - mod.log.Info().Msg("DCE connection successful") - } - return -} - -func (mod *Module) Cleanup(ctx context.Context, creds *adauth.Credential, target *adauth.Target, ccfg *exec.CleanupConfig) (err error) { - mod.log = zerolog.Ctx(ctx).With(). - Str("module", "tsch"). - Str("method", ccfg.CleanupMethod).Logger() - mod.creds = creds - mod.target = target - - if ccfg.CleanupMethod == MethodDelete { - if cfg, ok := ccfg.CleanupMethodConfig.(MethodDeleteConfig); !ok { - return errors.New("invalid configuration") - } else { - if err = mod.Connect(ctx, creds, target); err != nil { - return fmt.Errorf("connect: %w", err) - } else if _, err = mod.tsch.Delete(ctx, &itaskschedulerservice.DeleteRequest{ - Path: cfg.TaskPath, - Flags: 0, - }); err != nil { - mod.log.Error().Err(err).Str("task", cfg.TaskPath).Msg("Failed to delete task") - return fmt.Errorf("delete task: %w", err) - } else { - mod.log.Info().Str("task", cfg.TaskPath).Msg("Task deleted successfully") - } - } - } else { - return fmt.Errorf("method not implemented: %s", ccfg.CleanupMethod) - } - return -} - -func (mod *Module) Exec(ctx context.Context, creds *adauth.Credential, target *adauth.Target, ecfg *exec.ExecutionConfig) (err error) { - - mod.log = zerolog.Ctx(ctx).With(). - Str("module", "tsch"). - Str("method", ecfg.ExecutionMethod).Logger() - mod.creds = creds - mod.target = target - - if ecfg.ExecutionMethod == MethodRegister { - if cfg, ok := ecfg.ExecutionMethodConfig.(MethodRegisterConfig); !ok { - return errors.New("invalid configuration") - - } else { - startTime := time.Now().UTC().Add(cfg.StartDelay) - stopTime := startTime.Add(cfg.StopDelay) - - task := &task{ - TaskVersion: "1.2", // static - TaskNamespace: "http://schemas.microsoft.com/windows/2004/02/mit/task", // static - TimeTriggers: []taskTimeTrigger{ - { - StartBoundary: startTime.Format(TaskXMLDurationFormat), - Enabled: true, - }, - }, - Principals: defaultPrincipals, - Settings: defaultSettings, - Actions: actions{ - Context: defaultPrincipals.Principals[0].ID, - Exec: []actionExec{ - { - Command: ecfg.ExecutableName, - Arguments: ecfg.ExecutableArgs, - }, - }, - }, - } - if !cfg.NoDelete && !cfg.CallDelete { - if cfg.StopDelay == 0 { - // EndBoundary cannot be >= StartBoundary - cfg.StopDelay = 1 * time.Second - } - task.Settings.DeleteExpiredTaskAfter = xmlDuration(cfg.DeleteDelay) - task.TimeTriggers[0].EndBoundary = stopTime.Format(TaskXMLDurationFormat) - } - - if doc, err := xml.Marshal(task); err != nil { - return fmt.Errorf("marshal task XML: %w", err) - - } else { - mod.log.Debug().Str("task", string(doc)).Msg("Task XML generated") - docStr := TaskXMLHeader + string(doc) - - taskPath := cfg.TaskPath - taskName := cfg.TaskName - - if taskName == "" { - taskName = util.RandomString() - } - if taskPath == "" { - taskPath = `\` + taskName - } - - if err = mod.Connect(ctx, creds, target); err != nil { - return fmt.Errorf("connect: %w", err) - } - defer func() { - if err = mod.dce.Close(ctx); err != nil { - mod.log.Warn().Err(err).Msg("Failed to dispose dce client") - } else { - mod.log.Debug().Msg("Disposed DCE client") - } - }() - var response *itaskschedulerservice.RegisterTaskResponse - if response, err = mod.tsch.RegisterTask(ctx, &itaskschedulerservice.RegisterTaskRequest{ - Path: taskPath, - XML: docStr, - Flags: 0, // TODO - LogonType: 0, // TASK_LOGON_NONE - CredsCount: 0, - Creds: nil, - }); err != nil { - return err - - } else { - mod.log.Info().Str("path", response.ActualPath).Msg("Task registered successfully") - - if !cfg.NoDelete { - if cfg.CallDelete { - defer func() { - if err = mod.Cleanup(ctx, creds, target, &exec.CleanupConfig{ - CleanupMethod: MethodDelete, - CleanupMethodConfig: MethodDeleteConfig{TaskPath: taskPath}, - }); err != nil { - mod.log.Error().Err(err).Msg("Failed to delete task") - } - }() - mod.log.Info().Dur("ms", cfg.StartDelay).Msg("Waiting for task to run") - select { - case <-ctx.Done(): - mod.log.Warn().Msg("Cancelling execution") - return err - case <-time.After(cfg.StartDelay + (time.Second * 2)): // + two seconds - // TODO: check if task is running yet; delete if the wait period is over - break - } - return err - } else { - mod.log.Info().Time("when", stopTime).Msg("Task is scheduled to delete") - } - } - } - } - } - } else if ecfg.ExecutionMethod == MethodDemand { - if cfg, ok := ecfg.ExecutionMethodConfig.(MethodDemandConfig); !ok { - return errors.New("invalid configuration") - - } else { - taskPath := cfg.TaskPath - taskName := cfg.TaskName - - if taskName == "" { - mod.log.Debug().Msg("Task name not defined. Using random string") - taskName = util.RandomString() - } - if taskPath == "" { - taskPath = `\` + taskName - } - if !TaskNameRegex.MatchString(taskName) { - return fmt.Errorf("invalid task name: %s", taskName) - } - if !TaskPathRegex.MatchString(taskPath) { - return fmt.Errorf("invalid task path: %s", taskPath) - } - - mod.log.Debug().Msg("Using demand method") - settings := defaultSettings - settings.AllowStartOnDemand = true - task := &task{ - TaskVersion: "1.2", // static - TaskNamespace: "http://schemas.microsoft.com/windows/2004/02/mit/task", // static - Principals: defaultPrincipals, - Settings: defaultSettings, - Actions: actions{ - Context: defaultPrincipals.Principals[0].ID, - Exec: []actionExec{ - { - Command: ecfg.ExecutableName, - Arguments: ecfg.ExecutableArgs, - }, - }, - }, - } - if doc, err := xml.Marshal(task); err != nil { - return fmt.Errorf("marshal task: %w", err) - } else { - docStr := TaskXMLHeader + string(doc) - - if err = mod.Connect(ctx, creds, target); err != nil { - return fmt.Errorf("connect: %w", err) - } - defer func() { - if err = mod.dce.Close(ctx); err != nil { - mod.log.Warn().Err(err).Msg("Failed to dispose dce client") - } else { - mod.log.Debug().Msg("Disposed DCE client") - } - }() - - var response *itaskschedulerservice.RegisterTaskResponse - if response, err = mod.tsch.RegisterTask(ctx, &itaskschedulerservice.RegisterTaskRequest{ - Path: taskPath, - XML: docStr, - Flags: 0, // TODO - LogonType: 0, // TASK_LOGON_NONE - CredsCount: 0, - Creds: nil, - }); err != nil { - return fmt.Errorf("register task: %w", err) - - } else { - mod.log.Info().Str("task", response.ActualPath).Msg("Task registered successfully") - if !cfg.NoDelete { - defer func() { - if err = mod.Cleanup(ctx, creds, target, &exec.CleanupConfig{ - CleanupMethod: MethodDelete, - CleanupMethodConfig: MethodDeleteConfig{TaskPath: taskPath}, - }); err != nil { - mod.log.Error().Err(err).Msg("Failed to delete task") - } - }() - } - if _, err = mod.tsch.Run(ctx, &itaskschedulerservice.RunRequest{ - Path: response.ActualPath, - Flags: 0, // Maybe we want to use these? - }); err != nil { - return err - } else { - mod.log.Info().Str("task", response.ActualPath).Msg("Started task") - } - } - } - } - } else { - return fmt.Errorf("method not implemented: %s", ecfg.ExecutionMethod) - } - - return nil -} diff --git a/pkg/exec/tsch/module.go b/pkg/exec/tsch/module.go deleted file mode 100644 index 077951b..0000000 --- a/pkg/exec/tsch/module.go +++ /dev/null @@ -1,56 +0,0 @@ -package tschexec - -import ( - "context" - "github.com/FalconOpsLLC/goexec/pkg/client/dcerpc" - "github.com/RedTeamPentesting/adauth" - "github.com/oiweiwei/go-msrpc/msrpc/tsch/itaskschedulerservice/v1" - "github.com/rs/zerolog" - "time" -) - -type Step struct { - Name string // Name of the step - Status string // Status indicates whether the task succeeded, failed, etc. - Call func(context.Context, *Module, ...any) (interface{}, error) // Call will invoke the procedure - Match func(context.Context, *Module, ...any) (bool, error) // Match will make an assertion to determine whether the step was successful -} - -type Module struct { - creds *adauth.Credential - target *adauth.Target - - log zerolog.Logger - dce *dcerpc.DCEClient - tsch itaskschedulerservice.TaskSchedulerServiceClient -} - -type MethodRegisterConfig struct { - NoDelete bool - CallDelete bool - TaskName string - TaskPath string - StartDelay time.Duration - StopDelay time.Duration - DeleteDelay time.Duration -} - -type MethodDemandConfig struct { - NoDelete bool - CallDelete bool - TaskName string - TaskPath string - StopDelay time.Duration - DeleteDelay time.Duration -} - -type MethodDeleteConfig struct { - TaskPath string -} - -const ( - MethodRegister string = "register" - MethodDemand string = "demand" - MethodDelete string = "delete" - MethodChange string = "update" -) diff --git a/pkg/exec/tsch/tsch.go b/pkg/exec/tsch/tsch.go deleted file mode 100644 index bc3ed0b..0000000 --- a/pkg/exec/tsch/tsch.go +++ /dev/null @@ -1,102 +0,0 @@ -package tschexec - -import ( - "encoding/xml" -) - -// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsch/0d6383e4-de92-43e7-b0bb-a60cfa36379f - -type taskTimeTrigger struct { - XMLName xml.Name `xml:"TimeTrigger"` - StartBoundary string `xml:"StartBoundary,omitempty"` // Derived from time.Time - EndBoundary string `xml:"EndBoundary,omitempty"` // Derived from time.Time; must be > StartBoundary - Enabled bool `xml:"Enabled"` -} - -type idleSettings struct { - StopOnIdleEnd bool `xml:"StopOnIdleEnd"` - RestartOnIdle bool `xml:"RestartOnIdle"` -} - -type settings struct { - XMLName xml.Name `xml:"Settings"` - Enabled bool `xml:"Enabled"` - Hidden bool `xml:"Hidden"` - DisallowStartIfOnBatteries bool `xml:"DisallowStartIfOnBatteries"` - StopIfGoingOnBatteries bool `xml:"StopIfGoingOnBatteries"` - AllowHardTerminate bool `xml:"AllowHardTerminate"` - RunOnlyIfNetworkAvailable bool `xml:"RunOnlyIfNetworkAvailable"` - AllowStartOnDemand bool `xml:"AllowStartOnDemand"` - WakeToRun bool `xml:"WakeToRun"` - RunOnlyIfIdle bool `xml:"RunOnlyIfIdle"` - StartWhenAvailable bool `xml:"StartWhenAvailable"` - Priority int `xml:"Priority,omitempty"` // 1 to 10 inclusive - MultipleInstancesPolicy string `xml:"MultipleInstancesPolicy,omitempty"` - ExecutionTimeLimit string `xml:"ExecutionTimeLimit,omitempty"` - DeleteExpiredTaskAfter string `xml:"DeleteExpiredTaskAfter,omitempty"` // Derived from time.Duration - IdleSettings idleSettings `xml:"IdleSettings,omitempty"` -} - -type actionExec struct { - XMLName xml.Name `xml:"Exec"` - Command string `xml:"Command"` - Arguments string `xml:"Arguments"` -} - -type actions struct { - XMLName xml.Name `xml:"Actions"` - Context string `xml:"Context,attr"` - Exec []actionExec `xml:"Exec,omitempty"` -} - -type principals struct { - XMLName xml.Name `xml:"Principals"` - Principals []principal `xml:"Principal"` -} - -type principal struct { - XMLName xml.Name `xml:"Principal"` - ID string `xml:"id,attr"` - UserID string `xml:"UserId"` - RunLevel string `xml:"RunLevel"` -} - -type task struct { - XMLName xml.Name `xml:"Task"` - TaskVersion string `xml:"version,attr"` - TaskNamespace string `xml:"xmlns,attr"` - TimeTriggers []taskTimeTrigger `xml:"Triggers>TimeTrigger,omitempty"` - Actions actions `xml:"Actions"` - Principals principals `xml:"Principals"` - Settings settings `xml:"Settings"` -} - -var ( - defaultSettings = settings{ - MultipleInstancesPolicy: "IgnoreNew", - DisallowStartIfOnBatteries: false, - StopIfGoingOnBatteries: false, - AllowHardTerminate: true, - RunOnlyIfNetworkAvailable: false, - IdleSettings: idleSettings{ - StopOnIdleEnd: true, - RestartOnIdle: false, - }, - AllowStartOnDemand: true, - Enabled: true, - Hidden: true, - RunOnlyIfIdle: false, - WakeToRun: false, - Priority: 7, // 7 is a pretty standard value for scheduled tasks - StartWhenAvailable: true, - } - defaultPrincipals = principals{ - Principals: []principal{ - { - ID: "SYSTEM", - UserID: "S-1-5-18", - RunLevel: "HighestAvailable", - }, - }, - } -) diff --git a/pkg/windows/const.go b/pkg/windows/const.go deleted file mode 100644 index 4c4fbe6..0000000 --- a/pkg/windows/const.go +++ /dev/null @@ -1,37 +0,0 @@ -package windows - -const ( - // Windows error codes - ERROR_FILE_NOT_FOUND uint32 = 0x00000002 - ERROR_SERVICE_REQUEST_TIMEOUT uint32 = 0x0000041d - ERROR_SERVICE_DOES_NOT_EXIST uint32 = 0x00000424 - ERROR_SERVICE_NOT_ACTIVE uint32 = 0x00000426 - - // Windows service/scm constants - SERVICE_BOOT_START uint32 = 0x00000000 - SERVICE_SYSTEM_START uint32 = 0x00000001 - SERVICE_AUTO_START uint32 = 0x00000002 - SERVICE_DEMAND_START uint32 = 0x00000003 - SERVICE_DISABLED uint32 = 0x00000004 - - // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-scmr/4e91ff36-ab5f-49ed-a43d-a308e72b0b3c - SERVICE_CONTINUE_PENDING uint32 = 0x00000005 - SERVICE_PAUSE_PENDING uint32 = 0x00000006 - SERVICE_PAUSED uint32 = 0x00000007 - SERVICE_RUNNING uint32 = 0x00000004 - SERVICE_START_PENDING uint32 = 0x00000002 - SERVICE_STOP_PENDING uint32 = 0x00000003 - SERVICE_STOPPED uint32 = 0x00000001 - - SERVICE_WIN32_OWN_PROCESS uint32 = 0x00000010 - - SERVICE_CONTROL_STOP uint32 = 0x00000001 - SC_MANAGER_CREATE_SERVICE uint32 = 0x00000002 - - // https://learn.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights - SERVICE_QUERY_CONFIG uint32 = 0x00000001 - SERVICE_CHANGE_CONFIG uint32 = 0x00000002 - SERVICE_START uint32 = 0x00000010 - SERVICE_STOP uint32 = 0x00000020 - SERVICE_DELETE uint32 = 0x00010000 // special permission -) |