cmd

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 10, 2021 License: GPL-3.0 Imports: 14 Imported by: 5

Documentation

Index

Constants

View Source
const (
	// True is the 'true' bool value.
	True = boolean(2)
	// False is the 'false' bool value.
	False = boolean(1)
	// Empty represents the absence of a value.
	Empty = boolean(0)
)
View Source
const (
	// VerbEdit launches an editor and opens the document for editing. If the target is not a document file,
	// the function will fail.
	VerbEdit = Verb("edit")
	// VerbFind initiates a search beginning in the directory specified by the working directory.
	VerbFind = Verb("find")
	// VerbOpen opens the item specified by the target parameter. The item can be a file or folder.
	VerbOpen = Verb("open")
	// VerbPrint prints the file specified by the target. If the target is not a document file, the function fails.
	VerbPrint = Verb("print")
	// VerbRunAs launches an application as Administrator. User Account Control (UAC) will prompt the user for consent to run
	// the application elevated or enter the credentials of an administrator account used to run the application.
	VerbRunAs = Verb("runas")
	//VerbExplore explores a folder specified by the target.
	VerbExplore = Verb("explore")
)

Variables

View Source
var (
	// ErrEmptyCommand is an error returned when attempting to start a Process that has an empty 'Args' array.
	ErrEmptyCommand = xerr.New("process arguments are empty")
	// ErrNotCompleted is returned when attempting to access the exit code on a running process or wait on a
	// non-stared proess.
	ErrNotCompleted = xerr.New("the process has not yet completed or was not started")
	// ErrAlreadyStarted is an error returned by the 'Start' or 'Run' functions when attempting to start a process
	// that has already been started via a 'Start' or 'Run' function call.
	ErrAlreadyStarted = xerr.New("process has already been started")
	// ErrNoProcessFound is returned by the SetParent* functions on Windows devices when a specified parent process
	// could not be found.
	ErrNoProcessFound = xerr.New("could not find a suitable parent process")
)
View Source
var RandomParent = &Filter{Fallback: false}

RandomParent is a Filter that can be used by default to select ANY random process on the target device to be used as the parent process without crteating a new Filter struct.

Functions

func Fork

func Fork() (uint32, error)

Fork will attempt to use built-in system utilities to fork off the process into a separate, but similar process. If successful, this function will return the PID of the new process.

func ShellExecute

func ShellExecute(v Verb, f int32, dir string, args ...string) error

ShellExecute calls the Windows ShellExecuteW API function. This will "preform an operation on the specified target" from the API documentation. The parameters include the Verb (required), Flags, Working Directory and Arguments. The first string specified in args is the value that will fill 'lpFile' and the rest will be filled into the 'lpArguments' parameter. Otherwise, if empty, they will both be nil. The error returned will be nil if the function call is successful. Always returns 'ErrNoWindows' if the device is not running Windows.

func Split

func Split(s string) []string

Split will attempt to split the specified string based on the escape characters and spaces while attempting to preserve anything that is not a splitting space. This will automatically detect quotes and backslashes. The return result is a string array that can be used as args,

Types

type Code

type Code struct {
	Data []byte

	Timeout time.Duration
	// contains filtered or unexported fields
}

Code is a struct that can be used to contain and run shellcode on Windows devices. This struct has many of the functionallies of the standard 'cmd.Program' function. The 'SetParent*' function will attempt to set the target that runs the shellcode. If none are specified, the shellcode will be injected into the current process. This struct only works on Windows devices. All calls on non-Windows devices will return 'ErrNotSupportedOS'. TODO: Add Linux shellcode execution support.

func NewCode

func NewCode(b []byte) *Code

NewCode creates a new Code thread instance that uses the supplied byte array as the Data buffer . Similar to '&Code{Data: b}'.

func NewCodeContext

func NewCodeContext(x context.Context, b []byte) *Code

NewCodeContext creates a new Code thread instance that uses the supplied byte array as the Data buffer. This function accepts a context that can be used to control the cancelation of this Code thread.

func (Code) Error

func (c Code) Error() error

Error returns any errors that may have occurred during the Code thread operation.

func (Code) ExitCode

func (c Code) ExitCode() (int32, error)

ExitCode returns the Exit Code of the process. If the Code thread is still running or has not been started, this function returns an 'ErrNotCompleted' error.

func (Code) Handle

func (c Code) Handle() (uintptr, error)

Handle returns the handle of the current running Code thread. The return is a uintptr that can converted into a Handle. This function returns an error if the Code thread was not started. The handle is not expected to be valid after the Code thread exits or is terminated.

func (*Code) Run

func (c *Code) Run() error

Run will start the Code thread and wait until it completes. This function will return the same errors as the 'Start' function if they occur or the 'Wait' function if any errors occur during Code thread runtime.

func (*Code) Running

func (c *Code) Running() bool

Running returns true if the current Code thread is running, false otherwise.

func (*Code) SetParent

func (c *Code) SetParent(f *Filter)

SetParent will instruct the Code thread to choose a parent with the supplied process Filter. If the Filter is nil this will use the current process (default). This function has no effect if the device is not running Windows.

func (*Code) Start

func (c *Code) Start() error

Start will attempt to start the Code thread and will return an errors that occur while starting the Code thread. This function will return 'ErrEmptyCommand' if the 'Data' parameter is empty or nil and 'ErrAlreadyStarted' if attempting to start a Code thread that already has been started previously. Always returns 'ErrNoWindows' on non-Windows devices.

func (*Code) Stop

func (c *Code) Stop() error

Stop will attempt to terminate the currently running Code thread instance. Always returns nil on non-Windows devices.

func (Code) String

func (c Code) String() string

String returns the formatted size of the Code thread data.

func (*Code) Wait

func (c *Code) Wait() error

Wait will block until the Code thread completes or is terminated by a call to Stop. This function will return 'ErrNotCompleted' if the Code thread has not been started

type DLL

type DLL struct {
	Path string

	Timeout time.Duration
	// contains filtered or unexported fields
}

DLL is a struct that can be used to reflectively load a DLL into the memory of a selected process. Similar to the Code struct, this struct can only be used on Windows devices and will return 'ErrNoWindows' on non-Windows devices.

func NewDLL

func NewDLL(p string) *DLL

NewDLL creates a new DLL instance that uses the supplied string as the DLL file path. Similar to '&DLL{Path: p}'.

func NewDllContext

func NewDllContext(x context.Context, p string) *DLL

NewDllContext creates a new DLL instance that uses the supplied string as the DLL file path. This function accepts a context that can be used to control the cancelation of this DLL.

func (DLL) Error

func (d DLL) Error() error

Error returns any errors that may have occurred during the DLL operation.

func (DLL) ExitCode

func (d DLL) ExitCode() (int32, error)

ExitCode returns the Exit Code of the process. If the DLL is still running or has not been started, this function returns an 'ErrNotCompleted' error.

func (DLL) Handle

func (d DLL) Handle() (uintptr, error)

Handle returns the handle of the current running DLL. The return is a uintptr that can converted into a Handle. This function returns an error if the DLL was not started. The handle is not expected to be valid after the DLL exits or is terminated.

func (*DLL) Run

func (d *DLL) Run() error

Run will start the DLL and wait until it completes. This function will return the same errors as the 'Start' function if they occur or the 'Wait' function if any errors occur during DLL runtime.

func (*DLL) Running

func (d *DLL) Running() bool

Running returns true if the current DLL is running, false otherwise.

func (*DLL) SetParent

func (d *DLL) SetParent(f *Filter)

SetParent will instruct the DLL to choose a parent with the supplied process Filter. If the Filter is nil this will use the current process (default). This function has no effect if the device is not running Windows.

func (*DLL) Start

func (d *DLL) Start() error

Start will attempt to start the DLL and will return an errors that occur while starting the DLL. This function will return 'ErrEmptyCommand' if the 'Data' parameter is empty or nil and 'ErrAlreadyStarted' if attempting to start a DLL that already has been started previously. Always returns 'ErrNoWindows' on non-Windows devices.

func (*DLL) Stop

func (d *DLL) Stop() error

Stop will attempt to terminate the currently running DLL instance. Always returns nil on non-Windows devices.

func (DLL) String

func (d DLL) String() string

String returns the formatted size/handle of the DLL data.

func (*DLL) Wait

func (d *DLL) Wait() error

Wait will block until the DLL completes or is terminated by a call to Stop. This function will return 'ErrNotCompleted' if the DLL has not been started

type ExitError

type ExitError struct {
	Exit uint32
}

ExitError is a type of error that is returned by the Wait and Run functions when a function returns an error code other than zero.

func (ExitError) Error

func (e ExitError) Error() string

Error fulfills the error interface and retruns a formatted string that specifies the Process Exit Code.

type Filter

type Filter struct {
	// PID will attempt to select the PID to be used for the parent.
	// If set to zero, it will be ignored. Values of <5 are not valid!
	PID uint32 `json:"pid,omitempty"`
	// Fallback specifies if the opts routine should try again with less constaints
	// than the previous attempt. All attempts will still respect the 'Exclude' and
	// 'Ignore' directives.
	Fallback bool `json:"fallback,omitempty"`
	// Session can be set to 'True' or 'False' to attempt to target processes that
	// are either in or not in a DWM session environment (ie: in a user deskop [True]
	// or a service context [False]). This value is ignored if set to 'Empty'.
	Session boolean `json:"session,omitempty"`
	// Elevated can be set 'True' or 'False' to attempt to target processes that are
	// in a High/System or Lower integrity context. 'True' will attempt to select
	// elevated processes, while 'False' will select lower integrity or non-elevated
	// processes. If set to 'Empty' or omitted, this will be set based on the current
	// process's integrity level (ie: 'True' if device.Elevated == true else 'False').
	Elevated boolean `json:"elevated,omitempty"`
	// Exclude and Include determine the processes that can be included or omitted during
	// process listing. 'Exclude' always takes precedence over 'Include'. Ether one being
	// nil or empty means no processes are included/excluded. All matches are case-insensitive.
	Exclude []string `json:"exclude,omitempty"`
	Include []string `json:"include,omitempty"`
}

Filter is a struct that can be used to set the Parent process for many types of 'cmd.Runnable' compatable interfaces.

Each option can be set directly or chained using the function calls which all return the struct for chain usage.

This struct can be serialized into JSON or written using a Stream Marshaler.

func F

func F() *Filter

F is a shortcut for 'new(Filter)'

func (*Filter) Clear

func (f *Filter) Clear() *Filter

Clear clears the Filter settings, except for 'Fallback' and return the Filter struct.

func (Filter) MarshalStream

func (f Filter) MarshalStream(w data.Writer) error

MarshalStream will attempt to write the Filter data to the supplied Writer and return any errors that may occur.

func (Filter) Select

func (f Filter) Select() (uint32, error)

Select will attempt to find a process with the specified Filter options. If a suitable process is found, the Process ID will be returned. An 'ErrNoProcessFound' error will be returned if no processes that match the Filter match. This function returns 'ErrNoWindows' on non-Windows devices.

func (Filter) SelectFunc

func (f Filter) SelectFunc(x filter) (uint32, error)

SelectFunc will attempt to find a process with the specified Filter options. If a suitable process is found, the Process ID will be returned. An 'ErrNoProcessFound' error will be returned if no processes that match the Filter match. This function returns 'ErrNoWindows' on non-Windows devices.

This function allows for a filtering function to be passed along that will be supplied with the ProcessID, if the process is elevated, the process handle and process name. The function supplied should return true if the process passes the filter. The function argument may be nil.

func (*Filter) SetElevated

func (f *Filter) SetElevated(e bool) *Filter

SetElevated sets the Elevated setting to 'True' or 'False' and returns the Filter struct.

func (*Filter) SetExclude

func (f *Filter) SetExclude(n ...string) *Filter

SetExclude sets the Exclusion list and returns the Filter struct.

func (*Filter) SetFallback

func (f *Filter) SetFallback(i bool) *Filter

SetFallback sets the Fallback setting and returns the Filter struct.

func (*Filter) SetInclude

func (f *Filter) SetInclude(n ...string) *Filter

SetInclude sets the Inclusion list and returns the Filter struct.

func (*Filter) SetPID

func (f *Filter) SetPID(p uint32) *Filter

SetPID sets the target PID and returns the Filter struct.

func (*Filter) SetSession

func (f *Filter) SetSession(s bool) *Filter

SetSession sets the Session setting to 'True' or 'False' and returns the Filter struct.

func (*Filter) UnmarshalStream

func (f *Filter) UnmarshalStream(r data.Reader) error

UnmarshalStream will attempt to read the Filter data from the supplied Reader and return any errors that may occur.

type Process

type Process struct {
	Stdin          io.Reader
	Stdout, Stderr io.Writer

	Dir       string
	Env, Args []string

	Timeout time.Duration
	// contains filtered or unexported fields
}

Process is a struct that represents an executable command and allows for setting options in order change the operating functions.

func NewProcess

func NewProcess(s ...string) *Process

NewProcess creates a new process instance that uses the supplied string vardict as the command line arguments. Similar to '&Process{Args: s}'.

func NewProcessContext

func NewProcessContext(x context.Context, s ...string) *Process

NewProcessContext creates a new process instance that uses the supplied string vardict as the command line arguments. This function accepts a context that can be used to control the cancelation of this process.

func (*Process) CombinedOutput

func (p *Process) CombinedOutput() ([]byte, error)

CombinedOutput runs the Process and returns its combined standard output and standard error.

func (Process) Error

func (p Process) Error() error

Error returns any errors that may have occurred during Process operation.

func (Process) ExitCode

func (p Process) ExitCode() (int32, error)

ExitCode returns the Exit Code of the process. If the Process is still running or has not been started, this function returns an 'ErrNotCompleted' error.

func (Process) Flags

func (p Process) Flags() uint32

Flags returns the current set flags value based on the configured options.

func (Process) Handle

func (p Process) Handle() (uintptr, error)

Handle returns the handle of the current running Process. The return is a uintptr that can converted into a Handle. This function returns an error if the Process was not started. The handle is not expected to be valid after the Process exits or is terminated. This function always returns 'ErrNoWindows' on non-Windows devices.

func (*Process) Output

func (p *Process) Output() ([]byte, error)

Output runs the Process and returns its standard output. Any returned error will usually be of type *ExitError.

func (Process) Pid

func (p Process) Pid() uint64

Pid returns the current process PID. This function returns zero if the process has not been started.

func (*Process) Run

func (p *Process) Run() error

Run will start the process and wait until it completes. This function will return the same errors as the 'Start' function if they occur or the 'Wait' function if any errors occur during Process runtime.

func (*Process) Running

func (p *Process) Running() bool

Running returns true if the current Process is running, false otherwise.

func (*Process) SetChroot

func (*Process) SetChroot(_ string)

SetChroot will set the process Chroot directory at runtime. This function takes the directory path as a string value. Use an empty string "" to disable this setting. The specified Path value is validated at runtime. This function has no effect on Windows devices.

func (*Process) SetDetached

func (p *Process) SetDetached(d bool)

SetDetached will detach or detach the console of the newly spawned process from the parent. This function has no effect on non-console commands. Setting this to true disables SetNewConsole. This function has no effect if the device is not running Windows.

func (*Process) SetFlags

func (p *Process) SetFlags(f uint32)

SetFlags will set the startup Flag values used for Windows programs. This function overrites many of the 'Set*' functions.

func (*Process) SetFullscreen

func (p *Process) SetFullscreen(f bool)

SetFullscreen will set the window fullscreen state of the newly spawned process. This function has no effect on commands that do not generate windows. This function has no effect if the device is not running Windows.

func (*Process) SetGID

func (*Process) SetGID(_ int32)

SetGID will set the process GID at runtime. This function takes the numerical GID value. Use '-1' to disable this setting. The GID value is validated at runtime. This function has no effect on Windows devices.

func (*Process) SetInheritEnv

func (p *Process) SetInheritEnv(i bool)

SetInheritEnv will change the behavior of the Environment variable inheritance on startup. If true (the default), the current Environment variables will be filled in, even if 'Env' is not empty. If set to false, the current Environment variables will not be added into the Process's starting Environment.

func (*Process) SetNewConsole

func (p *Process) SetNewConsole(c bool)

SetNewConsole will allocate a new console for the newly spawned process. This console output will be independent of the parent process. This function has no effect if the device is not running Windows.

func (*Process) SetNoWindow

func (p *Process) SetNoWindow(h bool)

SetNoWindow will hide or show the window of the newly spawned process. This function has no effect on commands that do not generate windows. This function has no effect if the device is not running Windows.

func (*Process) SetParent

func (p *Process) SetParent(f *Filter)

SetParent will instruct the Process to choose a parent with the supplied process Filter. If the Filter is nil this will use the current process (default). This function has no effect if the device is not running Windows. Setting the Parent process will automatically set 'SetNewConsole' to true.

func (*Process) SetSuspended

func (p *Process) SetSuspended(s bool)

SetSuspended will delay the execution of this Process and will put the process in a suspended state until it is resumed using a Resume call. This function has no effect if the device is not running Windows.

func (*Process) SetUID

func (*Process) SetUID(_ int32)

SetUID will set the process UID at runtime. This function takes the numerical UID value. Use '-1' to disable this setting. The UID value is validated at runtime. This function has no effect on Windows devices.

func (*Process) SetWindowDisplay

func (p *Process) SetWindowDisplay(m int)

SetWindowDisplay will set the window display mode of the newly spawned process. This function has no effect on commands that do not generate windows. This function has no effect if the device is not running Windows. See the 'SW_*' values in winuser.h or the Golang windows package documentation for more details.

func (*Process) SetWindowPosition

func (p *Process) SetWindowPosition(x, y uint32)

SetWindowPosition will set the window postion of the newly spawned process. This function has no effect on commands that do not generate windows. This function has no effect if the device is not running Windows.

func (*Process) SetWindowSize

func (p *Process) SetWindowSize(w, h uint32)

SetWindowSize will set the window display size of the newly spawned process. This function has no effect on commands that do not generate windows. This function has no effect if the device is not running Windows.

func (*Process) SetWindowTitle

func (p *Process) SetWindowTitle(s string)

SetWindowTitle will set the title of the new spawned window to the the specified string. This function has no effect on commands that do not generate windows. This function has no effect if the device is not running Windows.

func (*Process) Start

func (p *Process) Start() error

Start will attempt to start the Process and will return an errors that occur while starting the Process. This function will return 'ErrEmptyCommand' if the 'Args' parameter is empty or nil and 'ErrAlreadyStarted' if attempting to start a Process that already has been started previously.

func (*Process) StderrPipe

func (p *Process) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a pipe that will be connected to the Processes's standard error when the Processes starts.

The pipe will be closed after the Processe exits, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe.

See the StdoutPipe example for idiomatic usage.

func (*Process) StdinPipe

func (p *Process) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the Processes's standard input when the Process starts. The pipe will be closed automatically after the Processes starts. A caller need only call Close to force the pipe to close sooner.

func (*Process) StdoutPipe

func (p *Process) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a pipe that will be connected to the Processes's standard output when the Processes starts.

The pipe will be closed after the Processe exits, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe.

See the StdoutPipe example for idiomatic usage.

func (*Process) Stop

func (p *Process) Stop() error

Stop will attempt to terminate the currently running Process instance. Stopping a Process may prevent the ability to read the Stdout/Stderr and any proper exit codes.

func (Process) String

func (p Process) String() string

String returns the command and arguments that this Process will execute.

func (*Process) Wait

func (p *Process) Wait() error

Wait will block until the Process completes or is terminated by a call to Stop. This function will return 'ErrNotCompleted' if the Process has not been started.

type Runnable

type Runnable interface {
	Run() error
	Wait() error
	Stop() error
	Start() error
	Running() bool
	SetParent(Filter)
	ExitCode() (int32, error)
}

Runnable is an interface that helps support the type of structs that can be used for execution, such as Code and Process, which share the same methods as this interface.

type Verb

type Verb string

Verb is the equivalent to the Windows ShellExecute verb type string. This is used in the ShellExecute function.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL