core

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: Apache-2.0 Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultCtrlTimeout = 10 * time.Second

DefaultCtrlTimeout is the maximum time to wait for a listener control response. Kept short (5s) to prevent RPC handler starvation when a listener is disconnected.

Variables

View Source
var (
	Connections = &connections{
		connections: &sync.Map{},
	}
	ListenerSessions = &listenerSessions{
		sessions: &sync.Map{},
	}
	ErrConnectionRemoved = fmt.Errorf("connection removed")
)
View Source
var (
	ErrEventBrokerUnavailable = errors.New("event broker unavailable")
	ErrEventBrokerQueueFull   = errors.New("event broker queue full")
)
View Source
var (
	// Sessions - Manages implant connections
	Sessions         *sessions
	ExtensionModules = []string{consts.ModuleExecuteBof, consts.ModuleExecuteDll}
	// ErrUnknownMessageType - Returned if the implant did not understand the message for
	//                         example when the command is not supported on the platform
	ErrUnknownMessageType = errors.New("unknown message type")

	// ErrImplantSendTimeout - The implant did not respond prior to timeout deadline
	ErrImplantSendTimeout = errors.New("implant timeout")
	ErrSpiteStreamClosed  = errors.New("spite stream writer closed")
)
View Source
var CacheName = "cache.bin"
View Source
var (
	// Clients - Manages client active
	Clients = &clients{
		mutex:  &sync.Mutex{},
		active: map[int]*Client{},
	}
)
View Source
var (
	// EventBroker - Distributes event messages
	EventBroker *eventBroker
)
View Source
var (
	Forwarders = &forwarders{
		forwarders: &sync.Map{},
	}
)
View Source
var (
	GlobalTicker = NewTicker()
)
View Source
var (
	Jobs = &jobs{
		Map: &sync.Map{},
	}
)
View Source
var (
	Listeners = listeners{
		&sync.Map{},
	}
)

Functions

func CurrentJobID

func CurrentJobID() uint32

func ErrorText added in v0.3.0

func ErrorText(err error) string

func GetCurrentID added in v0.0.3

func GetCurrentID() uint32

func GetKeyPairForSession added in v0.1.2

func GetKeyPairForSession(sid uint32, secureConfig *implanttypes.SecureConfig) *clientpb.KeyPair

GetKeyPairForSession 获取会话的密钥对 优先从 ListenerSessions 获取,如果没有则从 secureConfig 获取交换密钥对

func GoGuarded added in v0.3.0

func GoGuarded(label string, fn func() error, onError GoErrorHandler, cleanups ...func()) <-chan error

func HandleFileOperations added in v0.1.0

func HandleFileOperations(op string, data []byte, task *Task) error

func HandleKeylogger added in v0.3.0

func HandleKeylogger(data []byte, task *Task, identifier string, filename string, nonce string) error

func HandleMediaChunk added in v0.3.0

func HandleMediaChunk(task *Task, nonce, identifier, filename, mediaKind string, data []byte) error

func HandleScreenshot added in v0.1.0

func HandleScreenshot(data []byte, task *Task) error

func LoadContext added in v0.1.0

func LoadContext(ctx output.Context) (output.Context, error)

func NewBroker added in v0.0.3

func NewBroker() *eventBroker

func NewSessions added in v0.0.3

func NewSessions() *sessions

func NextCtrlID

func NextCtrlID() uint32

func NextJobID

func NextJobID() uint32

func PushContextEvent added in v0.1.0

func PushContextEvent(Op string, ctx *models.Context)

func ReadFileForContext added in v0.1.0

func ReadFileForContext(ctx output.Context) ([]byte, error)

func RecoverError added in v0.3.0

func RecoverError(label string, recovered any) error

func ResetTransientTransportState added in v0.3.0

func ResetTransientTransportState()

ResetTransientTransportState clears the in-memory listener transport state. It is primarily used by tests that start and stop isolated control planes in the same process.

func RunGuarded added in v0.3.0

func RunGuarded(label string, fn func() error, onError GoErrorHandler, cleanups ...func()) (err error)

func SaveContext added in v0.1.0

func SaveContext(ctx output.Context, task *Task) (*models.Context, error)

func SweepInactiveSessions added in v0.3.0

func SweepInactiveSessions()

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

func NewCache

func NewCache(savePath string) *Cache

NewCache initializes a new cache with a specified size, duration, and save path

func (*Cache) AddMessage

func (c *Cache) AddMessage(spite *implantpb.Spite, index int)

AddMessage adds a new item to the cache with TaskId and Index as part of the key

func (*Cache) GetAll

func (c *Cache) GetAll() map[string]*implantpb.Spite

GetAll returns all items in the cache

func (*Cache) GetLastMessage

func (c *Cache) GetLastMessage(taskID int) (*implantpb.Spite, bool)

func (*Cache) GetMessage

func (c *Cache) GetMessage(taskID, index int) (*implantpb.Spite, bool)

GetMessage retrieves a cache item by TaskId and Index

func (*Cache) GetMessages

func (c *Cache) GetMessages(taskID int) ([]*implantpb.Spite, bool)

func (*Cache) Load

func (c *Cache) Load() error

Load deserializes cache items from a file using protobuf

func (*Cache) Save

func (c *Cache) Save() error

Save serializes the cache items to a file using protobuf

type Client

type Client struct {
	*clientpb.Client
}

Client - Single client connection

func NewClient

func NewClient(operatorName string) *Client

NewClient - Create a new client object

func (*Client) ToProtobuf

func (c *Client) ToProtobuf() *clientpb.Client

type Connection

type Connection struct {
	RawID       uint32
	SessionID   string
	LastMessage time.Time
	PipelineID  string
	C           chan *clientpb.SpiteRequest // spite
	Sender      chan *implantpb.Spites
	Parser      *parser.MessageParser
	// contains filtered or unexported fields
}

func GetConnection added in v0.1.2

func GetConnection(conn *cryptostream.Conn, pipelineID string, secureConfig *implanttypes.SecureConfig) (*Connection, error)

GetConnection 统一的连接获取/创建函数 (适用于 TCP 和 HTTP pipeline) 从 cryptostream.Conn 中提取 SID 并获取/创建连接

func NewConnection

func NewConnection(p *parser.MessageParser, sid uint32, pipelineID string, keyPair *clientpb.KeyPair) *Connection

func (*Connection) Handler added in v0.0.3

func (c *Connection) Handler(ctx context.Context, conn *cryptostream.Conn) error

func (*Connection) HandlerSimplex added in v0.1.0

func (c *Connection) HandlerSimplex(ctx context.Context, conn *cryptostream.Conn) error

func (*Connection) IsAlive added in v0.3.0

func (c *Connection) IsAlive() bool

func (*Connection) LastError added in v0.3.0

func (c *Connection) LastError() error

func (*Connection) Send

func (c *Connection) Send(ctx context.Context, conn *cryptostream.Conn) error

type Event

type Event struct {
	Session  *clientpb.Session
	Job      *clientpb.Job
	Client   *clientpb.Client
	Task     *clientpb.Task
	Spite    *implantpb.Spite
	Listener *clientpb.Listener

	Important bool
	EventType string
	Op        string
	Message   string
	Err       string
	Callee    string
	IsNotify  bool
}

func (*Event) String added in v0.1.0

func (event *Event) String() string

func (*Event) ToProtobuf added in v0.1.0

func (event *Event) ToProtobuf() *clientpb.Event

toprotobuf

type Forward

type Forward struct {
	Pipeline
	ListenerId string
	Stream     forwardStream

	ListenerRpc forwardRPCClient
	// contains filtered or unexported fields
}

Forward is a struct that handles messages from listener and server

func NewForward

func NewForward(rpc forwardClient, pipeline Pipeline) (*Forward, error)

func (*Forward) Add

func (f *Forward) Add(msg *Message)

func (*Forward) Context added in v0.1.0

func (f *Forward) Context(sid string) context.Context

func (*Forward) Count

func (f *Forward) Count() int

func (*Forward) Handler

func (f *Forward) Handler() error

Handler is a loop that handles messages from implant

type GoErrorHandler added in v0.3.0

type GoErrorHandler func(error)

func CombineErrorHandlers added in v0.3.0

func CombineErrorHandlers(handlers ...GoErrorHandler) GoErrorHandler

func LogGuardedError added in v0.3.0

func LogGuardedError(label string) GoErrorHandler

type Job

type Job struct {
	ID       uint32
	Name     string
	Pipeline *clientpb.Pipeline
}

func (*Job) ToProtobuf

func (j *Job) ToProtobuf() *clientpb.Job

type Listener

type Listener struct {
	Name string
	IP   string

	Ctrl    chan *clientpb.JobCtrl
	CtrlJob *sync.Map
	// contains filtered or unexported fields
}

func NewListener added in v0.3.0

func NewListener(name, ip string) *Listener

func (*Listener) Active

func (l *Listener) Active() bool

Active returns whether the listener is active.

func (*Listener) AddPipeline added in v0.0.3

func (l *Listener) AddPipeline(pipeline *clientpb.Pipeline)

func (*Listener) AllPipelines added in v0.0.3

func (l *Listener) AllPipelines() []*clientpb.Pipeline

func (*Listener) GetPipeline added in v0.0.3

func (l *Listener) GetPipeline(name string) *clientpb.Pipeline

func (*Listener) PushCtrl added in v0.1.0

func (l *Listener) PushCtrl(ctrl *clientpb.JobCtrl) uint32

PushCtrl sends a control message to the listener. Returns the assigned ctrl ID. If the listener's Ctrl channel is full (listener not consuming), it logs a warning and returns 0 instead of blocking forever.

func (*Listener) RemovePipeline added in v0.0.3

func (l *Listener) RemovePipeline(pipeline *clientpb.Pipeline)

func (*Listener) ToProtobuf

func (l *Listener) ToProtobuf() *clientpb.Listener

func (*Listener) WaitCtrl added in v0.1.0

func (l *Listener) WaitCtrl(i uint32) *clientpb.JobStatus

WaitCtrl waits for a control response from the listener. Returns nil if the response does not arrive within DefaultCtrlTimeout or if ctrlID is 0 (PushCtrl failed).

type Message

type Message struct {
	Spites     *implantpb.Spites
	RawID      uint32
	SessionID  string
	RemoteAddr string
}

type PanicError added in v0.3.0

type PanicError struct {
	Label     string
	Cause     error
	Recovered any
	Stack     []byte
}

func (*PanicError) Error added in v0.3.0

func (e *PanicError) Error() string

func (*PanicError) Unwrap added in v0.3.0

func (e *PanicError) Unwrap() error

type Pipeline

type Pipeline interface {
	ID() string
	Start() error
	Close() error
	ToProtobuf() *clientpb.Pipeline
}

type PipelineConfig added in v0.0.3

type PipelineConfig struct {
	ListenerID   string
	Parser       string
	TLSConfig    *implanttypes.TlsConfig
	Encryption   implanttypes.EncryptionsConfig
	SecureConfig *implanttypes.SecureConfig
	PacketLength int
}

func FromPipeline added in v0.1.1

func FromPipeline(pipeline *clientpb.Pipeline) *PipelineConfig

func (*PipelineConfig) WrapBindConn added in v0.3.0

func (p *PipelineConfig) WrapBindConn(conn io.ReadWriteCloser) (*cryptostream.Conn, error)

WrapBindConn wraps a connection for bind mode without pre-reading Bind mode expects server to send data first, then receive response

func (*PipelineConfig) WrapConn added in v0.0.3

func (p *PipelineConfig) WrapConn(conn io.ReadWriteCloser) (*cryptostream.Conn, error)

type Pipelines

type Pipelines struct {
	// contains filtered or unexported fields
}

func NewPipelines added in v0.3.0

func NewPipelines() Pipelines

func (*Pipelines) Add

func (ps *Pipelines) Add(p Pipeline)

func (*Pipelines) Delete added in v0.3.0

func (ps *Pipelines) Delete(id string)

func (*Pipelines) Get

func (ps *Pipelines) Get(id string) Pipeline

func (*Pipelines) ToProtobuf

func (ps *Pipelines) ToProtobuf() *clientpb.Pipelines

type RingCache added in v0.1.0

type RingCache struct {
	// contains filtered or unexported fields
}

func NewMessageCache added in v0.1.0

func NewMessageCache(capacity int) *RingCache

func (*RingCache) Add added in v0.1.0

func (mc *RingCache) Add(message interface{})

func (*RingCache) GetAll added in v0.1.0

func (mc *RingCache) GetAll() []interface{}

func (*RingCache) GetLast added in v0.1.0

func (mc *RingCache) GetLast() interface{}

func (*RingCache) GetN added in v0.1.0

func (mc *RingCache) GetN(n int) []interface{}

GetN 返回最后 N 条消息

type SecureManager added in v0.1.2

type SecureManager struct {
	// contains filtered or unexported fields
}

SecureManager handles key exchange request and response processing.

func NewSecureSpiteManager added in v0.1.2

func NewSecureSpiteManager(sess *Session) *SecureManager

NewSecureSpiteManager creates a new secure manager.

func (*SecureManager) IncrementCounter added in v0.1.2

func (s *SecureManager) IncrementCounter()

IncrementCounter increments the message counter.

func (*SecureManager) ResetCounters added in v0.1.2

func (s *SecureManager) ResetCounters()

ResetCounters resets the counter (called after key exchange completes).

func (*SecureManager) ShouldRotateKey added in v0.1.2

func (s *SecureManager) ShouldRotateKey() bool

ShouldRotateKey checks whether key rotation is needed.

func (*SecureManager) UpdateKeyPair added in v0.1.2

func (s *SecureManager) UpdateKeyPair(keyPair *clientpb.KeyPair)

UpdateKeyPair updates the active key pair reference.

type Session

type Session struct {
	Type        string
	PipelineID  string
	ListenerID  string
	ID          string
	RawID       uint32
	Name        string
	Group       string
	Note        string
	Target      string
	Initialized bool
	CreatedAt   time.Time
	Tasks       *Tasks // task manager
	*client.SessionContext

	// Age 密码学安全管理器(运行时,负责密钥交换和轮换)
	SecureManager *SecureManager

	*Cache
	Taskseq uint32

	Ctx    context.Context
	Cancel context.CancelFunc
	// contains filtered or unexported fields
}

Session - Represents a connection to an implant

func RecoverSession added in v0.0.3

func RecoverSession(sess *models.Session) (*Session, error)

func RegisterSession added in v0.0.3

func RegisterSession(req *clientpb.RegisterSession) (*Session, error)

func (*Session) Abstract added in v0.1.0

func (s *Session) Abstract() string

func (*Session) DeleteAny added in v0.3.0

func (s *Session) DeleteAny(id string)

func (*Session) DeleteResp

func (s *Session) DeleteResp(taskId uint32)

func (*Session) FillSysInfo added in v0.1.2

func (s *Session) FillSysInfo()

func (*Session) GetAny added in v0.3.0

func (s *Session) GetAny(id string) (interface{}, bool)

func (*Session) GetPacketLength added in v0.3.0

func (s *Session) GetPacketLength() int

GetPacketLength returns the per-pipeline packet length or falls back to global config.

func (*Session) GetPipelineEncryptionKey added in v0.3.0

func (s *Session) GetPipelineEncryptionKey() string

GetPipelineEncryptionKey returns the transport encryption key from the session's pipeline config. Returns "" if not found.

func (*Session) GetResp

func (s *Session) GetResp(taskId uint32) (chan *implantpb.Spite, bool)

func (*Session) HasUnfinishedTasks added in v0.3.0

func (s *Session) HasUnfinishedTasks() bool

func (*Session) IsKeepaliveEnabled added in v0.3.0

func (s *Session) IsKeepaliveEnabled() bool

IsKeepaliveEnabled returns the current keepalive status.

func (*Session) IsMarkedDead added in v0.3.0

func (s *Session) IsMarkedDead() bool

func (*Session) LastCheckinUnix added in v0.3.0

func (s *Session) LastCheckinUnix() int64

func (*Session) MarkAlive added in v0.3.0

func (s *Session) MarkAlive() bool

func (*Session) MarkDead added in v0.3.0

func (s *Session) MarkDead() bool

func (*Session) NewTask

func (s *Session) NewTask(name string, total int) *Task

func (*Session) Publish added in v0.0.3

func (s *Session) Publish(Op string, msg string, notify bool, important bool)

func (*Session) PushCtrl added in v0.1.2

func (s *Session) PushCtrl()

func (*Session) PushUpdate added in v0.1.1

func (s *Session) PushUpdate(msg string)

func (*Session) Recover added in v0.0.3

func (s *Session) Recover() error

func (*Session) RecoverTaskIDByLog added in v0.0.3

func (s *Session) RecoverTaskIDByLog() (int, error)

func (*Session) RemoveResp added in v0.3.0

func (s *Session) RemoveResp(taskId uint32)

RemoveResp removes the response channel from the map without closing it. This prevents new producers from finding the channel, while existing producer goroutines that already hold a reference can still safely send into the buffer without panicking on a closed channel.

func (*Session) Request

func (s *Session) Request(msg *clientpb.SpiteRequest, stream grpc.ServerStream) error

Request

func (*Session) RequestAndWait

func (s *Session) RequestAndWait(msg *clientpb.SpiteRequest, stream grpc.ServerStream, timeout time.Duration) (*implantpb.Spite, error)

func (*Session) RequestWithAsync

func (s *Session) RequestWithAsync(msg *clientpb.SpiteRequest, stream grpc.ServerStream, timeout time.Duration) (chan *implantpb.Spite, error)

func (*Session) RequestWithStream

func (s *Session) RequestWithStream(msg *clientpb.SpiteRequest, stream grpc.ServerStream, timeout time.Duration) (*SpiteStreamWriter, chan *implantpb.Spite, error)

RequestWithStream - 'async' means that the response is not returned immediately, but is returned through the channel 'ch

func (*Session) ResetKeepalive added in v0.3.0

func (s *Session) ResetKeepalive()

ResetKeepalive resets keepalive state (used on disconnect).

func (*Session) RpcLogger added in v0.0.3

func (s *Session) RpcLogger() *logs.Logger

func (*Session) Save added in v0.1.2

func (s *Session) Save() error

func (*Session) SaveAndNotify added in v0.3.0

func (s *Session) SaveAndNotify(msg string) error

SaveAndNotify 持久化 session 到数据库并广播更新事件到所有客户端。 这是 RPC handler 修改 session 持久化字段后的标准路径。

func (*Session) SetAny added in v0.3.0

func (s *Session) SetAny(id string, value interface{})

func (*Session) SetKeepalive added in v0.3.0

func (s *Session) SetKeepalive(enabled bool) bool

SetKeepalive updates the keepalive state. Returns the previous state.

func (*Session) SetLastCheckin added in v0.3.0

func (s *Session) SetLastCheckin(ts int64)

func (*Session) StoreResp

func (s *Session) StoreResp(taskId uint32, ch chan *implantpb.Spite)

func (*Session) TaskLog added in v0.0.3

func (s *Session) TaskLog(task *Task, spite *implantpb.Spite) error

func (*Session) ToModel added in v0.0.3

func (s *Session) ToModel() *models.Session

func (*Session) ToProtobuf

func (s *Session) ToProtobuf() *clientpb.Session

func (*Session) ToProtobufLite added in v0.0.3

func (s *Session) ToProtobufLite() *clientpb.Session

func (*Session) Update

func (s *Session) Update(req *clientpb.RegisterSession)

func (*Session) UpdateKeyPair added in v0.1.2

func (s *Session) UpdateKeyPair(keyPair *clientpb.KeyPair)

UpdateKeyPair 更新KeyPair并同步到SecureManager

func (*Session) UpdateKeyPairFieldsAndPushCtrl added in v0.3.0

func (s *Session) UpdateKeyPairFieldsAndPushCtrl(publicKey string, privateKey string)

func (*Session) UpdatePrivateKey added in v0.1.2

func (s *Session) UpdatePrivateKey(key string)

func (*Session) UpdatePublicKey added in v0.1.2

func (s *Session) UpdatePublicKey(key string)

func (*Session) UpdateSysInfo

func (s *Session) UpdateSysInfo(info *implantpb.SysInfo)

type SpiteStreamWriter added in v0.3.0

type SpiteStreamWriter struct {
	// contains filtered or unexported fields
}

func (*SpiteStreamWriter) Close added in v0.3.0

func (w *SpiteStreamWriter) Close()

func (*SpiteStreamWriter) Err added in v0.3.0

func (w *SpiteStreamWriter) Err() error

func (*SpiteStreamWriter) Send added in v0.3.0

func (w *SpiteStreamWriter) Send(spite *implantpb.Spite) error

type Task

type Task struct {
	Id        uint32
	Type      string
	SessionId string
	Callee    string
	Cur       int
	Total     int
	Callback  func()
	Ctx       context.Context
	Cancel    context.CancelFunc
	Session   *Session
	DoneCh    chan bool

	Deadline   time.Time
	CallBy     string
	CreatedAt  time.Time
	FinishedAt time.Time
	// contains filtered or unexported fields
}

func FromTaskProtobuf added in v0.0.3

func FromTaskProtobuf(task *clientpb.Task) *Task

func (*Task) CancelTask added in v0.3.0

func (t *Task) CancelTask(spite *implantpb.Spite, msg string)

func (*Task) Close

func (t *Task) Close()

func (*Task) Done

func (t *Task) Done(spite *implantpb.Spite, msg string)

func (*Task) Finish

func (t *Task) Finish(spite *implantpb.Spite, msg string)

func (*Task) Finished added in v0.0.3

func (t *Task) Finished() bool

func (*Task) FinishedAtTime added in v0.3.0

func (t *Task) FinishedAtTime() time.Time

func (*Task) IsClosed added in v0.3.0

func (t *Task) IsClosed() bool

func (*Task) Name

func (t *Task) Name() string

func (*Task) Panic

func (t *Task) Panic(event Event)

func (*Task) Progress added in v0.3.0

func (t *Task) Progress() (cur, total int)

func (*Task) Publish added in v0.0.3

func (t *Task) Publish(op string, spite *implantpb.Spite, msg string)

func (*Task) String

func (t *Task) String() string

func (*Task) TaskID added in v0.0.3

func (t *Task) TaskID() string

func (*Task) Timeout added in v0.0.3

func (t *Task) Timeout() bool

func (*Task) ToProtobuf

func (t *Task) ToProtobuf() *clientpb.Task

func (*Task) UpdateTotal added in v0.3.0

func (t *Task) UpdateTotal(total int)

UpdateTotal sets the task's total count and persists only the total field to DB. This avoids racing with Done() which updates cur independently.

type Tasks

type Tasks struct {
	// contains filtered or unexported fields
}

func NewTasks added in v0.0.3

func NewTasks() *Tasks

func (*Tasks) Add

func (t *Tasks) Add(task *Task)

func (*Tasks) All

func (t *Tasks) All() []*Task

All - Return a list of all tasks

func (*Tasks) Get

func (t *Tasks) Get(taskID uint32) *Task

get

func (*Tasks) GetNotFinish added in v0.0.3

func (t *Tasks) GetNotFinish() []*clientpb.Task

func (*Tasks) GetOrRecover added in v0.3.0

func (t *Tasks) GetOrRecover(sess *Session, taskID uint32) *Task

GetOrRecover 先从内存查找,找不到则回退到 DB 恢复

func (*Tasks) Remove

func (t *Tasks) Remove(taskId uint32)

func (*Tasks) ToProtobuf

func (t *Tasks) ToProtobuf() *clientpb.Tasks

type Ticker

type Ticker struct {
	// contains filtered or unexported fields
}

func NewTicker

func NewTicker() *Ticker

func (*Ticker) AddCronFunc added in v0.3.0

func (t *Ticker) AddCronFunc(spec string, cmd func()) (cron.EntryID, error)

AddCronFunc adds a cron-expression scheduled function (e.g. "0 0 * * *" for daily midnight).

func (*Ticker) Remove

func (t *Ticker) Remove(id cron.EntryID)

func (*Ticker) RemoveAll

func (t *Ticker) RemoveAll()

func (*Ticker) Start

func (t *Ticker) Start(interval int, cmd func()) (cron.EntryID, error)

Jump to

Keyboard shortcuts

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