feat: build wahrwelt A/D toolkit

This commit is contained in:
TakuyaYagam1 committed 2026-10-14 11:30:41 +03:00
1 parent 303438d206
commit 653924d8c6
564 files changed
+36310 -49998

No files matched your search

+256
View File
@@ -0,0 +1,256 @@
package client
import (
"context"
"errors"
"fmt"
"io"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"github.com/c4t-but-s4d/neo/v2/pkg/filestream"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
)
func New(cc grpc.ClientConnInterface, id string) *Client {
return &Client{
exploits: epb.NewServiceClient(cc),
fs: fspb.NewServiceClient(cc),
logs: logspb.NewServiceClient(cc),
ID: id,
}
}
type Client struct {
exploits epb.ServiceClient
fs fspb.ServiceClient
logs logspb.ServiceClient
ID string
Weight int
}
func (nc *Client) GetServerState(ctx context.Context) (*epb.ServerState, error) {
resp, err := nc.exploits.Ping(
ctx,
&epb.PingRequest{
ClientId: nc.ID,
Payload: &epb.PingRequest_ServerInfoRequest{
ServerInfoRequest: &epb.PingRequest_ServerInfo{},
},
},
)
if err != nil {
return nil, fmt.Errorf("запрос проверки связи: %w", err)
}
return resp.State, nil
}
func (nc *Client) Heartbeat(ctx context.Context) (*epb.ServerState, error) {
resp, err := nc.exploits.Ping(
ctx,
&epb.PingRequest{
ClientId: nc.ID,
Payload: &epb.PingRequest_HeartbeatRequest{
HeartbeatRequest: &epb.PingRequest_Heartbeat{
Weight: int32(nc.Weight),
},
},
},
)
if err != nil {
return nil, fmt.Errorf("запрос проверки связи: %w", err)
}
return resp.State, nil
}
func (nc *Client) Leave(ctx context.Context) error {
if _, err := nc.exploits.Ping(
ctx,
&epb.PingRequest{
ClientId: nc.ID,
Payload: &epb.PingRequest_LeaveRequest{
LeaveRequest: &epb.PingRequest_Leave{},
},
},
); err != nil {
return fmt.Errorf("запрос проверки связи: %w", err)
}
return nil
}
func (nc *Client) Exploit(ctx context.Context, id string) (*epb.ExploitResponse, error) {
req := &epb.ExploitRequest{
ExploitId: id,
}
resp, err := nc.exploits.Exploit(ctx, req)
if err != nil {
return nil, fmt.Errorf("запрос эксплойта: %w", err)
}
return resp, nil
}
func (nc *Client) UpdateExploit(ctx context.Context, state *epb.ExploitState) (*epb.ExploitState, error) {
req := &epb.UpdateExploitRequest{State: state}
resp, err := nc.exploits.UpdateExploit(ctx, req)
if err != nil {
return nil, fmt.Errorf("запрос обновления эксплойта: %w", err)
}
return resp.State, nil
}
func (nc *Client) DownloadFile(ctx context.Context, info *fspb.FileInfo, out io.Writer) error {
resp, err := nc.fs.DownloadFile(ctx, info)
if err != nil {
return fmt.Errorf("запрос скачивания файла: %w", err)
}
if err := filestream.SaveLimit(resp, out, filestream.MaxFileSize); err != nil {
return fmt.Errorf("сохранение скачанного файла: %w", err)
}
if err := resp.CloseSend(); err != nil {
return fmt.Errorf("закрытие потока: %w", err)
}
return nil
}
func (nc *Client) UploadFile(ctx context.Context, r io.Reader) (*fspb.FileInfo, error) {
client, err := nc.fs.UploadFile(ctx)
if err != nil {
return nil, fmt.Errorf("запрос загрузки файла: %w", err)
}
if err := filestream.Load(r, client); err != nil {
return nil, fmt.Errorf("передача файла в поток: %w", err)
}
fileInfo, err := client.CloseAndRecv()
if err != nil {
return nil, fmt.Errorf("закрытие потока и чтение ответа о загрузке: %w", err)
}
return fileInfo, nil
}
func (nc *Client) BroadcastCommand(ctx context.Context, command string) error {
req := &epb.BroadcastRequest{Command: command}
if _, err := nc.exploits.BroadcastCommand(ctx, req); err != nil {
return fmt.Errorf("запрос рассылки команды: %w", err)
}
return nil
}
func (nc *Client) SingleRun(ctx context.Context, exploitID string) error {
req := &epb.SingleRunRequest{ExploitId: exploitID}
if _, err := nc.exploits.SingleRun(ctx, req); err != nil {
return fmt.Errorf("запрос одиночного запуска: %w", err)
}
return nil
}
func (nc *Client) SetExploitDisabled(ctx context.Context, id string, disabled bool) error {
resp, err := nc.Exploit(ctx, id)
if err != nil {
return fmt.Errorf("получение текущей конфигурации эксплойта: %w", err)
}
req := &epb.UpdateExploitRequest{State: resp.State}
req.State.Config.Disabled = disabled
if _, err := nc.exploits.UpdateExploit(ctx, req); err != nil {
return fmt.Errorf("запрос изменения состояния эксплойта: %w", err)
}
return nil
}
func (nc *Client) ListenBroadcasts(ctx context.Context) (<-chan *epb.BroadcastSubscribeResponse, error) {
stream, err := nc.exploits.BroadcastSubscribe(ctx, &epb.BroadcastSubscribeRequest{})
if err != nil {
return nil, fmt.Errorf("создание потока запросов рассылки: %w", err)
}
results := make(chan *epb.BroadcastSubscribeResponse)
go func() {
defer close(results)
for {
cmd, err := stream.Recv()
if !checkStreamError("broadcast", err, stream.Context().Err()) {
return
}
select {
case results <- cmd:
case <-ctx.Done():
logrus.Debugf("Контекст рассылки отменен")
return
}
}
}()
return results, nil
}
func (nc *Client) ListenSingleRuns(ctx context.Context) (<-chan *epb.SingleRunSubscribeResponse, error) {
stream, err := nc.exploits.SingleRunSubscribe(ctx, &epb.SingleRunSubscribeRequest{})
if err != nil {
return nil, fmt.Errorf("создание потока одиночных запусков: %w", err)
}
results := make(chan *epb.SingleRunSubscribeResponse)
go func() {
defer close(results)
for {
er, err := stream.Recv()
if !checkStreamError("single runs", err, stream.Context().Err()) {
return
}
select {
case results <- er:
case <-ctx.Done():
logrus.Warningf("Контекст одиночного запуска отменен")
return
}
}
}()
return results, nil
}
func (nc *Client) AddLogLines(ctx context.Context, lines ...*logspb.LogLine) error {
req := logspb.AddLogLinesRequest{Lines: lines}
if _, err := nc.logs.AddLogLines(ctx, &req); err != nil {
return fmt.Errorf("отправка пакета строк журнала (%d): %w", len(lines), err)
}
return nil
}
func (nc *Client) SearchLogLines(ctx context.Context, exploit string, version int64) (<-chan []*logspb.LogLine, error) {
req := logspb.SearchLogLinesRequest{
Exploit: exploit,
Version: version,
}
stream, err := nc.logs.SearchLogLines(ctx, &req)
if err != nil {
return nil, fmt.Errorf("запрос к серверу: %w", err)
}
results := make(chan []*logspb.LogLine)
go func() {
defer close(results)
for {
resp, err := stream.Recv()
if err != nil {
if !errors.Is(err, io.EOF) {
logrus.Errorf("Ошибка чтения строк журнала: %v", err)
}
return
}
select {
case results <- resp.Lines:
case <-ctx.Done():
logrus.Debugf("Контекст чтения журнала отменен")
return
}
}
}()
return results, nil
}
+23
View File
@@ -0,0 +1,23 @@
package client
import (
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func MustUnmarshalConfig() *Config {
cfg := new(Config)
if err := viper.Unmarshal(&cfg); err != nil {
logrus.Fatalf("Не удалось разобрать структуру конфигурации: %v", err)
}
return cfg
}
type Config struct {
Host string `mapstructure:"host"`
MetricsHost string `mapstructure:"metrics_host"`
ExploitDir string `mapstructure:"exploit_dir"`
GrpcAuthKey string `mapstructure:"grpc_auth_key"`
UseTLS bool `mapstructure:"use_tls"`
AllowBroadcastCommands bool `mapstructure:"allow_broadcast_commands"`
}
@@ -0,0 +1,11 @@
//go:build linux
package client
import "golang.org/x/sys/unix"
// HardenProcess не дает заданиям с тем же UID читать память и окружение
// worker через /proc, сохраняя возможность запускать дочерние процессы.
func HardenProcess() error {
return unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0)
}
@@ -0,0 +1,17 @@
//go:build linux
package client
import (
"testing"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)
func TestHardenProcessDisablesDumpability(t *testing.T) {
require.NoError(t, HardenProcess())
dumpable, err := unix.PrctlRetInt(unix.PR_GET_DUMPABLE, 0, 0, 0, 0)
require.NoError(t, err)
require.Zero(t, dumpable)
}
@@ -0,0 +1,5 @@
//go:build !linux
package client
func HardenProcess() error { return nil }
+25
View File
@@ -0,0 +1,25 @@
package client
import (
"context"
"errors"
"io"
"github.com/sirupsen/logrus"
)
func checkStreamError(tp string, err error, streamErr error) bool {
if errors.Is(err, io.EOF) {
logrus.Errorf("Поток %s закрыт", tp)
return false
}
if errors.Is(streamErr, context.Canceled) {
logrus.Debugf("Контекст потока %s отменен", tp)
return false
}
if err != nil {
logrus.Errorf("Ошибка чтения из потока %s: %v", tp, err)
return false
}
return true
}
+47
View File
@@ -0,0 +1,47 @@
package config
import (
"fmt"
"regexp"
"time"
"google.golang.org/protobuf/types/known/durationpb"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
type ExploitsConfig struct {
PingEvery time.Duration
SubmitEvery time.Duration
FarmURL string
FarmPassword string
FlagRegexp *regexp.Regexp
Environ []string
}
func ToProto(c *ExploitsConfig) *epb.Config {
return &epb.Config{
FarmUrl: c.FarmURL,
FarmPassword: c.FarmPassword,
FlagRegexp: c.FlagRegexp.String(),
PingEvery: durationpb.New(c.PingEvery),
SubmitEvery: durationpb.New(c.SubmitEvery),
Environ: c.Environ,
}
}
func FromProto(config *epb.Config) (*ExploitsConfig, error) {
var (
cfg ExploitsConfig
err error
)
if cfg.FlagRegexp, err = regexp.Compile(config.FlagRegexp); err != nil {
return nil, fmt.Errorf("компиляция регулярного выражения: %w", err)
}
cfg.FarmURL = config.FarmUrl
cfg.FarmPassword = config.FarmPassword
cfg.PingEvery = config.PingEvery.AsDuration()
cfg.SubmitEvery = config.SubmitEvery.AsDuration()
cfg.Environ = config.Environ
return &cfg, nil
}
+73
View File
@@ -0,0 +1,73 @@
package exploit
import (
"sync"
"time"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func NewCache() *Cache {
return &Cache{
states: make(map[string]*State),
m: sync.RWMutex{},
}
}
// Cache хранит исполняемые файлы в памяти клиента.
// Кэш не сохраняется на диск, поэтому после перезапуска файлы загружаются заново.
type Cache struct {
states map[string]*State
m sync.RWMutex
}
func (c *Cache) Exploits() (res []*State) {
c.m.RLock()
defer c.m.RUnlock()
for _, v := range c.states {
res = append(res, v)
}
return
}
func (c *Cache) Exploit(id string) (res *State, ok bool) {
c.m.RLock()
defer c.m.RUnlock()
res, ok = c.states[id]
return
}
func (c *Cache) Diff(exs []*epb.ExploitState) []*epb.ExploitState {
c.m.RLock()
defer c.m.RUnlock()
var diff []*epb.ExploitState
for _, ex := range exs {
state, exists := c.states[ex.ExploitId]
if !exists {
diff = append(diff, ex)
continue
}
if state.Version != ex.Version {
diff = append(diff, ex)
}
}
return diff
}
func (c *Cache) Update(exs []*State) {
c.m.Lock()
defer c.m.Unlock()
for _, ex := range exs {
c.states[ex.ID] = ex
}
}
func (c *Cache) UpdateLastRun(exploitID string, t time.Time) {
c.m.Lock()
defer c.m.Unlock()
if ex, ok := c.states[exploitID]; ok {
ex.LastRun = t
}
}
@@ -0,0 +1,202 @@
package exploit
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"google.golang.org/protobuf/testing/protocmp"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func TestCache_Diff(t *testing.T) {
for _, tc := range []struct {
have []*State
new []*epb.ExploitState
diff []*epb.ExploitState
}{
{
have: nil,
new: nil,
diff: nil,
},
{
have: []*State{
{ID: "1", Version: 1},
},
new: []*epb.ExploitState{{
ExploitId: "1",
Version: 1,
File: nil,
}},
diff: nil,
},
{
have: []*State{
{ID: "1", Version: 1},
},
new: []*epb.ExploitState{{
ExploitId: "2",
Version: 1,
File: nil,
}},
diff: []*epb.ExploitState{{
ExploitId: "2",
Version: 1,
File: nil,
}},
},
{
have: []*State{
{ID: "1", Version: 1},
},
new: []*epb.ExploitState{{
ExploitId: "1",
Version: 2,
File: nil,
}},
diff: []*epb.ExploitState{{
ExploitId: "1",
Version: 2,
File: nil,
}},
},
{
have: []*State{
{ID: "1", Version: 1},
{ID: "2", Version: 1},
},
new: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
File: nil,
},
{
ExploitId: "2",
Version: 1,
File: nil,
},
{
ExploitId: "3",
Version: 1,
File: nil,
},
},
diff: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
File: nil,
},
{
ExploitId: "3",
Version: 1,
File: nil,
},
},
},
{
have: []*State{
{ID: "1", Version: 1},
{ID: "2", Version: 1},
},
new: nil,
diff: nil,
},
{
have: []*State{
{ID: "1", Version: 1, Endless: false},
},
new: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: true},
},
},
diff: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: true},
},
},
},
{
have: []*State{
{ID: "1", Version: 1, Endless: true},
},
new: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: false},
},
},
diff: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: false},
},
},
},
{
have: nil,
new: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: true},
},
},
diff: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: true},
},
},
},
{
have: nil,
new: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: false},
},
},
diff: []*epb.ExploitState{
{
ExploitId: "1",
Version: 2,
Config: &epb.ExploitConfiguration{Endless: false},
},
},
},
} {
c := NewCache()
c.Update(tc.have)
got := c.Diff(tc.new)
if diff := cmp.Diff(tc.diff, got, protocmp.Transform(), cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Diff() mismatch (-want +got):\n%s", diff)
}
}
}
func TestCache_Exploits(t *testing.T) {
c := NewCache()
data := []*State{{
ID: "1",
Version: 1,
Dir: "/test",
Path: "kek",
}}
c.Update(data)
if diff := cmp.Diff(data, c.Exploits(), cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Diff() mismatch (-want +got):\n%s", diff)
}
}
@@ -0,0 +1,51 @@
package exploit
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type Metrics struct {
FlagsSubmitted *prometheus.CounterVec
Teams prometheus.Gauge
Queue *prometheus.GaugeVec
}
func NewMetrics(namespace string) *Metrics {
const subsystem = "exploit_runner"
return &Metrics{
FlagsSubmitted: promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "flags_submitted_total",
Help: "Number of exploits finished",
},
[]string{
"target_id",
"target_ip",
"exploit_id",
"exploit_version",
"exploit_type",
},
),
Teams: promauto.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "teams",
Help: "Number of teams scheduled for the current runner",
}),
Queue: promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "queue",
Help: "Number of exploits in the queue",
},
[]string{"type"},
),
}
}
+70
View File
@@ -0,0 +1,70 @@
package exploit
import (
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/samber/lo"
"github.com/c4t-but-s4d/neo/v2/internal/models"
)
type FarmRequest struct {
Flag string `json:"flag"`
Exploit string `json:"sploit"`
Team string `json:"team"`
}
type FullResult struct {
Exploit *models.Exploit
Target *models.Target
Flag string
}
func NewFullResult(exploit *models.Exploit, target *models.Target, flag string) *FullResult {
return &FullResult{
Exploit: exploit,
Target: target,
Flag: flag,
}
}
func (r *FullResult) FarmRequest() *FarmRequest {
return &FarmRequest{
Flag: r.Flag,
Exploit: "[neo] " + r.Exploit.ID,
Team: r.Target.ID,
}
}
func (r *FullResult) MetricLabels() prometheus.Labels {
return lo.Assign(r.Exploit.MetricLabels(), r.Target.MetricLabels())
}
type State struct {
ID string
Version int64
Dir string
Path string
Disabled bool
Endless bool
RunEvery time.Duration
LastRun time.Time
ScaledTimeout time.Duration
Timeout time.Duration
}
func (s *State) ExploitType() models.ExploitType {
if s.Endless {
return models.ExploitTypeEndless
}
return models.ExploitTypeRecurrent
}
func (s *State) ToModel() *models.Exploit {
return &models.Exploit{
ID: s.ID,
Version: s.Version,
Type: s.ExploitType(),
}
}
+459
View File
@@ -0,0 +1,459 @@
package exploit
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
"github.com/prometheus/common/expfmt"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/internal/client"
"github.com/c4t-but-s4d/neo/v2/internal/config"
"github.com/c4t-but-s4d/neo/v2/internal/models"
"github.com/c4t-but-s4d/neo/v2/internal/queue"
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
var (
ErrFinishedUnexpectedly = errors.New("служба завершилась неожиданно")
)
func NewRunner(
clientID string,
maxJobs, maxEndlessJobs int,
timeoutScaleTarget float64,
clientConfig *client.Config,
c *client.Client,
logSender joblogger.Sender,
) *Runner {
var metricsPusher *push.Pusher
if strings.TrimSpace(clientConfig.MetricsHost) != "" {
metricsPusher = push.New(clientConfig.MetricsHost, "neo_runner").
Grouping("client_id", clientID).
Format(expfmt.FmtOpenMetrics_1_0_0).
Gatherer(prometheus.DefaultGatherer)
}
return &Runner{
storage: NewStorage(NewCache(), clientConfig.ExploitDir, c),
cfg: &config.ExploitsConfig{},
client: c,
maxJobs: maxJobs,
maxEndlessJobs: maxEndlessJobs,
timeoutScaleTarget: timeoutScaleTarget,
allowBroadcastCommands: clientConfig.AllowBroadcastCommands,
singleRuns: make(chan *epb.SingleRunSubscribeResponse),
restarts: make(chan struct{}, 1),
logSender: logSender,
metricsPusher: metricsPusher,
metrics: NewMetrics("neo"),
logger: logrus.WithField("component", "exploit-runner"),
}
}
type Runner struct {
storage *Storage
teams map[string]string
cfg *config.ExploitsConfig
client *client.Client
logSender joblogger.Sender
metricsPusher *push.Pusher
metrics *Metrics
maxJobs int
maxEndlessJobs int
timeoutScaleTarget float64
allowBroadcastCommands bool
simpleLoop *submitLoop
endlessLoop *submitLoop
singleRuns chan *epb.SingleRunSubscribeResponse
restarts chan struct{}
logger *logrus.Entry
}
func (r *Runner) Run(ctx context.Context) error {
r.printGreeting()
state, err := r.pingHeartbeat(ctx)
if err != nil {
return fmt.Errorf("отправка сигнала проверки связи: %w", err)
}
if err := r.onServerStateUpdate(ctx, state); err != nil {
return fmt.Errorf("обновление состояния сервера: %w", err)
}
// Очистить накопленные сигналы обновления.
select {
case <-r.restarts:
default:
}
wg := sync.WaitGroup{}
srvCtx, srvCancel := context.WithCancel(ctx)
defer srvCancel()
// Ошибка не завершает работу: циклы повторяют попытки бесконечно.
wg.Add(3)
go func() {
defer wg.Done()
if err := retryLoop(srvCtx, "broadcast", -1, 3*time.Second, r.listenBroadcast); err != nil && !errors.Is(err, context.Canceled) {
r.logger.WithError(err).Error("Ошибка цикла приема рассылок")
}
}()
go func() {
defer wg.Done()
if err := retryLoop(srvCtx, "single runs", -1, 3*time.Second, r.listenSingleRuns); err != nil && !errors.Is(err, context.Canceled) {
r.logger.WithError(err).Error("Ошибка цикла приема одиночных запусков")
}
}()
go func() {
defer wg.Done()
r.startPushingMetrics(srvCtx)
}()
defer func() {
r.logger.Info("Остановка вспомогательных служб")
srvCancel()
r.logger.Info("Ожидание остановки вспомогательных служб")
wg.Wait()
}()
r.eventLoop(ctx)
r.logger.Info("Worker завершает работу, отправка сигнала выхода")
leaveCtx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := r.client.Leave(leaveCtx); err != nil {
return fmt.Errorf("не удалось отправить сигнал выхода: %w", err)
}
return nil
}
func (r *Runner) eventLoop(ctx context.Context) {
defer r.logger.Info("Цикл событий остановлен")
var loopsWg sync.WaitGroup
loopsCancel := r.runWorkers(ctx, &loopsWg)
stopLoops := func() {
r.logger.Info("Остановка циклов отправки")
loopsCancel()
r.logger.Info("Ожидание остановки циклов отправки")
loopsWg.Wait()
}
defer stopLoops()
r.scheduleEndlessExploits()
runTicker := time.NewTicker(time.Second)
defer runTicker.Stop()
savedPingEvery := r.cfg.PingEvery
pingTicker := time.NewTicker(savedPingEvery)
for {
select {
case <-pingTicker.C:
r.logger.Debug("Отправка сигнала проверки связи")
state, err := r.pingHeartbeat(ctx)
if err != nil {
r.logger.WithError(err).Error("Ошибка периодической проверки связи")
return
}
if err := r.onServerStateUpdate(ctx, state); err != nil {
r.logger.WithError(err).Error("Ошибка обработки обновления состояния сервера")
} else if r.cfg.PingEvery != savedPingEvery {
savedPingEvery = r.cfg.PingEvery
pingTicker.Reset(savedPingEvery)
}
case <-r.restarts:
r.logger.Info("Получен запрос на перезапуск циклов")
stopLoops()
loopsCancel = r.runWorkers(ctx, &loopsWg)
r.scheduleEndlessExploits()
case <-runTicker.C:
r.logger.Debug("Планирование периодических эксплойтов")
r.scheduleRecurrentExploits()
case req := <-r.singleRuns:
r.logger.Infof("Обработка одиночного запуска эксплойта %s", req.GetExploitId())
// Обновить конфигурацию, чтобы запрошенный эксплойт был загружен.
if _, err := r.pingHeartbeat(ctx); err != nil {
r.logger.WithError(err).Error("Ошибка обновления конфигурации перед одиночным запуском")
}
if err := r.submitExploit(r.simpleLoop, req.ExploitId); err != nil {
r.logger.WithError(err).Errorf("Ошибка добавления эксплойта %s в очередь одиночного запуска", req.ExploitId)
}
case <-ctx.Done():
return
}
}
}
func (r *Runner) pingHeartbeat(ctx context.Context) (*epb.ServerState, error) {
state, err := r.client.Heartbeat(ctx)
if err != nil {
return nil, fmt.Errorf("отправка сигнала проверки связи: %w", err)
}
return state, nil
}
func (r *Runner) runWorkers(ctx context.Context, wg *sync.WaitGroup) context.CancelFunc {
r.simpleLoop = newSubmitLoop(r.maxJobs, r.cfg, r.metrics, queue.NewSimpleQueueFactory())
r.endlessLoop = newSubmitLoop(r.maxEndlessJobs, r.cfg, r.metrics, queue.NewEndlessQueueFactory())
loopsCtx, loopsCancel := context.WithCancel(ctx)
r.logger.Info("Запуск циклов отправки")
wg.Add(2)
go func() {
defer wg.Done()
r.simpleLoop.Start(loopsCtx)
r.logger.Info("Обычный цикл отправки завершен")
}()
go func() {
defer wg.Done()
r.endlessLoop.Start(loopsCtx)
r.logger.Info("Бесконечный цикл отправки завершен")
}()
return loopsCancel
}
func (r *Runner) scheduleRecurrentExploits() {
exs := r.storage.Exploits()
now := time.Now()
for _, ex := range exs {
if ex.Disabled || ex.Endless {
continue
}
if ex.LastRun.Add(ex.RunEvery).After(now) {
continue
}
if err := r.submitExploit(r.simpleLoop, ex.ID); err != nil {
r.logger.WithError(err).Errorf("Ошибка добавления периодического эксплойта %s в очередь", ex.ID)
}
}
}
func (r *Runner) scheduleEndlessExploits() {
exs := r.storage.Exploits()
for _, ex := range exs {
if ex.Disabled || !ex.Endless {
continue
}
if err := r.submitExploit(r.endlessLoop, ex.ID); err != nil {
r.logger.WithError(err).Errorf("Ошибка добавления бесконечного эксплойта %s в очередь, перезапуск циклов", ex.ID)
// Перезапустить циклы, чтобы бесконечный эксплойт не завис в очереди.
// Перезапуск также повторяет запуск и помогает обнаруживать ошибки по журналам.
r.restartLoops()
}
}
}
func (r *Runner) submitExploit(l *submitLoop, id string) error {
ex, ok := r.storage.Exploit(id)
if !ok {
return fmt.Errorf("эксплойт %v не найден", id)
}
jobs := CreateExploitJobs(ex, r.teams, r.cfg.Environ, r.logSender)
for _, t := range jobs {
r.logger.Infof("Добавление задания: %v", t)
if err := l.Add(t); err != nil {
return fmt.Errorf("добавление задания в очередь: %w", err)
}
}
r.storage.UpdateLastRun(ex.ID, time.Now())
return nil
}
func (r *Runner) restartLoops() {
select {
case r.restarts <- struct{}{}:
default:
}
}
func (r *Runner) listenBroadcast(ctx context.Context) error {
resp, err := r.client.ListenBroadcasts(ctx)
if err != nil {
return fmt.Errorf("запрос потока рассылок: %w", err)
}
for {
select {
case cmd, ok := <-resp:
if !ok {
r.logger.Error("Канал рассылок закрыт")
return ErrFinishedUnexpectedly
}
r.logger.Info("Получена команда рассылки")
if err := r.handleBroadcastCommand(ctx, cmd); err != nil {
r.logger.WithError(err).Error("Ошибка обработки команды рассылки")
}
case <-ctx.Done():
return ctx.Err()
}
}
}
func (r *Runner) listenSingleRuns(ctx context.Context) error {
resp, err := r.client.ListenSingleRuns(ctx)
if err != nil {
return fmt.Errorf("запрос потока одиночных запусков: %w", err)
}
for {
select {
case req, ok := <-resp:
if !ok {
r.logger.Error("Канал одиночных запусков закрыт")
return ErrFinishedUnexpectedly
}
r.logger.Infof("Получен запрос на одиночный запуск эксплойта %s", req.GetExploitId())
r.singleRuns <- req
case <-ctx.Done():
return ctx.Err()
}
}
}
func (r *Runner) startPushingMetrics(ctx context.Context) {
if r.metricsPusher == nil {
return
}
t := time.NewTicker(time.Second * 1)
defer t.Stop()
for {
select {
case <-t.C:
if err := r.metricsPusher.PushContext(ctx); err != nil {
r.logger.WithError(err).Error("Ошибка отправки метрик")
}
case <-ctx.Done():
return
}
}
}
func (r *Runner) handleBroadcastCommand(ctx context.Context, cmd *epb.BroadcastSubscribeResponse) error {
if !r.allowBroadcastCommands {
return fmt.Errorf("выполнение широковещательных shell-команд отключено")
}
if cmd == nil || strings.TrimSpace(cmd.Command) == "" {
return fmt.Errorf("пустая shell-команда")
}
c := exec.CommandContext(ctx, "/bin/bash", "-c", cmd.Command)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if err := c.Run(); err != nil {
return fmt.Errorf("выполнение команды: %w", err)
}
return nil
}
func (r *Runner) onServerStateUpdate(ctx context.Context, state *epb.ServerState) error {
cfg, err := config.FromProto(state.Config)
if err != nil {
return fmt.Errorf("разбор конфигурации: %w", err)
}
r.cfg = cfg
cid := r.client.ID
teamsChanged := false
if ipbuck, ok := state.ClientTeamMap[cid]; !ok {
r.logger.Warning("Клиент отсутствует в списке команд")
} else {
if diff := cmp.Diff(r.teams, ipbuck.Teams, cmpopts.EquateEmpty()); diff != "" {
r.teams = ipbuck.Teams
teamsChanged = true
r.logger.Info("Состав команд изменился, запланирован перезапуск циклов")
r.restartLoops()
}
r.metrics.Teams.Set(float64(len(r.teams)))
}
exploitsChanged := r.storage.UpdateExploits(ctx, state.Exploits)
if r.timeoutScaleTarget > 0 && (exploitsChanged || teamsChanged) {
r.storage.ScaleTimeouts(r.maxJobs, len(r.teams), r.timeoutScaleTarget)
}
if exploitsChanged {
r.logger.Info("Список эксплойтов изменился, запланирован перезапуск циклов")
r.restartLoops()
}
return nil
}
func (r *Runner) printGreeting() {
fmt.Println(` _
___| |__ ___ _ __ ___ ___ _ __ _ _ _ __ _ __ ___ _ __
/ __| '_ \/ __| | '_ \ / _ \/ _ \ | '__| | | | '_ \| '_ \ / _ \ '__|
| (__| |_) \__ \ | | | | __/ (_) | | | | |_| | | | | | | | __/ |
\___|_.__/|___/ |_| |_|\___|\___/ |_| \__,_|_| |_|_| |_|\___|_|
`)
}
func CreateExploitJobs(
ex *State,
teams map[string]string,
environ []string,
sender joblogger.Sender,
) (jobs []*queue.Job) {
for id, ip := range teams {
jobs = append(jobs, queue.NewJob(
models.NewExploit(ex.ID, ex.Version, ex.ExploitType()),
models.NewTarget(id, ip),
ex.Path,
ex.Dir,
environ,
ex.ScaledTimeout,
joblogger.New(ex.ID, ex.Version, ip, sender),
))
}
return
}
func retryLoop(ctx context.Context, name string, retries int, interval time.Duration, f func(ctx context.Context) error) error {
t := time.NewTimer(interval)
defer t.Stop()
var err error
for attempts := 0; retries == -1 || attempts < retries; attempts++ {
logrus.Infof("Запуск цикла %s", name)
err = f(ctx)
if err == nil || errors.Is(err, context.Canceled) {
logrus.Infof("Цикл %s завершает работу", name)
return err
}
if retries == -1 || attempts+1 < retries {
logrus.Errorf("Цикл %s завершился с ошибкой %v, перезапуск", name, err)
t.Reset(interval)
select {
case <-t.C:
case <-ctx.Done():
return ctx.Err()
}
}
}
return err
}
@@ -0,0 +1,134 @@
package exploit
import (
"context"
"io"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/c4t-but-s4d/neo/v2/internal/client"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func TestRunner_onServerStateUpdateRescalesOnTeamChange(t *testing.T) {
st, cleanup := mockStorage()
defer func() {
require.NoError(t, cleanup())
}()
st.cache.Update([]*State{{
ID: "check",
Version: 1,
RunEvery: time.Minute,
Timeout: time.Minute,
ScaledTimeout: time.Minute,
}})
r := &Runner{
storage: st,
client: &client.Client{ID: "worker"},
maxJobs: 1,
timeoutScaleTarget: 1,
teams: map[string]string{},
restarts: make(chan struct{}, 1),
metrics: &Metrics{Teams: prometheus.NewGauge(prometheus.GaugeOpts{Name: "neo_test_teams", Help: "team count"})},
logger: logrus.NewEntry(logrus.New()),
}
state := &epb.ServerState{
Config: &epb.Config{
FlagRegexp: ".*",
PingEvery: durationpb.New(time.Minute),
SubmitEvery: durationpb.New(time.Second),
},
ClientTeamMap: map[string]*epb.TeamBucket{
"worker": {Teams: map[string]string{}},
},
Exploits: []*epb.ExploitState{{ExploitId: "check", Version: 1}},
}
// Эксплойт уже загружен, поэтому повторное состояние не меняет его версию.
require.NoError(t, r.onServerStateUpdate(context.Background(), state))
got, ok := st.Exploit("check")
require.True(t, ok)
require.Equal(t, time.Minute, got.ScaledTimeout)
state.ClientTeamMap["worker"] = &epb.TeamBucket{Teams: map[string]string{
"team-a": "192.0.2.1",
"team-b": "192.0.2.2",
}}
require.NoError(t, r.onServerStateUpdate(context.Background(), state))
got, ok = st.Exploit("check")
require.True(t, ok)
require.Equal(t, time.Minute, got.Timeout)
require.Equal(t, 30*time.Second, got.ScaledTimeout)
}
func Test_retryLoop(t *testing.T) {
tests := []struct {
name string
retries int
doRetries int
returnErr error
lastErr error
wantErr error
}{
{
"simple",
1,
1,
ErrFinishedUnexpectedly,
nil,
nil,
},
{
"endless retries",
-1,
100,
ErrFinishedUnexpectedly,
nil,
nil,
},
{
"return last error",
1,
5,
io.EOF,
nil,
io.EOF,
},
{
"context cancelled",
5,
3,
ErrFinishedUnexpectedly,
context.Canceled,
context.Canceled,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cnt := 0
f := func(context.Context) error {
cnt++
if cnt < tt.doRetries {
return tt.returnErr
}
return tt.lastErr
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
require.ErrorIs(t, retryLoop(ctx, "test", tt.retries, time.Millisecond, f), tt.wantErr)
if tt.retries != -1 && tt.doRetries > tt.retries {
require.Equal(t, tt.retries, cnt)
} else {
require.Equal(t, tt.doRetries, cnt)
}
})
}
}
+305
View File
@@ -0,0 +1,305 @@
package exploit
import (
"context"
"fmt"
"io"
"math"
"os"
"path/filepath"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/internal/client"
"github.com/c4t-but-s4d/neo/v2/pkg/archive"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func NewStorage(cache *Cache, exploitDir string, client *client.Client) *Storage {
return &Storage{
cache: cache,
exploitDir: exploitDir,
client: client,
}
}
type Storage struct {
cache *Cache
exploitDir string
client *client.Client
}
func (s *Storage) Exploits() (res []*State) {
return s.cache.Exploits()
}
func (s *Storage) Exploit(id string) (res *State, ok bool) {
return s.cache.Exploit(id)
}
func (s *Storage) UpdateLastRun(exploitID string, t time.Time) {
s.cache.UpdateLastRun(exploitID, t)
}
func (s *Storage) UpdateExploits(ctx context.Context, exs []*epb.ExploitState) bool {
diff := s.cache.Diff(exs)
if len(diff) == 0 {
return false
}
logrus.Infof("Обнаружены обновленные эксплойты: %d", len(diff))
states := make([]*State, 0, len(diff))
for _, ex := range diff {
st, err := s.updateExploit(ctx, ex.ExploitId)
if err != nil {
logrus.Errorf("Не удалось обновить или скачать эксплойт %s:%d: %v", ex.ExploitId, ex.Version, err)
continue
}
states = append(states, st)
}
s.cache.Update(states)
return true
}
func (s *Storage) ScaleTimeouts(workers, teams int, target float64) {
exploits := s.cache.Exploits()
// Alpha показывает долю времени worker, занятую заданиями.
// Например, при тайм-ауте 10 секунд и запуске каждые 20 секунд одно
// задание занимает половину времени на каждую команду. При четырех командах
// это соответствует двум полностью занятым worker.
// В этом примере Alpha равен 10/20 = 0.5; при двух worker итог будет
// 0.5 * 4 / 2 = 1, то есть все worker будут заняты.
// Если значение ниже цели, тайм-ауты можно увеличить; если выше -
// пропорционально уменьшить относительно исходных значений.
// Target задает желаемое Alpha. Значение 1 обычно неэффективно, так как
// задания часто завершаются до тайм-аута.
// Бесконечные задания не масштабируются.
// Тайм-ауты округляются вниз до целой секунды.
fallback := func(reason string) {
logrus.Warnf("Масштабирование тайм-аутов пропущено (%s), используются исходные значения", reason)
for _, ex := range exploits {
if ex.Endless {
continue
}
newTimeout := positiveTimeout(ex.Timeout)
logrus.Infof("Тайм-аут эксплойта %s: %s -> %s", ex.ID, ex.ScaledTimeout, newTimeout)
ex.ScaledTimeout = newTimeout
}
}
if workers <= 0 || teams <= 0 || !isPositiveFinite(target) {
fallback("некорректные число worker, число команд или цель")
return
}
alpha := 0.0
hasTimedExploits := false
for _, ex := range exploits {
if ex.Endless {
continue
}
hasTimedExploits = true
if ex.Timeout <= 0 || ex.RunEvery <= 0 {
fallback("исходный тайм-аут или интервал неположителен")
return
}
load := float64(ex.Timeout) / float64(ex.RunEvery)
if !isPositiveFinite(load) {
fallback("нагрузка эксплойта не является конечной")
return
}
alpha += load
if !isPositiveFinite(alpha) {
fallback("суммарная нагрузка не является конечной")
return
}
}
if !hasTimedExploits {
return
}
alpha *= float64(teams) / float64(workers)
if !isPositiveFinite(alpha) {
fallback("суммарная нагрузка равна нулю или не является конечной")
return
}
logrus.Infof("Масштабирование тайм-аутов: alpha = %.2f, цель = %.2f", alpha, target)
scaleFactor := target / alpha
if !isPositiveFinite(scaleFactor) {
fallback("коэффициент масштабирования не является конечным")
return
}
const maxDurationSeconds = float64((1<<63 - 1) / int64(time.Second))
for _, ex := range exploits {
if ex.Endless {
continue
}
scaledSeconds := float64(ex.Timeout) / float64(time.Second) * scaleFactor
newTimeout := positiveTimeout(ex.Timeout)
if math.IsNaN(scaledSeconds) || math.IsInf(scaledSeconds, 0) || scaledSeconds > maxDurationSeconds {
logrus.Warnf("Результат масштабирования эксплойта %s вне допустимого диапазона, используется исходный тайм-аут", ex.ID)
} else {
// Тайм-ауты округляются вниз до целой секунды, но не могут быть меньше секунды.
seconds := math.Floor(scaledSeconds)
if seconds < 1 {
seconds = 1
}
newTimeout = time.Duration(seconds) * time.Second
}
logrus.Infof("Тайм-аут эксплойта %s: %s -> %s", ex.ID, ex.ScaledTimeout, newTimeout)
ex.ScaledTimeout = newTimeout
}
}
func isPositiveFinite(value float64) bool {
return value > 0 && !math.IsNaN(value) && !math.IsInf(value, 0)
}
func positiveTimeout(timeout time.Duration) time.Duration {
if timeout > 0 {
return timeout
}
return time.Second
}
func (s *Storage) updateExploit(ctx context.Context, exploitID string) (*State, error) {
if err := validateExploitID(exploitID); err != nil {
return nil, err
}
// Получить актуальное состояние эксплойта.
resp, err := s.client.Exploit(ctx, exploitID)
if err != nil {
return nil, fmt.Errorf("запрос состояния эксплойта: %w", err)
}
state := resp.State
if state == nil {
return nil, fmt.Errorf("состояние эксплойта отсутствует")
}
if state.File == nil {
return nil, fmt.Errorf("файл эксплойта отсутствует")
}
if state.Config == nil {
return nil, fmt.Errorf("конфигурация эксплойта отсутствует")
}
if state.ExploitId != exploitID || state.Version <= 0 {
return nil, fmt.Errorf("идентификатор или версия эксплойта недопустимы")
}
if err := os.MkdirAll(s.exploitDir, 0700); err != nil {
return nil, fmt.Errorf("создание каталога эксплойтов: %w", err)
}
// Создать временный файл для загрузки.
f, err := os.CreateTemp(s.exploitDir, "DOWNLOAD")
if err != nil {
return nil, fmt.Errorf("создание временного файла: %w", err)
}
defer func() {
_ = f.Close()
_ = os.Remove(f.Name())
}()
// Загрузить исполняемый файл во временный файл.
if err := s.client.DownloadFile(ctx, state.File, f); err != nil {
return nil, fmt.Errorf("загрузка файла: %w", err)
}
// Перейти в начало файла, чтобы использовать его как io.Reader.
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, fmt.Errorf("переход к началу загруженного файла: %w", err)
}
oPath := filepath.Join(s.exploitDir, fmt.Sprintf("%s_%d", state.ExploitId, state.Version))
if _, err := os.Lstat(oPath); err == nil {
return nil, fmt.Errorf("каталог этой версии эксплойта уже существует")
} else if !os.IsNotExist(err) {
return nil, fmt.Errorf("проверка каталога версии эксплойта: %w", err)
}
keepFiles := false
defer func() {
if !keepFiles {
_ = os.RemoveAll(oPath)
}
}()
if state.Config.IsArchive && (strings.ContainsAny(state.Config.Entrypoint, "\\\x00") || !filepath.IsLocal(state.Config.Entrypoint)) {
return nil, fmt.Errorf("путь к точке входа архива недопустим")
}
var entryPath string
if entryPath, err = saveExploit(f, oPath, state.Config); err != nil {
return nil, fmt.Errorf("сохранение эксплойта: %w", err)
}
logrus.Infof("Каталог эксплойта: %s, точка входа: %s", oPath, entryPath)
if entryPath, err = prepareEntry(entryPath); err != nil {
return nil, fmt.Errorf("подготовка точки входа: %w", err)
}
res := &State{
ID: state.ExploitId,
Version: state.Version,
Dir: "",
Path: entryPath,
Disabled: state.Config.Disabled,
Endless: state.Config.Endless,
RunEvery: state.Config.RunEvery.AsDuration(),
ScaledTimeout: state.Config.Timeout.AsDuration(),
Timeout: state.Config.Timeout.AsDuration(),
}
if state.Config.IsArchive {
res.Dir = oPath
}
keepFiles = true
return res, nil
}
func saveExploit(f *os.File, outPath string, cfg *epb.ExploitConfiguration) (string, error) {
if cfg.IsArchive {
if err := archive.Untar(outPath, f); err != nil {
return "", fmt.Errorf("распаковка архива: %w", err)
}
return filepath.Join(outPath, cfg.Entrypoint), nil
}
if err := f.Close(); err != nil {
return "", fmt.Errorf("закрытие файла: %w", err)
}
if err := os.Link(f.Name(), outPath); err != nil {
return "", fmt.Errorf("перемещение файла %s в %s: %w", f.Name(), outPath, err)
}
return outPath, nil
}
func prepareEntry(path string) (string, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("получение абсолютного пути: %w", err)
}
info, err := os.Lstat(absPath)
if err != nil {
return "", fmt.Errorf("проверка точки входа: %w", err)
}
if !info.Mode().IsRegular() {
return "", fmt.Errorf("точка входа не является обычным файлом")
}
if err := os.Chmod(absPath, 0755); err != nil {
return "", fmt.Errorf("установка разрешений файла: %w", err)
}
return absPath, nil
}
func validateExploitID(id string) error {
if id == "" || len(id) > 128 || id == "." || id == ".." ||
strings.ContainsAny(id, "/\\\x00") || !filepath.IsLocal(id) {
return fmt.Errorf("недопустимый идентификатор эксплойта")
}
return nil
}
@@ -0,0 +1,343 @@
package exploit
import (
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/require"
"github.com/c4t-but-s4d/neo/v2/pkg/archive"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func mockStorage() (*Storage, func() error) {
name, err := os.MkdirTemp("", "testStorage")
if err != nil {
panic(err)
}
return NewStorage(NewCache(), name, nil), func() error {
if err != nil {
return fmt.Errorf("remove exploit storage: %w", os.RemoveAll(name))
}
return nil
}
}
func TestStorage_Exploit(t *testing.T) {
st, cleanup := mockStorage()
defer func() {
require.NoError(t, cleanup())
}()
st.cache.Update([]*State{
{ID: "1", Version: 1},
})
res, ok := st.Exploit("1")
require.True(t, ok)
require.EqualValues(t, 1, res.Version)
}
func Test_saveExploit(t *testing.T) {
f, err := os.CreateTemp("", "")
require.NoError(t, err)
defer func(f *os.File) {
require.Error(t, f.Close())
require.NoError(t, os.Remove(f.Name()))
}(f)
testData := []byte("test")
_, err = f.Write(testData)
require.NoError(t, err)
outfile := filepath.Join(t.TempDir(), "result")
cfg := &epb.ExploitConfiguration{
Entrypoint: "kek",
IsArchive: false,
}
entry, err := saveExploit(f, outfile, cfg)
require.NoError(t, err)
require.Equal(t, outfile, entry)
data, err := os.ReadFile(outfile)
require.NoError(t, err)
if diff := cmp.Diff(data, testData, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Runner.saveExploit() returned data mismatch (-want +got):\n%s", diff)
}
}
func Test_saveExploitArchive(t *testing.T) {
dir, err := os.MkdirTemp("", "TEMP_TAR")
require.NoError(t, err)
remove := func(name string) {
require.NoError(t, os.RemoveAll(name))
}
defer remove(dir)
writeFile := func(name string, content []byte) error {
f, err := os.Create(name)
if err != nil {
return fmt.Errorf("os.Create() got unexpected error = %w", err)
}
if _, err := f.Write(content); err != nil {
return fmt.Errorf("f.Write() got unexpected error = %w", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("f.Close() got unexpected error = %w", err)
}
return nil
}
exploitFile := "exp.py"
exploitData := []byte("print(1);")
require.NoError(t, writeFile(path.Join(dir, exploitFile), exploitData))
secondFile := "t.txt"
secondData := []byte("123")
require.NoError(t, writeFile(path.Join(dir, secondFile), secondData))
tarFile, err := os.CreateTemp("", "ARCHIVE")
require.NoError(t, err)
defer remove(tarFile.Name())
require.NoError(t, archive.Tar(dir, tarFile))
_, err = tarFile.Seek(0, io.SeekStart)
require.NoError(t, err)
outDir, err := os.MkdirTemp("", "TEMP_UNTAR")
require.NoError(t, err)
defer remove(outDir)
cfg := &epb.ExploitConfiguration{
Entrypoint: exploitFile,
IsArchive: true,
}
entry, err := saveExploit(tarFile, outDir, cfg)
require.NoError(t, err)
entryDir, entryPath := path.Split(entry)
entryDir = path.Clean(entryDir)
require.Equal(t, outDir, entryDir)
require.Equal(t, cfg.Entrypoint, entryPath)
entryContent, err := os.ReadFile(entry)
require.NoError(t, err)
if diff := cmp.Diff(exploitData, entryContent, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Runner.saveExploit() returned entrypoint data mismatch (-want +got):\n%s", diff)
}
additionalContent, err := os.ReadFile(path.Join(entryDir, secondFile))
require.NoError(t, err)
if diff := cmp.Diff(secondData, additionalContent, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Runner.saveExploit() returned additional data mismatch (-want +got):\n%s", diff)
}
}
func Test_prepareEntry(t *testing.T) {
f, err := os.CreateTemp("", "exec")
require.NoError(t, err)
defer func() {
require.NoError(t, os.Remove(f.Name()))
}()
require.NoError(t, f.Close())
entry, err := prepareEntry(f.Name())
require.NoError(t, err)
require.True(t, strings.Contains(entry, f.Name()))
fi, err := os.Stat(entry)
require.NoError(t, err)
// Файл должен быть исполняемым.
require.NotZero(t, fi.Mode()&0111)
}
func TestStorage_Scale(t *testing.T) {
st, cleanup := mockStorage()
defer func() {
require.NoError(t, cleanup())
}()
// При teams = 2 * workers таймаут задания должен уменьшиться вдвое.
st.cache.Update([]*State{
{
ID: "1",
Version: 1,
RunEvery: time.Minute,
ScaledTimeout: time.Minute,
Timeout: time.Minute,
},
})
st.ScaleTimeouts(10, 20, 1)
res, ok := st.Exploit("1")
require.True(t, ok)
require.EqualValues(t, 1, res.Version)
require.EqualValues(t, time.Minute, res.RunEvery)
require.EqualValues(t, 30*time.Second, res.ScaledTimeout)
// При workers = 2 * teams таймаут должен удвоиться.
st.ScaleTimeouts(20, 10, 1)
res, ok = st.Exploit("1")
require.True(t, ok)
require.EqualValues(t, time.Minute, res.RunEvery)
require.EqualValues(t, 2*time.Minute, res.ScaledTimeout)
// Новое задание сохраняет масштабирование исходных таймаутов.
st.cache.Update([]*State{
{
ID: "2",
Version: 1,
RunEvery: time.Minute,
ScaledTimeout: time.Minute,
Timeout: time.Minute,
},
})
st.ScaleTimeouts(20, 10, 1)
res, ok = st.Exploit("1")
require.True(t, ok)
require.EqualValues(t, time.Minute, res.RunEvery)
require.EqualValues(t, time.Minute, res.ScaledTimeout)
res, ok = st.Exploit("2")
require.True(t, ok)
require.EqualValues(t, time.Minute, res.RunEvery)
require.EqualValues(t, time.Minute, res.ScaledTimeout)
// При target = 2 таймауты заданий должны увеличиться.
st.ScaleTimeouts(20, 10, 2)
res, ok = st.Exploit("1")
require.True(t, ok)
require.EqualValues(t, 2*time.Minute, res.ScaledTimeout)
res, ok = st.Exploit("2")
require.True(t, ok)
require.EqualValues(t, 2*time.Minute, res.ScaledTimeout)
}
func TestStorage_ScaleTimeoutsInvalidInputs(t *testing.T) {
tests := []struct {
name string
workers int
teams int
target float64
timeout time.Duration
runEvery time.Duration
want time.Duration
}{
{
name: "zero workers preserves configured timeout",
workers: 0,
teams: 2,
target: 1,
timeout: time.Minute,
runEvery: time.Minute,
want: time.Minute,
},
{
name: "zero teams preserves configured timeout",
workers: 2,
teams: 0,
target: 1,
timeout: time.Minute,
runEvery: time.Minute,
want: time.Minute,
},
{
name: "zero alpha uses minimum timeout",
workers: 2,
teams: 2,
target: 1,
timeout: 0,
runEvery: time.Minute,
want: time.Second,
},
{
name: "zero interval preserves configured timeout",
workers: 2,
teams: 2,
target: 1,
timeout: time.Minute,
runEvery: 0,
want: time.Minute,
},
{
name: "non-finite target preserves configured timeout",
workers: 2,
teams: 2,
target: math.NaN(),
timeout: time.Minute,
runEvery: time.Minute,
want: time.Minute,
},
{
name: "infinite target preserves configured timeout",
workers: 2,
teams: 2,
target: math.Inf(1),
timeout: time.Minute,
runEvery: time.Minute,
want: time.Minute,
},
{
name: "subsecond result is clamped to one second",
workers: 1,
teams: 1,
target: math.SmallestNonzeroFloat64,
timeout: 30 * time.Second,
runEvery: 30 * time.Second,
want: time.Second,
},
{
name: "overflow preserves configured timeout",
workers: 1,
teams: 1,
target: math.MaxFloat64,
timeout: 30 * time.Second,
runEvery: 30 * time.Second,
want: 30 * time.Second,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
st, cleanup := mockStorage()
defer func() {
require.NoError(t, cleanup())
}()
st.cache.Update([]*State{{
ID: "check",
Version: 1,
RunEvery: tt.runEvery,
Timeout: tt.timeout,
ScaledTimeout: time.Minute,
}})
st.ScaleTimeouts(tt.workers, tt.teams, tt.target)
got, ok := st.Exploit("check")
require.True(t, ok)
require.Equal(t, tt.want, got.ScaledTimeout)
require.Greater(t, got.ScaledTimeout, time.Duration(0))
})
}
}
@@ -0,0 +1,186 @@
package exploit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/internal/config"
"github.com/c4t-but-s4d/neo/v2/internal/queue"
)
const maxFarmResponseBytes = 1 << 20
var farmHTTPClient = &http.Client{Timeout: 3 * time.Second}
type submitLoop struct {
q queue.Queue
maxJobs int
cfg *config.ExploitsConfig
metrics *Metrics
factory queue.Factory
logger *logrus.Entry
}
func newSubmitLoop(
maxJobs int,
cfg *config.ExploitsConfig,
metrics *Metrics,
factory queue.Factory,
) *submitLoop {
return &submitLoop{
q: factory.Create(maxJobs),
maxJobs: maxJobs,
factory: factory,
metrics: metrics,
cfg: cfg,
logger: logrus.WithFields(logrus.Fields{
"component": "submit_loop",
"queue": factory.Type(),
}),
}
}
// Start выполняется синхронно и блокируется до отмены контекста.
func (l *submitLoop) Start(ctx context.Context) {
l.logger.Info("Запуск")
defer l.logger.Info("Остановлено")
var (
queueWG sync.WaitGroup
queueCtx context.Context
queueCancel context.CancelFunc
)
startQueue := func() {
l.logger.Info("Запуск очереди")
queueWG.Add(1)
queueCtx, queueCancel = context.WithCancel(ctx)
go func() {
defer queueWG.Done()
l.q.Start(queueCtx)
l.logger.Info("Очередь завершена")
}()
}
startQueue()
stopQueue := func() {
l.logger.Info("Остановка очереди")
queueCancel()
l.logger.Info("Ожидание остановки очереди")
queueWG.Wait()
}
defer stopQueue()
t := time.NewTicker(l.cfg.SubmitEvery)
defer t.Stop()
var results []*FullResult
flush := func() {
if len(results) == 0 {
return
}
l.logger.Infof("Отправка флагов: %d", len(results))
if err := l.submitResults(ctx, results); err != nil {
l.logger.Errorf("Не удалось отправить флаги Farm (%d): %v", len(results), err)
} else {
l.logger.Infof("Отправлено флагов в Farm: %d", len(results))
for _, result := range results {
l.metrics.FlagsSubmitted.With(result.MetricLabels()).Inc()
}
results = results[:0]
}
}
defer func() {
l.logger.Info("Последняя отправка накопленных флагов")
flush()
}()
queueCache := make(map[string]struct{})
for {
select {
case res, ok := <-l.q.Results():
if !ok {
l.logger.Warningf("Очередь завершилась неожиданно, перезапуск")
stopQueue()
l.q = l.factory.Create(l.maxJobs)
startQueue()
break
}
for _, match := range l.cfg.FlagRegexp.FindAll(res.Out, -1) {
flag := string(match)
if _, ok := queueCache[flag]; ok {
continue
}
results = append(results, NewFullResult(res.Exploit, res.Target, flag))
queueCache[flag] = struct{}{}
}
case <-t.C:
flush()
l.metrics.Queue.WithLabelValues(string(l.q.Type())).Set(float64(l.q.Size()))
case <-ctx.Done():
return
}
}
}
func (l *submitLoop) Add(t *queue.Job) error {
if err := l.q.Add(t); err != nil {
return fmt.Errorf("добавление задания в очередь: %w", err)
}
return nil
}
func (l *submitLoop) submitResults(ctx context.Context, results []*FullResult) error {
// Пока что используется только для стенда с возможностью внесения изменений.
url := l.cfg.FarmURL + "/api/post_flags"
toSend := make([]*FarmRequest, 0, len(results))
for _, fullRes := range results {
toSend = append(toSend, fullRes.FarmRequest())
}
data, err := json.Marshal(toSend)
if err != nil {
return fmt.Errorf("не удалось сериализовать результаты: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
if err != nil {
return fmt.Errorf("создание запроса: %w", err)
}
req.Header.Set("Authorization", l.cfg.FarmPassword)
req.Header.Add("X-Token", l.cfg.FarmPassword)
req.Header.Set("Content-Type", "application/json")
resp, err := farmHTTPClient.Do(req)
if err != nil {
return fmt.Errorf("выполнение запроса: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
l.logger.Errorf("Ошибка закрытия ответа Farm: %v", err)
}
}()
read, err := io.Copy(io.Discard, io.LimitReader(resp.Body, maxFarmResponseBytes+1))
if err != nil {
return fmt.Errorf("чтение ответа Farm: %w", err)
}
if read > maxFarmResponseBytes {
return fmt.Errorf("ответ Farm превышает %d байт", maxFarmResponseBytes)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Farm отклонил флаги, HTTP-код %d", resp.StatusCode)
}
return nil
}
@@ -0,0 +1,372 @@
package exploit
import (
"context"
"encoding/json"
"errors"
"net/http"
"regexp"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
"github.com/c4t-but-s4d/neo/v2/internal/config"
"github.com/c4t-but-s4d/neo/v2/internal/logger"
"github.com/c4t-but-s4d/neo/v2/internal/models"
"github.com/c4t-but-s4d/neo/v2/internal/queue"
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
"github.com/c4t-but-s4d/neo/v2/pkg/neosync"
"github.com/c4t-but-s4d/neo/v2/pkg/testutils"
)
var (
errQueueFull = errors.New("queue is full")
)
func TestMain(m *testing.M) {
logger.Init()
goleak.VerifyTestMain(m)
}
func Test_newSubmitLoop(t *testing.T) {
q := newMockQueue()
factory := &mockQueueFactory{
q: q,
}
cfg := config.ExploitsConfig{
FarmURL: "127.0.0.1",
FarmPassword: "1234",
}
want := submitLoop{
q: q,
maxJobs: 5,
cfg: &cfg,
factory: factory,
}
got := newSubmitLoop(5, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
assert.Equal(t, want.maxJobs, got.maxJobs)
assert.Equal(t, want.cfg, got.cfg)
assert.Equal(t, want.q, got.q)
}
func Test_submitLoop_Add(t *testing.T) {
q := newMockQueue()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go q.Start(ctx)
factory := &mockQueueFactory{q: q}
cfg := config.ExploitsConfig{
FarmURL: "127.0.0.1",
FarmPassword: "1234",
}
sl := newSubmitLoop(1, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
sender := joblogger.NewRemoteSender(nil)
jobLogger := joblogger.New("id", 1, "127.0.0.1", sender)
job := queue.NewJob(
&models.Exploit{ID: "id", Version: 1, Type: models.ExploitTypeRecurrent},
&models.Target{ID: "12", IP: "127.0.0.1"},
"echo",
"",
nil,
time.Second*5,
jobLogger,
)
require.NoError(t, sl.Add(job), "Add() returned an unexpected error")
select {
case got := <-q.in:
require.Equal(t, got.String(), job.String(), "invalid job added")
default:
t.Errorf("Add(): queue is empty after adding job")
}
}
func Test_submitLoop_AddFullQueue(t *testing.T) {
q := &mockQueue{}
factory := &mockQueueFactory{q: q}
cfg := config.ExploitsConfig{
FarmURL: "127.0.0.1",
FarmPassword: "1234",
}
sl := newSubmitLoop(1, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
sender := joblogger.NewRemoteSender(nil)
jobLogger := joblogger.New("id", 1, "127.0.0.1", sender)
job := queue.NewJob(
&models.Exploit{ID: "id", Version: 1, Type: models.ExploitTypeRecurrent},
&models.Target{ID: "12", IP: "127.0.0.1"},
"echo",
"",
nil,
time.Second*5,
jobLogger,
)
// in/out are nil, so queue is always full.
require.ErrorIs(t, sl.Add(job), errQueueFull, "Add() did not return an error")
}
func Test_submitLoop_Run(t *testing.T) {
q := newMockQueue()
factory := &mockQueueFactory{q: q}
wg := sync.WaitGroup{}
wantResults := []*FarmRequest{
{
Flag: "AAAAA=",
Exploit: "[neo] test",
Team: "Target 1",
},
{
Flag: "BBBBB=",
Exploit: "[neo] another test",
Team: "Target 2",
},
}
outputs := []*queue.Output{
{
Exploit: &models.Exploit{ID: "test"},
Target: &models.Target{ID: "Target 1"},
Out: []byte("some large AAAAA= output"),
},
{
Exploit: &models.Exploit{ID: "another test"},
Target: &models.Target{ID: "Target 2"},
Out: []byte("some large BBBBB= output"),
},
}
wg.Add(1) // checker must be called once
checker := func(t *testing.T, r *http.Request) {
t.Helper()
t.Log("checker called")
defer t.Log("checker finished")
defer wg.Done()
auth := r.Header.Get("Authorization")
token := r.Header.Get("X-Token")
contentType := r.Header.Get("Content-Type")
require.Equal(t, "1234", auth, "Invalid auth header %v", auth)
require.Equal(t, auth, token, "Invalid X-Token header %v", token)
require.Equal(t, "application/json", contentType, "Invalid content type %v", contentType)
var results []*FarmRequest
err := json.NewDecoder(r.Body).Decode(&results)
require.NoError(t, err, "Could not json-decode request body: %v", err)
t.Logf("checker received results: %v", results)
diff := cmp.Diff(results, wantResults)
require.Equal(t, "", diff, "Invalid results returned: %v", diff)
}
s := testutils.NewCheckedTestServer(t, checker)
defer s.Close()
cfg := config.ExploitsConfig{
FarmURL: s.URL,
FarmPassword: "1234",
FlagRegexp: regexp.MustCompile("[AB]{5}="),
SubmitEvery: time.Second,
}
sl := newSubmitLoop(1, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
slDone := make(chan struct{})
go func() {
defer close(slDone)
defer t.Logf("Submit loop stopped")
sl.Start(ctx)
}()
wg.Add(1) // outputs must be added
go func() {
defer wg.Done()
for _, out := range outputs {
t.Logf("sending output %v", out)
q.out <- out
}
}()
// Ждем результаты.
select {
case <-time.After(cfg.SubmitEvery * 2):
t.Errorf("Run(): test timed out")
case <-neosync.AwaitWG(&wg):
// Ждем завершения отправки.
time.Sleep(time.Millisecond * 200)
}
done := make(chan struct{})
go func() {
defer close(done)
cancel()
<-slDone // wait for submit loop to stop
}()
// Останавливаем очередь после обработки заданий.
select {
case <-time.After(time.Millisecond * 100):
t.Errorf("Run(): stop timed out")
case <-done:
}
}
func Test_submitLoop_submitResults(t *testing.T) {
tests := []struct {
name string
ctx context.Context
sendResults []*FullResult
wantResults []*FarmRequest
wantRequest bool
wantErr error
}{
{
"simple",
context.Background(),
[]*FullResult{
{
&models.Exploit{ID: "exploit"},
&models.Target{ID: "team"},
"AAAAA=",
},
},
[]*FarmRequest{
{
"AAAAA=",
"[neo] exploit",
"team",
},
},
true,
nil,
},
{
"cancelled context",
testutils.CanceledContext(),
[]*FullResult{
{
&models.Exploit{ID: "exploit"},
&models.Target{ID: "team"},
"AAAAA=",
},
},
nil,
false,
context.Canceled,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := testutils.NewCheckedTestServer(t, func(t *testing.T, r *http.Request) {
t.Helper()
t.Log("checker called")
defer t.Log("checker finished")
require.True(t, tt.wantRequest, "Unexpected request was made")
auth := r.Header.Get("Authorization")
token := r.Header.Get("X-Token")
contentType := r.Header.Get("Content-Type")
require.Equal(t, "1234", auth, "Invalid auth header %v", auth)
require.Equal(t, auth, token, "Invalid X-Token header %v", token)
require.Equal(t, "application/json", contentType, "Invalid content type %v", contentType)
var results []*FarmRequest
err := json.NewDecoder(r.Body).Decode(&results)
require.NoError(t, err, "Could not json-decode request body: %v", err)
t.Logf("checker received results: %v", results)
diff := cmp.Diff(results, tt.wantResults)
require.Equal(t, "", diff, "Invalid results returned: %v", diff)
})
defer s.Close()
loop := newSubmitLoop(
1,
&config.ExploitsConfig{
FarmURL: s.URL,
FarmPassword: "1234",
},
NewMetrics(testutils.MetricsNamespace()),
&mockQueueFactory{},
)
require.ErrorIs(t, loop.submitResults(tt.ctx, tt.sendResults), tt.wantErr)
})
}
}
type mockQueue struct {
out chan *queue.Output
in chan *queue.Job
}
func (m *mockQueue) String() string {
return "MockQueue"
}
func newMockQueue() *mockQueue {
return &mockQueue{
in: make(chan *queue.Job, 100),
out: make(chan *queue.Output, 100),
}
}
func (m *mockQueue) Type() queue.Type {
return "mock"
}
func (m *mockQueue) Size() int {
return len(m.in)
}
func (m *mockQueue) Start(ctx context.Context) {
<-ctx.Done()
}
func (m *mockQueue) Add(job *queue.Job) error {
select {
case m.in <- job:
return nil
default:
return errQueueFull
}
}
func (m *mockQueue) Stop() {
close(m.in)
close(m.out)
}
func (m *mockQueue) Results() <-chan *queue.Output {
return m.out
}
type mockQueueFactory struct {
q *mockQueue
}
func (m mockQueueFactory) Create(int) queue.Queue {
if m.q == nil {
m.q = newMockQueue()
}
return m.q
}
func (m mockQueueFactory) Type() queue.Type {
return "mock"
}
+214
View File
@@ -0,0 +1,214 @@
package logger
import (
"bytes"
"fmt"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/sirupsen/logrus"
)
const (
red = 31
yellow = 33
blue = 36
gray = 37
)
const defaultTimestampFormat = "2006-01-02T15:04:05.000Z07:00"
const (
CustomKeyFile = "@logger@file@"
CustomKeyFunc = "@logger@func@"
)
var baseTimestamp time.Time
func init() {
baseTimestamp = time.Now()
}
// CustomFormatter форматирует записи журнала в текст.
// Это форматтер logrus, настроенный для нужд Neo.
type CustomFormatter struct {
// Показывать полную временную метку при выводе в терминал, а не время
// с начала работы программы.
FullTimestamp bool
// Формат временной метки. Используется тот же формат, что и в time.Format
// и time.Parse стандартной библиотеки.
TimestampFormat string
// Не сокращать название уровня журнала до четырех символов.
DisableLevelTruncation bool
// Дополнять название уровня пробелами до общей длины.
// Этот параметр включает DisableLevelTruncation.
PadLevelText bool
// CallerPrettyfier позволяет настроить значения полей функции и файла,
// когда включен ReportCaller. Пустое возвращенное значение удаляет
// соответствующее поле.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
terminalInitOnce sync.Once
// Максимальная длина названия уровня, вычисляемая при инициализации.
levelTextMaxLength int
}
func (f *CustomFormatter) init() {
// Найти максимальную длину названия уровня.
for _, level := range logrus.AllLevels {
levelTextLength := utf8.RuneCount([]byte(level.String()))
if levelTextLength > f.levelTextMaxLength {
f.levelTextMaxLength = levelTextLength
}
}
}
// Format формирует одну запись журнала.
func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
data := make(logrus.Fields)
for k, v := range entry.Data {
data[k] = v
}
keys := make([]string, 0, len(data))
for k := range data {
if k == CustomKeyFile || k == CustomKeyFunc {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
f.terminalInitOnce.Do(func() { f.init() })
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
f.printColored(b, entry, keys, data, timestampFormat)
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *CustomFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys []string, data logrus.Fields, timestampFormat string) {
var levelColor int
switch entry.Level {
case logrus.DebugLevel, logrus.TraceLevel:
levelColor = gray
case logrus.WarnLevel:
levelColor = yellow
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
levelColor = red
case logrus.InfoLevel:
levelColor = blue
default:
levelColor = blue
}
levelText := strings.ToUpper(entry.Level.String())
if !f.DisableLevelTruncation && !f.PadLevelText {
levelText = levelText[0:4]
}
if f.PadLevelText {
// Сформировать шаблон выравнивания, например "%-6s" или "%-7s",
// на основе максимальной длины названия уровня.
formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s"
// Дополнить название уровня пробелами, например:
// - "INFO "
// - "WARNING"
levelText = fmt.Sprintf(formatString, levelText)
}
// Удалить завершающий перевод строки, чтобы поведение совпадало
// с text_formatter из logrus и стандартным пакетом log.
entry.Message = strings.TrimSuffix(entry.Message, "\n")
caller := ""
if entry.HasCaller() {
var (
funcVal string
fileVal string
ok bool
)
if fileVal, ok = data[CustomKeyFile].(string); ok && fileVal != "" {
delete(data, CustomKeyFile)
}
if funcVal, ok = data[CustomKeyFunc].(string); ok && funcVal != "" {
delete(data, CustomKeyFunc)
}
if fileVal == "" && funcVal == "" {
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
} else {
fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
funcVal = fmt.Sprintf("%s()", entry.Caller.Function)
}
}
b := strings.Builder{}
if fileVal != "" {
b.WriteByte(' ')
b.WriteString(fileVal)
}
if funcVal != "" {
b.WriteByte(' ')
b.WriteString(funcVal)
}
caller = b.String()
}
switch {
case !f.FullTimestamp:
_, _ = fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
default:
_, _ = fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
}
for _, k := range keys {
v := data[k]
_, _ = fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
f.appendValue(b, v)
}
}
func (f *CustomFormatter) needsQuoting(text string) bool {
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
return true
}
}
return false
}
func (f *CustomFormatter) appendValue(b *bytes.Buffer, value interface{}) {
stringVal, ok := value.(string)
if !ok {
stringVal = fmt.Sprint(value)
}
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}
+35
View File
@@ -0,0 +1,35 @@
package logger
import (
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"github.com/sirupsen/logrus"
)
var once = sync.Once{}
func Init() {
once.Do(func() {
logrus.SetFormatter(&CustomFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02T15:04:05.000Z07:00",
DisableLevelTruncation: false,
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
filename := filepath.Base(f.File)
return "", fmt.Sprintf("%s:%d", filename, f.Line)
},
})
logrus.SetReportCaller(true)
})
if ll := os.Getenv("NEO_LOG_LEVEL"); ll != "" {
level, err := logrus.ParseLevel(ll)
if err != nil {
logrus.Fatalf("Не удалось разобрать уровень журналирования %v: %v", ll, err)
}
logrus.SetLevel(level)
}
}
+40
View File
@@ -0,0 +1,40 @@
package models
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
)
type ExploitType string
const (
ExploitTypeRecurrent ExploitType = "recurrent"
ExploitTypeEndless ExploitType = "endless"
)
type Exploit struct {
ID string
Version int64
Type ExploitType
}
func NewExploit(id string, version int64, exploitType ExploitType) *Exploit {
return &Exploit{
ID: id,
Version: version,
Type: exploitType,
}
}
func (i *Exploit) String() string {
return fmt.Sprintf("Exploit(%s_%d, type=%s)", i.ID, i.Version, i.Type)
}
func (i *Exploit) MetricLabels() prometheus.Labels {
return prometheus.Labels{
"exploit_id": i.ID,
"exploit_version": fmt.Sprintf("%d", i.Version),
"exploit_type": string(i.Type),
}
}
+27
View File
@@ -0,0 +1,27 @@
package models
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
)
type Target struct {
ID string
IP string
}
func NewTarget(teamID, teamIP string) *Target {
return &Target{
ID: teamID,
IP: teamIP,
}
}
func (i *Target) String() string {
return fmt.Sprintf("Target(id=%s, ip=%s)", i.ID, i.IP)
}
func (i *Target) MetricLabels() prometheus.Labels {
return prometheus.Labels{"target_id": i.ID, "target_ip": i.IP}
}
+188
View File
@@ -0,0 +1,188 @@
package queue
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/pkg/neosync"
)
const (
endlessDebounce = 3 * time.Second
)
// Проверки типов во время компиляции.
var (
_ Queue = (*endlessQueue)(nil)
)
type endlessQueue struct {
out chan *Output
c chan *Job
maxJobs int
metrics *Metrics
logger *logrus.Entry
}
func NewEndlessQueue(maxJobs int) Queue {
queueID := uuid.NewString()[:8]
return &endlessQueue{
out: make(chan *Output, resultBufferSize),
c: make(chan *Job, jobBufferSize),
maxJobs: maxJobs,
metrics: NewMetrics("neo", queueID, TypeEndless),
logger: logrus.WithFields(logrus.Fields{
"component": "endless_queue",
"id": queueID,
}),
}
}
func (q *endlessQueue) Type() Type {
return TypeEndless
}
func (q *endlessQueue) Size() int {
return len(q.c)
}
// Start выполняется синхронно. Чтобы остановить очередь, отмените контекст.
func (q *endlessQueue) Start(ctx context.Context) {
q.logger.WithField("jobs", q.maxJobs).Info("Запуск очереди")
q.metrics.MaxJobs.Add(float64(q.maxJobs))
defer q.metrics.MaxJobs.Sub(float64(q.maxJobs))
wg := sync.WaitGroup{}
wg.Add(q.maxJobs)
for i := 0; i < q.maxJobs; i++ {
go func() {
defer wg.Done()
q.worker(ctx)
}()
}
wg.Wait()
q.logger.Info("Очередь остановлена")
}
func (q *endlessQueue) Results() <-chan *Output {
return q.out
}
func (q *endlessQueue) Add(task *Job) error {
select {
case q.c <- task:
return nil
default:
return ErrQueueFull
}
}
func (q *endlessQueue) String() string {
return "EndlessQueue"
}
func (q *endlessQueue) worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case job := <-q.c:
for {
select {
case <-ctx.Done():
return
default:
}
err := q.runExploit(ctx, job)
switch {
case errors.Is(err, context.Canceled):
return
case err != nil:
job.logger.Errorf("Бесконечный эксплойт завершился с ошибкой: %v", err)
neosync.Sleep(ctx, endlessDebounce)
default:
job.logger.Errorf("Бесконечный эксплойт завершился неожиданно")
neosync.Sleep(ctx, endlessDebounce)
}
}
}
}
}
func (q *endlessQueue) runExploit(ctx context.Context, job *Job) error {
cmd := job.Command(ctx)
job.logger.Infof("Бесконечный запуск задания: %s", cmd)
// os.Pipe работает быстрее io.Pipe.
r, w, err := os.Pipe()
if err != nil {
return fmt.Errorf("создание канала вывода: %w", err)
}
exploitLabels := job.Exploit.MetricLabels()
errC := make(chan error, 1)
go func() {
defer func(w *os.File) {
if err := w.Close(); err != nil {
job.logger.Errorf("Ошибка закрытия канала вывода: %v", err)
}
}(w)
cmd.Stdout = w
cmd.Stderr = w
q.metrics.ExploitInstancesRunning.With(exploitLabels).Inc()
defer q.metrics.ExploitInstancesRunning.With(exploitLabels).Dec()
errC <- cmd.Run()
}()
readDone := make(chan struct{})
defer func() {
job.logger.Infof("Ожидание завершения чтения вывода")
<-readDone
}()
go func() {
defer close(readDone)
scanner := bufio.NewScanner(r)
for scanner.Scan() {
q.out <- NewOutput(job, scanner.Bytes())
}
if err := scanner.Err(); err != nil && ctx.Err() == nil {
job.logger.Errorf("Ошибка чтения вывода бесконечного задания: %v", err)
}
}()
select {
case <-ctx.Done():
<-errC
q.metrics.ExploitsFinished.With(exploitLabels).Inc()
return nil
case err := <-errC:
// Ожидаемая ошибка при отмене контекста.
if ctx.Err() != nil {
q.metrics.ExploitsFinished.With(exploitLabels).Inc()
return nil
}
job.logger.Errorf("Бесконечный эксплойт %v завершился: %v", job, err)
q.metrics.ExploitsFailed.With(exploitLabels).Inc()
if err != nil {
return fmt.Errorf("ошибка бесконечного эксплойта %v: %w", job, err)
}
return nil
}
}
@@ -0,0 +1,15 @@
package queue
type endlessQueueFactory struct{}
func (f endlessQueueFactory) Create(maxJobs int) Queue {
return NewEndlessQueue(maxJobs)
}
func (f endlessQueueFactory) Type() Type {
return TypeEndless
}
func NewEndlessQueueFactory() Factory {
return endlessQueueFactory{}
}
@@ -0,0 +1,88 @@
package queue
import (
"context"
"sync"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
"github.com/c4t-but-s4d/neo/v2/internal/logger"
"github.com/c4t-but-s4d/neo/v2/internal/models"
"github.com/c4t-but-s4d/neo/v2/pkg/testutils"
)
func TestMain(m *testing.M) {
logger.Init()
logrus.SetLevel(logrus.DebugLevel)
goleak.VerifyTestMain(m)
}
func Test_endlessQueue_Add(t *testing.T) {
makeQueue := func(s int) *endlessQueue {
q := NewEndlessQueue(1).(*endlessQueue)
q.c = make(chan *Job, s)
return q
}
for _, tc := range []struct {
q *endlessQueue
t *Job
wantTask *Job
wantErr error
}{
{q: makeQueue(100), t: &Job{executable: "1"}, wantErr: nil},
{q: makeQueue(1), t: &Job{executable: "1"}, wantErr: nil},
{q: makeQueue(0), t: &Job{executable: "1"}, wantErr: ErrQueueFull},
} {
tc.t.logger = testutils.DummyJobLogger("1", "127.0.0.1")
err := tc.q.Add(tc.t)
require.ErrorIs(t, err, tc.wantErr)
if err != nil {
continue
}
require.Equal(t, tc.t.executable, (<-tc.q.c).executable)
}
}
func Test_endlessQueue_Start(t *testing.T) {
q := NewEndlessQueue(10)
task := &Job{
Exploit: &models.Exploit{ID: "kek"},
Target: &models.Target{
ID: "id",
IP: "ip",
},
executable: "echo",
dir: "",
timeout: time.Second * 2,
logger: testutils.DummyJobLogger("echo", "ip"),
}
require.NoError(t, q.Add(task))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
q.Start(ctx)
}()
select {
case <-time.After(time.Second * 3):
t.Fatal("timeout")
case out := <-q.Results():
assert.Equal(t, task.Exploit, out.Exploit)
assert.Equal(t, task.Target, out.Target)
assert.Equal(t, task.Target.IP, string(out.Out))
break
}
cancel()
wg.Wait()
}
+112
View File
@@ -0,0 +1,112 @@
package queue
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"time"
"github.com/c4t-but-s4d/neo/v2/internal/models"
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
)
func NewJob(
exploit *models.Exploit,
target *models.Target,
executable, dir string,
environ []string,
timeout time.Duration,
logger *joblogger.JobLogger,
) *Job {
return &Job{
Exploit: exploit,
Target: target,
executable: executable,
dir: dir,
timeout: timeout,
environ: environ,
logger: logger,
}
}
type Job struct {
Exploit *models.Exploit
Target *models.Target
executable string
dir string
environ []string
timeout time.Duration
logger *joblogger.JobLogger
}
func (t *Job) String() string {
return fmt.Sprintf(
"Job(exploit=%v, target=%v, path=%s, timeout=%v, env-vars=%d)",
t.Exploit,
t.Target,
t.executable,
t.timeout,
len(t.environ),
)
}
func (t *Job) Command(ctx context.Context) *exec.Cmd {
cmd := exec.CommandContext(ctx, t.executable, t.Target.IP)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process == nil {
return os.ErrProcessDone
}
if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && err != syscall.ESRCH {
return err
}
return nil
}
cmd.WaitDelay = 2 * time.Second
if t.dir != "" {
cmd.Dir = t.dir
}
cmd.Env = jobEnvironment(os.Environ(), t.environ)
// Отключить буферизацию вывода скриптов Python.
cmd.Env = append(cmd.Env, "PYTHONUNBUFFERED=1")
// Отключить использование терминала в pwntools.
cmd.Env = append(cmd.Env, "PWNLIB_NOTERM=1")
return cmd
}
var controlPlaneSecrets = map[string]struct{}{
"NEO_GRPC_AUTH_KEY": {},
"NEO_WORKER_KEY": {},
"NEO_KEY": {},
"GRPC_AUTH_KEY": {},
"FARM_PASSWORD": {},
"NEO_FARM_PASSWORD": {},
}
func jobEnvironment(base, extra []string) []string {
values := make([]string, 0, len(base)+len(extra))
positions := make(map[string]int, len(base)+len(extra))
for _, entry := range append(append([]string(nil), base...), extra...) {
key, _, ok := strings.Cut(entry, "=")
if !ok {
continue
}
if _, secret := controlPlaneSecrets[strings.ToUpper(key)]; secret {
continue
}
if pos, exists := positions[key]; exists {
values[pos] = entry
continue
}
positions[key] = len(values)
values = append(values, entry)
}
return values
}
+45
View File
@@ -0,0 +1,45 @@
package queue
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"github.com/c4t-but-s4d/neo/v2/internal/models"
"github.com/stretchr/testify/require"
)
func TestJobEnvironmentDoesNotPassControlPlaneSecrets(t *testing.T) {
env := jobEnvironment(
[]string{"PATH=/usr/bin", "NEO_GRPC_AUTH_KEY=worker-secret", "NEO_FARM_PASSWORD=farm-secret"},
[]string{"NEO_WORKER_KEY=worker-secret", "TEAM_TOKEN=job-token", "MODE=old", "MODE=new"},
)
require.Equal(t, []string{"PATH=/usr/bin", "TEAM_TOKEN=job-token", "MODE=new"}, env)
}
func TestJobStringDoesNotIncludeEnvironmentValues(t *testing.T) {
job := NewJob(nil, &models.Target{IP: "127.0.0.1"}, "/bin/true", "", []string{"NEO_GRPC_AUTH_KEY=worker-secret"}, time.Second, nil)
require.NotContains(t, job.String(), "worker-secret")
require.NotContains(t, job.Command(context.Background()).Env, "NEO_GRPC_AUTH_KEY=worker-secret")
}
func TestJobTimeoutKillsChildProcesses(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "child-finished")
script := filepath.Join(dir, "job.sh")
contents := "#!/bin/sh\n(sleep 0.5; printf done > \"" + marker + "\") &\nwait\n"
require.NoError(t, os.WriteFile(script, []byte(contents), 0700))
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
job := NewJob(nil, &models.Target{IP: "127.0.0.1"}, script, dir, nil, time.Second, nil)
started := time.Now()
err := job.Command(ctx).Run()
require.Error(t, err)
require.Less(t, time.Since(started), time.Second)
time.Sleep(600 * time.Millisecond)
_, err = os.Stat(marker)
require.ErrorIs(t, err, os.ErrNotExist)
}
+78
View File
@@ -0,0 +1,78 @@
package queue
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type Metrics struct {
ExploitInstancesRunning *prometheus.GaugeVec
ExploitsFinished *prometheus.CounterVec
ExploitsFailed *prometheus.CounterVec
ExploitRunTime *prometheus.HistogramVec
MaxJobs prometheus.Gauge
}
func NewMetrics(namespace, id string, queueType Type) *Metrics {
const subsystem = "exploit_queue"
exploitLabels := []string{"exploit_id", "exploit_version", "exploit_type"}
constLabels := prometheus.Labels{
"queue_type": queueType.String(),
"queue_id": id,
}
return &Metrics{
ExploitInstancesRunning: promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "exploit_instances_running",
Help: "Number of exploit instances currently running",
ConstLabels: constLabels,
},
exploitLabels,
),
ExploitsFinished: promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "exploits_finished_total",
Help: "Number of exploits finished",
ConstLabels: constLabels,
},
exploitLabels,
),
ExploitsFailed: promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "exploits_failed_total",
Help: "Number of exploits failed",
ConstLabels: constLabels,
},
exploitLabels,
),
ExploitRunTime: promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "exploit_run_time_seconds",
Help: "Time it took to run an exploit",
ConstLabels: constLabels,
Buckets: prometheus.ExponentialBucketsRange(0.001, 300, 30),
},
exploitLabels,
),
MaxJobs: promauto.NewGauge(
prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "max_jobs",
Help: "Maximum number of jobs for the current runner",
ConstLabels: constLabels,
},
),
}
}
+25
View File
@@ -0,0 +1,25 @@
package queue
import (
"fmt"
"github.com/c4t-but-s4d/neo/v2/internal/models"
)
type Output struct {
Exploit *models.Exploit
Target *models.Target
Out []byte
}
func NewOutput(job *Job, out []byte) *Output {
return &Output{
Exploit: job.Exploit,
Target: job.Target,
Out: out,
}
}
func (o *Output) String() string {
return fmt.Sprintf("%s (%s): %s", o.Exploit, o.Target, o.Out)
}
+37
View File
@@ -0,0 +1,37 @@
package queue
import (
"context"
"errors"
"fmt"
)
var (
ErrQueueFull = errors.New("очередь заданий заполнена")
)
type Type string
func (t Type) String() string {
return string(t)
}
const (
TypeSimple Type = "simple"
TypeEndless Type = "endless"
)
type Factory interface {
Create(maxJobs int) Queue
Type() Type
}
type Queue interface {
Start(context.Context)
Add(*Job) error
Results() <-chan *Output
Type() Type
Size() int
fmt.Stringer
}
+150
View File
@@ -0,0 +1,150 @@
package queue
import (
"context"
"errors"
"fmt"
"os/exec"
"sync"
"time"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
const (
jobBufferSize = 1000
resultBufferSize = 1000
)
// Проверки типов во время компиляции.
var (
_ Queue = (*simpleQueue)(nil)
)
type simpleQueue struct {
out chan *Output
c chan *Job
maxJobs int
metrics *Metrics
logger *logrus.Entry
}
func NewSimpleQueue(maxJobs int) Queue {
id := uuid.NewString()[:8]
return &simpleQueue{
out: make(chan *Output, resultBufferSize),
c: make(chan *Job, jobBufferSize),
maxJobs: maxJobs,
metrics: NewMetrics("neo", id, TypeSimple),
logger: logrus.WithFields(logrus.Fields{
"component": "simple_queue",
"id": id,
}),
}
}
func (q *simpleQueue) Type() Type {
return TypeSimple
}
func (q *simpleQueue) Size() int {
return len(q.c)
}
// Start выполняется синхронно. Чтобы остановить очередь, отмените контекст.
func (q *simpleQueue) Start(ctx context.Context) {
q.logger.WithField("jobs", q.maxJobs).Info("Запуск очереди")
q.metrics.MaxJobs.Add(float64(q.maxJobs))
defer q.metrics.MaxJobs.Sub(float64(q.maxJobs))
wg := sync.WaitGroup{}
wg.Add(q.maxJobs)
for i := 0; i < q.maxJobs; i++ {
go func() {
defer wg.Done()
q.worker(ctx)
}()
}
wg.Wait()
q.logger.Info("Очередь остановлена")
}
func (q *simpleQueue) Results() <-chan *Output {
return q.out
}
func (q *simpleQueue) Add(task *Job) error {
select {
case q.c <- task:
return nil
default:
return ErrQueueFull
}
}
func (q *simpleQueue) String() string {
return "SimpleQueue"
}
func (q *simpleQueue) worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case task := <-q.c:
res, err := q.runExploit(ctx, task)
exploitLabels := task.Exploit.MetricLabels()
var exitErr *exec.ExitError
switch {
case err == nil:
task.logger.Infof("Задание выполнено")
q.metrics.ExploitsFinished.With(exploitLabels).Inc()
case errors.Is(err, context.Canceled):
// При перезапуске очереди ожидается ошибка.
q.metrics.ExploitsFinished.With(exploitLabels).Inc()
return
case errors.As(err, &exitErr):
if exitErr.ExitCode() == -1 {
task.logger.Warningf("Эксплойт завершился по сигналу: %v", exitErr)
} else {
task.logger.Warningf("Ошибка при выполнении эксплойта: %v", err)
}
q.metrics.ExploitsFailed.With(exploitLabels).Inc()
default:
task.logger.Errorf("Не удалось выполнить задание: %v", err)
q.metrics.ExploitsFailed.With(exploitLabels).Inc()
}
q.out <- NewOutput(task, res)
}
}
}
func (q *simpleQueue) runExploit(ctx context.Context, task *Job) ([]byte, error) {
cmdCtx, cancel := context.WithTimeout(ctx, task.timeout)
defer cancel()
cmd := task.Command(cmdCtx)
task.logger.Infof("Запуск задания: %v", cmd)
start := time.Now()
exploitLabels := task.Exploit.MetricLabels()
q.metrics.ExploitInstancesRunning.With(exploitLabels).Inc()
defer func() {
q.metrics.ExploitInstancesRunning.With(exploitLabels).Dec()
q.metrics.ExploitRunTime.With(exploitLabels).Observe(time.Since(start).Seconds())
}()
// Процесс завершится при отмене контекста.
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("ошибка выполнения команды: %w", err)
}
return out, err
}
@@ -0,0 +1,15 @@
package queue
type simpleQueueFactory struct{}
func (f simpleQueueFactory) Create(maxJobs int) Queue {
return NewSimpleQueue(maxJobs)
}
func (f simpleQueueFactory) Type() Type {
return TypeSimple
}
func NewSimpleQueueFactory() Factory {
return simpleQueueFactory{}
}
@@ -0,0 +1,174 @@
package queue
import (
"context"
"os/exec"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/c4t-but-s4d/neo/v2/internal/models"
"github.com/c4t-but-s4d/neo/v2/pkg/testutils"
)
func TestSimpleQueue_Add(t *testing.T) {
makeQueue := func(s int) *simpleQueue {
q := NewSimpleQueue(1).(*simpleQueue)
q.c = make(chan *Job, s)
return q
}
for _, tc := range []struct {
q *simpleQueue
t *Job
wantTask *Job
wantErr error
}{
{
q: makeQueue(100),
t: &Job{
Exploit: &models.Exploit{ID: "kek"},
Target: &models.Target{ID: "t", IP: "i"},
executable: "1",
},
wantErr: nil,
},
{
q: makeQueue(1),
t: &Job{
Exploit: &models.Exploit{ID: "kek"},
Target: &models.Target{ID: "t", IP: "i"},
executable: "1",
},
wantErr: nil,
},
{
q: makeQueue(0),
t: &Job{
Exploit: &models.Exploit{ID: "kek"},
Target: &models.Target{ID: "t", IP: "i"},
executable: "1",
},
wantErr: ErrQueueFull,
},
} {
tc.t.logger = testutils.DummyJobLogger(tc.t.Exploit.ID, tc.t.Target.IP)
err := tc.q.Add(tc.t)
require.ErrorIs(t, err, tc.wantErr)
if err != nil {
continue
}
require.Equal(t, tc.t.executable, (<-tc.q.c).executable)
}
}
func TestSimpleQueue_runExploit(t *testing.T) {
for _, tc := range []struct {
q *simpleQueue
t *Job
ctx context.Context
wantErr error
wantData []byte
}{
{
q: NewSimpleQueue(1).(*simpleQueue),
t: &Job{
Exploit: &models.Exploit{ID: "echo"},
executable: "echo",
Target: &models.Target{ID: "id", IP: "ip"},
timeout: time.Second * 5,
},
wantErr: nil,
wantData: []byte("ip\n"),
ctx: context.Background(),
},
{
q: NewSimpleQueue(1).(*simpleQueue),
t: &Job{
Exploit: &models.Exploit{ID: "bad executable"},
executable: "notfoundcli",
Target: &models.Target{ID: "id", IP: "ip"},
timeout: time.Second * 5,
},
wantErr: exec.ErrNotFound,
wantData: nil,
ctx: context.Background(),
},
{
q: NewSimpleQueue(1).(*simpleQueue),
t: &Job{
Exploit: &models.Exploit{ID: "cancelled ctx"},
executable: "echo",
Target: &models.Target{ID: "id", IP: "ip"},
timeout: time.Second * 5,
},
wantErr: context.Canceled,
wantData: nil,
ctx: testutils.CanceledContext(),
},
{
q: NewSimpleQueue(1).(*simpleQueue),
t: &Job{
Exploit: &models.Exploit{ID: "timed out ctx"},
executable: "echo",
Target: &models.Target{ID: "id", IP: "ip"},
timeout: time.Second * 5,
},
wantErr: context.DeadlineExceeded,
wantData: nil,
ctx: testutils.TimedOutContext(),
},
{
q: NewSimpleQueue(1).(*simpleQueue),
t: &Job{
Exploit: &models.Exploit{ID: "zero timeout"},
executable: "echo",
Target: &models.Target{ID: "id", IP: "ip"},
timeout: time.Second * 0,
},
wantErr: context.DeadlineExceeded,
wantData: nil,
ctx: context.Background(),
},
} {
tc.t.logger = testutils.DummyJobLogger(tc.t.Exploit.ID, tc.t.Target.IP)
data, err := tc.q.runExploit(tc.ctx, tc.t)
require.ErrorIs(t, err, tc.wantErr)
if diff := cmp.Diff(data, tc.wantData, cmpopts.EquateEmpty()); diff != "" {
t.Errorf("simpleQueue.runExploit() returned data mismatch (-want +got):\n%s", diff)
}
}
}
func TestSimpleQueue_Start(t *testing.T) {
q := NewSimpleQueue(10)
task := &Job{
Exploit: &models.Exploit{ID: "kek"},
Target: &models.Target{
ID: "id",
IP: "ip",
},
executable: "echo",
dir: "",
timeout: time.Second * 2,
logger: testutils.DummyJobLogger("echo", "ip"),
}
require.NoError(t, q.Add(task))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go q.Start(ctx)
select {
case <-time.After(time.Second * 3):
t.Fatal("timeout")
case out := <-q.Results():
assert.Equal(t, task.Exploit, out.Exploit)
assert.Equal(t, task.Target, out.Target)
assert.Equal(t, task.Target.IP+"\n", string(out.Out))
}
}
@@ -0,0 +1,37 @@
package common
import (
"context"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type LoggingServer struct {
Logger *logrus.Entry
}
func NewLoggingServer(serverName string) LoggingServer {
return LoggingServer{Logger: logrus.WithField("server", serverName)}
}
func (s *LoggingServer) WrapErrorf(ctx context.Context, code codes.Code, fmt string, values ...any) error {
err := status.Errorf(code, fmt, values...)
s.GetMethodLogger(ctx).Errorf("%v", err)
return err // nolint
}
func (s *LoggingServer) LogRequest(ctx context.Context, r any) {
// Данные RPC могут содержать секреты или вывод недоверенной программы.
// Записывать только тип запроса, но не его значения.
s.GetMethodLogger(ctx).Infof("Request type: %T", r)
}
func (s *LoggingServer) GetMethodLogger(ctx context.Context) *logrus.Entry {
if method, ok := grpc.Method(ctx); ok {
return s.Logger.WithField("method", method)
}
return s.Logger
}
@@ -0,0 +1,69 @@
package config
import (
"encoding/json"
"fmt"
"io"
"net/url"
"strings"
"time"
"github.com/c4t-but-s4d/neo/v2/pkg/grpcauth"
)
type Config struct {
Debug bool `mapstructure:"debug"`
Addr string `mapstructure:"addr"`
DBPath string `mapstructure:"db_path"`
RedisURL string `mapstructure:"redis_url"`
BaseDir string `mapstructure:"base_dir"`
PingEvery time.Duration `mapstructure:"ping_every"`
SubmitEvery time.Duration `mapstructure:"submit_every"`
FarmConfig FarmConfig `mapstructure:"farm"`
GrpcAuthKey string `mapstructure:"grpc_auth_key"`
WorkerKey string `mapstructure:"worker_key"`
Environ map[string]string `mapstructure:"env"`
MetricsNamespace string `mapstructure:"metrics_namespace"`
}
type FarmConfig struct {
URL string `mapstructure:"url"`
Password string `mapstructure:"password"`
FlagRegexp string `json:"FLAG_FORMAT"`
Teams map[string]string `json:"TEAMS"`
}
func (cfg *Config) Validate() error {
if err := grpcauth.ValidateKeyPair(cfg.GrpcAuthKey, cfg.WorkerKey); err != nil {
return err
}
if strings.TrimSpace(cfg.FarmConfig.Password) == "" {
return fmt.Errorf("farm.password обязателен")
}
u, err := url.Parse(cfg.FarmConfig.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil {
return fmt.Errorf("farm.url должен быть HTTP(S) адресом без учетных данных")
}
if cfg.Addr == "" || cfg.DBPath == "" || cfg.BaseDir == "" || cfg.RedisURL == "" {
return fmt.Errorf("обязательны поля addr, db_path, base_dir и redis_url")
}
if cfg.PingEvery <= 0 || cfg.SubmitEvery <= 0 {
return fmt.Errorf("ping_every и submit_every должны быть положительными")
}
return nil
}
func (cfg *FarmConfig) ParseJSON(r io.Reader) error {
dec := json.NewDecoder(r)
if err := dec.Decode(cfg); err != nil {
return fmt.Errorf("разбор JSON: %w", err)
}
var extra any
if err := dec.Decode(&extra); err != io.EOF {
if err == nil {
return fmt.Errorf("после объекта JSON обнаружены лишние данные")
}
return fmt.Errorf("проверка конца JSON: %w", err)
}
return nil
}
@@ -0,0 +1,43 @@
package config
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func validTestConfig() *Config {
return &Config{
Addr: ":5005",
DBPath: "/data/db.db",
RedisURL: "redis://neo-redis:6379/0",
BaseDir: "/data/exploits",
PingEvery: time.Second,
SubmitEvery: time.Second,
GrpcAuthKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
WorkerKey: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
FarmConfig: FarmConfig{
URL: "http://farm:5000",
Password: "farm-secret",
},
}
}
func TestValidateRequiresDifferentAdminAndWorkerKeys(t *testing.T) {
cfg := validTestConfig()
require.NoError(t, cfg.Validate())
cfg.WorkerKey = cfg.GrpcAuthKey
require.ErrorContains(t, cfg.Validate(), "должны различаться")
}
func TestValidateRequiresFarmCredentialsAndHTTPURL(t *testing.T) {
cfg := validTestConfig()
cfg.FarmConfig.Password = ""
require.ErrorContains(t, cfg.Validate(), "farm.password")
cfg = validTestConfig()
cfg.FarmConfig.URL = "http://user:pass@farm:5000"
require.ErrorContains(t, cfg.Validate(), "без учетных данных")
}
@@ -0,0 +1,66 @@
package exploits
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/c4t-but-s4d/neo/v2/internal/server/config"
)
func NewFarmClient(cfg config.FarmConfig) *FarmClient {
return &FarmClient{
url: strings.TrimRight(cfg.URL, "/"),
password: cfg.Password,
client: http.Client{
Timeout: 3 * time.Second,
},
}
}
type FarmClient struct {
url string
password string
client http.Client
}
const maxFarmConfigBytes = 1 << 20
func (fc *FarmClient) FillConfig(ctx context.Context, cfg *config.FarmConfig) error {
url := fmt.Sprintf("%s/api/get_config", fc.url)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return fmt.Errorf("создание запроса к Farm: %w", err)
}
req.Header.Set("Authorization", fc.password)
req.Header.Set("X-Token", fc.password)
resp, err := fc.client.Do(req)
if err != nil {
return fmt.Errorf("выполнение запроса к Farm: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
logrus.Errorf("Не удалось закрыть ответ Farm: %v", err)
}
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Farm вернул HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFarmConfigBytes+1))
if err != nil {
return fmt.Errorf("чтение конфигурации Farm: %w", err)
}
if len(body) > maxFarmConfigBytes {
return fmt.Errorf("конфигурация Farm превышает %d байт", maxFarmConfigBytes)
}
if err := cfg.ParseJSON(bytes.NewReader(body)); err != nil {
return fmt.Errorf("разбор ответа Farm: %w", err)
}
return nil
}
@@ -0,0 +1,21 @@
package exploits
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type Metrics struct {
AliveClients prometheus.Gauge
}
func NewMetrics(namespace string) *Metrics {
return &Metrics{
AliveClients: promauto.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: "server",
Name: "alive_clients",
Help: "Number of alive clients",
}),
}
}
@@ -0,0 +1,236 @@
package exploits
import (
"context"
"fmt"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/google/uuid"
"google.golang.org/grpc/codes"
"github.com/c4t-but-s4d/neo/v2/internal/config"
"github.com/c4t-but-s4d/neo/v2/internal/server/common"
serverConfig "github.com/c4t-but-s4d/neo/v2/internal/server/config"
"github.com/c4t-but-s4d/neo/v2/pkg/gstream"
"github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
"github.com/c4t-but-s4d/neo/v2/pkg/pubsub"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
func New(cfg *serverConfig.Config, storage *CachedStorage) *Server {
ems := &Server{
LoggingServer: common.NewLoggingServer("exploits"),
storage: storage,
buckets: hostbucket.New(cfg.FarmConfig.Teams),
visits: newVisitsMap(),
singleRunPubSub: pubsub.NewPubSub[*epb.SingleRunRequest](),
broadcastPubSub: pubsub.NewPubSub[*epb.BroadcastRequest](),
metrics: NewMetrics(cfg.MetricsNamespace),
}
ems.UpdateConfig(cfg)
return ems
}
type Server struct {
epb.UnimplementedServiceServer
common.LoggingServer
storage *CachedStorage
config *config.ExploitsConfig
cfgMutex sync.RWMutex
buckets *hostbucket.HostBucket
visits *visitsMap
metrics *Metrics
singleRunPubSub *pubsub.PubSub[*epb.SingleRunRequest]
broadcastPubSub *pubsub.PubSub[*epb.BroadcastRequest]
}
func (s *Server) Ping(ctx context.Context, r *epb.PingRequest) (*epb.PingResponse, error) {
s.LogRequest(ctx, r)
if r == nil {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "требуется запрос Ping")
}
switch p := r.Payload.(type) {
case *epb.PingRequest_ServerInfoRequest:
// Пропустить эту запись.
case *epb.PingRequest_HeartbeatRequest:
s.cfgMutex.RLock()
defer s.cfgMutex.RUnlock()
s.visits.Add(r.ClientId)
s.buckets.AddNode(r.ClientId, int(p.HeartbeatRequest.Weight))
case *epb.PingRequest_LeaveRequest:
s.visits.MarkInvalid(r.ClientId)
default:
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неизвестный тип данных: %T", p)
}
return &epb.PingResponse{
State: &epb.ServerState{
ClientTeamMap: s.buckets.Buckets(),
Exploits: s.storage.States(),
Config: config.ToProto(s.config),
},
}, nil
}
func (s *Server) Exploit(ctx context.Context, r *epb.ExploitRequest) (*epb.ExploitResponse, error) {
s.LogRequest(ctx, r)
if r == nil || !validExploitID(r.ExploitId) {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный идентификатор эксплойта")
}
state, ok := s.storage.GetState(r.ExploitId)
if !ok {
return nil, s.WrapErrorf(ctx, codes.NotFound, "эксплойт %q не найден", r.ExploitId)
}
return &epb.ExploitResponse{
State: state,
}, nil
}
func (s *Server) UpdateExploit(ctx context.Context, r *epb.UpdateExploitRequest) (*epb.UpdateExploitResponse, error) {
s.LogRequest(ctx, r)
if r == nil || r.State == nil || r.State.Config == nil || r.State.File == nil ||
!validExploitID(r.State.ExploitId) || !validFileUUID(r.State.File.Uuid) {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверное состояние эксплойта")
}
if r.State.Config.IsArchive && (r.State.Config.Entrypoint == "" ||
strings.ContainsAny(r.State.Config.Entrypoint, "\\\x00") || !filepath.IsLocal(r.State.Config.Entrypoint)) {
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный путь точки входа в архиве")
}
newState, err := s.storage.UpdateExploitVersion(r.State)
if err != nil {
return nil, s.WrapErrorf(ctx, codes.Internal, "Не удалось обновить версию эксплойта: %v", err)
}
return &epb.UpdateExploitResponse{State: newState}, nil
}
func validExploitID(id string) bool {
return id != "" && len(id) <= 128 && id != "." && id != ".." &&
!strings.ContainsAny(id, "/\\\x00") && filepath.IsLocal(id)
}
func validFileUUID(id string) bool {
parsed, err := uuid.Parse(id)
return err == nil && parsed.String() == id
}
func (s *Server) BroadcastCommand(ctx context.Context, r *epb.BroadcastRequest) (*epb.BroadcastResponse, error) {
s.LogRequest(ctx, r)
s.broadcastPubSub.Publish(r)
return &epb.BroadcastResponse{}, nil
}
func (s *Server) BroadcastSubscribe(r *epb.BroadcastSubscribeRequest, stream epb.Service_BroadcastSubscribeServer) error {
s.LogRequest(stream.Context(), r)
wstream := gstream.Wrap[
epb.BroadcastRequest,
epb.BroadcastSubscribeResponse,
](
stream,
func(t *epb.BroadcastRequest) *epb.BroadcastSubscribeResponse {
return &epb.BroadcastSubscribeResponse{Command: t.Command}
},
)
sub := s.broadcastPubSub.Subscribe(wstream.Send)
defer s.broadcastPubSub.Unsubscribe(sub)
sub.Run(stream.Context())
return nil
}
func (s *Server) SingleRun(ctx context.Context, r *epb.SingleRunRequest) (*epb.SingleRunResponse, error) {
s.LogRequest(ctx, r)
s.singleRunPubSub.Publish(r)
return &epb.SingleRunResponse{}, nil
}
func (s *Server) SingleRunSubscribe(r *epb.SingleRunSubscribeRequest, stream epb.Service_SingleRunSubscribeServer) error {
s.LogRequest(stream.Context(), r)
wstream := gstream.Wrap[
epb.SingleRunRequest,
epb.SingleRunSubscribeResponse,
](
stream,
func(t *epb.SingleRunRequest) *epb.SingleRunSubscribeResponse {
return &epb.SingleRunSubscribeResponse{ExploitId: t.ExploitId}
},
)
sub := s.singleRunPubSub.Subscribe(wstream.Send)
defer s.singleRunPubSub.Unsubscribe(sub)
sub.Run(stream.Context())
return nil
}
func (s *Server) HeartBeat(ctx context.Context) {
ticker := time.NewTicker(s.config.PingEvery)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.Logger.Info("Проверка клиентов")
s.checkClients()
case <-ctx.Done():
return
}
}
}
func (s *Server) UpdateMetrics(ctx context.Context) {
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.Logger.Info("Обновление метрик")
s.updateMetrics()
case <-ctx.Done():
return
}
}
}
func (s *Server) UpdateConfig(cfg *serverConfig.Config) {
env := make([]string, 0, len(cfg.Environ))
for k, v := range cfg.Environ {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
s.cfgMutex.Lock()
defer s.cfgMutex.Unlock()
s.config = &config.ExploitsConfig{
PingEvery: cfg.PingEvery,
SubmitEvery: cfg.SubmitEvery,
FarmURL: cfg.FarmConfig.URL,
FarmPassword: cfg.FarmConfig.Password,
FlagRegexp: regexp.MustCompile(cfg.FarmConfig.FlagRegexp),
Environ: env,
}
s.buckets.UpdateTeams(cfg.FarmConfig.Teams)
}
func (s *Server) checkClients() {
alive, dead := s.visits.Invalidate(time.Now(), s.config.PingEvery)
s.Logger.Infof("Проверка связи: недоступные клиенты %v, доступные клиенты %v", dead, alive)
for _, c := range dead {
s.buckets.DeleteNode(c)
}
}
func (s *Server) updateMetrics() {
s.metrics.AliveClients.Set(float64(s.visits.Size()))
}
@@ -0,0 +1,165 @@
package exploits
import (
"context"
"fmt"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/testing/protocmp"
"github.com/c4t-but-s4d/neo/v2/internal/server/config"
"github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
)
func testServer(t *testing.T) (*Server, func()) {
t.Helper()
db, cleanupDB := testDB()
st, err := NewStorage(db)
require.NoError(t, err)
require.NoError(t, err)
cfg := &config.Config{
BaseDir: t.TempDir(),
MetricsNamespace: fmt.Sprintf("tests_%s", uuid.NewString()[:8]),
}
es := New(cfg, st)
return es, cleanupDB
}
func TestServer_UpdateExploit(t *testing.T) {
es, clean := testServer(t)
defer clean()
fileID := uuid.NewString()
cfg := &epb.ExploitConfiguration{
Entrypoint: "bin",
IsArchive: false,
}
r := &epb.UpdateExploitRequest{
State: &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: fileID},
Config: cfg,
},
}
resp, err := es.UpdateExploit(context.Background(), r)
require.NoError(t, err)
want := &epb.ExploitState{
ExploitId: "1",
Version: 1,
File: r.State.File,
Config: cfg,
}
if diff := cmp.Diff(want, resp.State, protocmp.Transform()); diff != "" {
t.Errorf("UpdateExploit() mismatch (-want +got):\n%s", diff)
}
}
func TestServer_Exploit(t *testing.T) {
es, clean := testServer(t)
defer clean()
fileID := uuid.NewString()
cfg := &epb.ExploitConfiguration{
Entrypoint: "bin",
IsArchive: false,
}
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: fileID},
Config: cfg,
}
req := &epb.UpdateExploitRequest{State: state}
ctx := context.Background()
_, err := es.UpdateExploit(ctx, req)
require.NoError(t, err)
resp, err := es.Exploit(ctx, &epb.ExploitRequest{ExploitId: state.ExploitId})
require.NoError(t, err)
wantState := &epb.ExploitState{
ExploitId: "1",
Version: 1,
File: state.File,
Config: cfg,
}
if diff := cmp.Diff(wantState, resp.State, protocmp.Transform()); diff != "" {
t.Errorf("Exploit() state mismatch (-want +got):\n%s", diff)
}
}
func TestServer_Ping(t *testing.T) {
es, clean := testServer(t)
defer clean()
fileID := uuid.NewString()
es.buckets = hostbucket.New(map[string]string{"id1": "ip1", "id2": "ip2"})
es.config.FarmURL = "test"
ctx := context.Background()
cfg := &epb.ExploitConfiguration{
Entrypoint: "bin",
IsArchive: false,
}
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: fileID},
Config: cfg,
}
r := &epb.UpdateExploitRequest{State: state}
updateResp, err := es.UpdateExploit(ctx, r)
require.NoError(t, err)
const clientID = "id1"
req := &epb.PingRequest{
ClientId: clientID,
Payload: &epb.PingRequest_HeartbeatRequest{
HeartbeatRequest: &epb.PingRequest_Heartbeat{},
},
}
resp, err := es.Ping(ctx, req)
require.NoError(t, err)
want := []*epb.ExploitState{updateResp.State}
if diff := cmp.Diff(want, resp.State.Exploits, protocmp.Transform()); diff != "" {
t.Errorf("Ping() states mismatch (-want +got):\n%s", diff)
}
if diff := cmp.Diff(es.buckets.Buckets(), resp.State.ClientTeamMap, protocmp.Transform()); diff != "" {
t.Errorf("Ping() bucket mismatch (-want +got):\n%s", diff)
}
require.NotEmpty(t, es.buckets.Buckets()[clientID].Teams)
require.Equal(t, es.config.FarmURL, resp.State.Config.FarmUrl)
require.True(t, es.visits.visits["id1"].Before(time.Now()))
}
func TestServer_BroadcastCommand(t *testing.T) {
es, clean := testServer(t)
defer clean()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var received *epb.BroadcastRequest
signal := make(chan struct{})
handler := func(msg *epb.BroadcastRequest) error {
received = msg
close(signal)
return nil
}
testSub := es.broadcastPubSub.Subscribe(handler)
defer es.broadcastPubSub.Unsubscribe(testSub)
go testSub.Run(ctx)
r := &epb.BroadcastRequest{Command: "echo 123"}
_, err := es.BroadcastCommand(ctx, r)
require.NoError(t, err)
select {
case <-signal:
break
case <-time.After(time.Millisecond * 100):
t.Errorf("Handler was not called in time")
}
require.Equal(t, r, received)
}
@@ -0,0 +1,133 @@
package exploits
import (
"fmt"
"strings"
"sync"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/proto"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
const (
stateBucketKey = "states"
)
func NewBoltStorage(path string) (*CachedStorage, error) {
db, err := bolt.Open(path, 0755, nil)
if err != nil {
return nil, fmt.Errorf("открытие базы Bolt %s: %w", path, err)
}
return NewStorage(db)
}
func NewStorage(db *bolt.DB) (*CachedStorage, error) {
cs := &CachedStorage{
stateCache: nil,
bdb: db,
}
if err := cs.initDB(); err != nil {
return nil, err
}
cs.initCache()
return cs, nil
}
type CachedStorage struct {
stateCache map[string]*epb.ExploitState
m sync.RWMutex
bdb *bolt.DB
}
func (cs *CachedStorage) States() []*epb.ExploitState {
cs.m.RLock()
defer cs.m.RUnlock()
return lo.Values(cs.stateCache)
}
func (cs *CachedStorage) GetState(exploitID string) (*epb.ExploitState, bool) {
cs.m.RLock()
defer cs.m.RUnlock()
val, ok := cs.stateCache[exploitID]
return val, ok
}
func (cs *CachedStorage) UpdateExploitVersion(newState *epb.ExploitState) (*epb.ExploitState, error) {
cs.m.Lock()
defer cs.m.Unlock()
if state, ok := cs.stateCache[newState.ExploitId]; ok {
newState.Version = state.Version + 1
} else {
newState.Version = 1
}
key := []byte(fmt.Sprintf("%s:%d", newState.ExploitId, newState.Version))
stateBytes, err := proto.Marshal(newState)
if err != nil {
return nil, fmt.Errorf("сериализация состояния: %w", err)
}
if err := cs.bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
if err := b.Put(key, stateBytes); err != nil {
return fmt.Errorf("сохранение состояния в базе: %w", err)
}
return nil
}); err != nil {
return nil, fmt.Errorf("обновление состояния в базе: %w", err)
}
cs.stateCache[newState.ExploitId] = newState
return newState, nil
}
func (cs *CachedStorage) initCache() {
cs.m.Lock()
defer cs.m.Unlock()
if cs.stateCache == nil {
cs.stateCache = make(map[string]*epb.ExploitState)
if err := cs.readDB(); err != nil {
logrus.Errorf("Не удалось прочитать данные эксплойта из базы: %v", err)
}
}
}
func (cs *CachedStorage) readDB() error {
if err := cs.bdb.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
if err := b.ForEach(func(k, v []byte) error {
key := string(k)
eID := strings.Split(key, ":")[0]
es := new(epb.ExploitState)
if err := proto.Unmarshal(v, es); err != nil {
return fmt.Errorf("разбор состояния эксплойта: %w", err)
}
if v, ok := cs.stateCache[eID]; !ok || es.Version > v.Version {
cs.stateCache[eID] = es
}
return nil
}); err != nil {
return fmt.Errorf("чтение состояний эксплойтов: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("чтение состояния из базы: %w", err)
}
return nil
}
func (cs *CachedStorage) initDB() error {
if err := cs.bdb.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucketIfNotExists([]byte(stateBucketKey)); err != nil {
return fmt.Errorf("создание раздела состояний: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("инициализация базы: %w", err)
}
return nil
}
@@ -0,0 +1,148 @@
package exploits
import (
"fmt"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
)
func testDB() (*bolt.DB, func()) {
tmpFile, err := os.CreateTemp("", "db")
if err != nil {
panic(err)
}
db, err := bolt.Open(tmpFile.Name(), 0755, nil)
if err != nil {
panic(err)
}
return db, func() {
defer func(name string) {
err := os.Remove(name)
if err != nil {
logrus.Errorf("Error removing file: %v", err)
}
}(tmpFile.Name())
if err := db.Close(); err != nil {
panic(err)
}
}
}
func TestCachedStorage_States(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
cs, err := NewStorage(db)
require.NoError(t, err)
for i := 0; i < 5; i++ {
state := &epb.ExploitState{
ExploitId: fmt.Sprintf("%d", i),
File: &fspb.FileInfo{Uuid: "1"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
_, err := cs.UpdateExploitVersion(state)
require.NoError(t, err)
}
require.Len(t, cs.States(), 5)
}
func TestCachedStorage_UpdateStates(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
cs, err := NewStorage(db)
require.NoError(t, err)
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: "1"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
_, err = cs.UpdateExploitVersion(state)
require.NoError(t, err)
require.EqualValues(t, 1, state.Version)
s, _ := cs.GetState(state.ExploitId)
if diff := cmp.Diff(state, s, protocmp.Transform()); diff != "" {
t.Errorf("UpdateExploitVersion(): unexpected state diff: (-want +got):\n%s", diff)
}
state = &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: "2"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek2",
IsArchive: true,
},
}
_, err = cs.UpdateExploitVersion(state)
require.NoError(t, err)
require.Len(t, cs.States(), 1)
require.EqualValues(t, 2, state.Version)
s, _ = cs.GetState(state.ExploitId)
if diff := cmp.Diff(state, s, protocmp.Transform()); diff != "" {
t.Errorf("UpdateExploitVersion(): unexpected state diff: (-want +got):\n%s", diff)
}
}
func TestCachedStorage_UpdateExploitVersionDB(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
cs, err := NewStorage(db)
require.NoError(t, err)
state := &epb.ExploitState{
ExploitId: "1",
File: &fspb.FileInfo{Uuid: "1"},
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
_, err = cs.UpdateExploitVersion(state)
require.NoError(t, err)
require.NoError(t, cs.readDB())
require.Len(t, cs.States(), 1)
}
// Проверка чтения кешированного хранилища из базы.
func TestCachedStorage_readDB(t *testing.T) {
db, cleanup := testDB()
defer cleanup()
state := &epb.ExploitState{
ExploitId: "1",
Version: 1,
Config: &epb.ExploitConfiguration{
Entrypoint: "./kek",
IsArchive: false,
},
}
cs, err := NewStorage(db)
require.NoError(t, err)
require.NoError(t, cs.bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
stateBytes, err := proto.Marshal(state)
require.NoError(t, err)
stateKey := []byte(fmt.Sprintf("%s:%d", state.ExploitId, state.Version))
if err := b.Put(stateKey, stateBytes); err != nil {
return fmt.Errorf("setting state in db: %w", err)
}
return nil
}))
require.NoError(t, cs.readDB())
if diff := cmp.Diff(state, cs.stateCache["1"], protocmp.Transform()); diff != "" {
t.Errorf("readDB(): unexpected diff for exploit with id = 1")
}
}
@@ -0,0 +1,56 @@
package exploits
import (
"sync"
"time"
)
const beatThreshold = 3
func newVisitsMap() *visitsMap {
return &visitsMap{
visits: make(map[string]time.Time),
}
}
type visitsMap struct {
visits map[string]time.Time
m sync.Mutex
}
func (vm *visitsMap) Add(cid string) {
vm.m.Lock()
defer vm.m.Unlock()
vm.visits[cid] = time.Now()
}
// MarkInvalid сбрасывает время клиента, чтобы следующий вызов Invalidate удалил его.
func (vm *visitsMap) MarkInvalid(cid string) {
vm.m.Lock()
defer vm.m.Unlock()
if _, ok := vm.visits[cid]; !ok {
return
}
vm.visits[cid] = time.Unix(0, 0)
}
func (vm *visitsMap) Invalidate(now time.Time, pingEvery time.Duration) (alive, dead []string) {
vm.m.Lock()
defer vm.m.Unlock()
for k, v := range vm.visits {
if v.Add(pingEvery * beatThreshold).Before(now) {
delete(vm.visits, k)
dead = append(dead, k)
} else {
alive = append(alive, k)
}
}
return alive, dead
}
func (vm *visitsMap) Size() int {
vm.m.Lock()
defer vm.m.Unlock()
return len(vm.visits)
}
@@ -0,0 +1,102 @@
package exploits
import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/c4t-but-s4d/neo/v2/pkg/testutils"
)
func TestVisitsMap_Invalidate(t *testing.T) {
generate := func(m map[string]time.Time) *visitsMap {
vm := newVisitsMap()
vm.visits = m
return vm
}
for _, tc := range []struct {
vm *visitsMap
dur string
now time.Time
want []string
}{
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "5s",
now: time.Unix(35, 0),
want: []string{"1"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "50s",
now: time.Unix(35, 0),
want: []string{},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "1s",
now: time.Unix(35, 0),
want: []string{"1", "2"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
dur: "5s",
now: time.Unix(15, 0),
want: []string{},
},
} {
d, _ := time.ParseDuration(tc.dur)
_, invalid := tc.vm.Invalidate(tc.now, d)
if diff := cmp.Diff(tc.want, invalid, cmpopts.SortSlices(testutils.LessString), cmpopts.EquateEmpty()); diff != "" {
t.Errorf("Invalidate() ids mismatch (-want +got):\n%s", diff)
}
}
}
func Test_visitsMap_MarkForDeletion(t *testing.T) {
generate := func(m map[string]time.Time) *visitsMap {
vm := newVisitsMap()
vm.visits = m
return vm
}
for _, tc := range []struct {
vm *visitsMap
dur string
now time.Time
mark []string
want []string
}{
{
vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
dur: "5s",
now: time.Unix(1000, 0),
mark: []string{"2"},
want: []string{"1", "2"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
dur: "100s",
now: time.Unix(1000, 0),
mark: []string{"1"},
want: []string{"1"},
},
{
vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
dur: "100s",
now: time.Unix(1000, 0),
mark: []string{"1", "2"},
want: []string{"1", "2"},
},
} {
d, _ := time.ParseDuration(tc.dur)
for _, cid := range tc.mark {
tc.vm.MarkInvalid(cid)
}
_, invalid := tc.vm.Invalidate(tc.now, d)
if diff := cmp.Diff(tc.want, invalid, cmpopts.SortSlices(testutils.LessString), cmpopts.EquateEmpty()); diff != "" {
t.Errorf("MarkInvalid() ids mismatch (-want +got):\n%s", diff)
}
}
}
+88
View File
@@ -0,0 +1,88 @@
package fs
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
)
type fileInterface interface {
io.ReadWriteCloser
Name() string
}
type filesystem interface {
Create(string) (fileInterface, error)
Open(string) (fileInterface, error)
Remove(string) error
}
type osFs struct {
root *os.Root
}
func newOsFs(dir string) (*osFs, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return nil, fmt.Errorf("определение пути каталога %s: %w", dir, err)
}
if err := os.MkdirAll(abs, 0700); err != nil {
return nil, fmt.Errorf("создание каталога %s: %w", dir, err)
}
root, err := os.OpenRoot(abs)
if err != nil {
return nil, fmt.Errorf("открытие каталога %s: %w", dir, err)
}
return &osFs{root: root}, nil
}
func (o *osFs) Create(f string) (fileInterface, error) {
if err := validateFileID(f); err != nil {
return nil, err
}
fi, err := o.root.OpenFile(f, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return nil, fmt.Errorf("создание файла %s в %s: %w", f, o.root.Name(), err)
}
return fi, nil
}
func (o *osFs) Open(f string) (fileInterface, error) {
if err := validateFileID(f); err != nil {
return nil, err
}
info, err := o.root.Lstat(f)
if err != nil {
return nil, fmt.Errorf("открытие файла %s в %s: %w", f, o.root.Name(), err)
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("путь %s в %s не является обычным файлом", f, o.root.Name())
}
fi, err := o.root.Open(f)
if err != nil {
return nil, fmt.Errorf("повторное открытие файла %s в %s: %w", f, o.root.Name(), err)
}
return fi, nil
}
func (o *osFs) Remove(f string) error {
if err := validateFileID(f); err != nil {
return err
}
if err := o.root.Remove(f); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("удаление файла %s в %s: %w", f, o.root.Name(), err)
}
return nil
}
func validateFileID(id string) error {
parsed, err := uuid.Parse(id)
if err != nil || parsed.String() != id || strings.ContainsAny(id, `/\\`) {
return fmt.Errorf("неверный идентификатор файла")
}
return nil
}
@@ -0,0 +1,35 @@
package fs
import (
"os"
"path/filepath"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func TestOSFSRejectsTraversalAndSymlink(t *testing.T) {
rootPath := t.TempDir()
root, err := newOsFs(rootPath)
require.NoError(t, err)
t.Cleanup(func() { _ = root.root.Close() })
_, err = root.Create("../outside")
require.Error(t, err)
id := uuid.NewString()
outside := filepath.Join(t.TempDir(), "outside")
require.NoError(t, os.WriteFile(outside, []byte("secret"), 0600))
require.NoError(t, os.Symlink(outside, filepath.Join(rootPath, id)))
_, err = root.Open(id)
require.Error(t, err)
require.Equal(t, "secret", mustRead(t, outside))
}
func mustRead(t *testing.T, name string) string {
t.Helper()
data, err := os.ReadFile(name)
require.NoError(t, err)
return string(data)
}
@@ -0,0 +1,86 @@
package fs
import (
"fmt"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"github.com/c4t-but-s4d/neo/v2/internal/server/common"
serverConfig "github.com/c4t-but-s4d/neo/v2/internal/server/config"
"github.com/c4t-but-s4d/neo/v2/internal/server/utils"
"github.com/c4t-but-s4d/neo/v2/pkg/filestream"
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
)
func New(cfg *serverConfig.Config) (*Server, error) {
fs, err := newOsFs(cfg.BaseDir)
if err != nil {
return nil, fmt.Errorf("создание файлового хранилища: %w", err)
}
ems := &Server{
LoggingServer: common.NewLoggingServer("fileserver"),
fs: fs,
}
return ems, nil
}
type Server struct {
fspb.UnimplementedServiceServer
common.LoggingServer
fs filesystem
}
func (s *Server) UploadFile(stream fspb.Service_UploadFileServer) (retErr error) {
info := &fspb.FileInfo{Uuid: uuid.NewString()}
s.GetMethodLogger(stream.Context()).Infof("New file upload: %v", info)
of, err := s.fs.Create(info.Uuid)
if err != nil {
return utils.WrapErrorf(codes.Internal, "Не удалось создать файл: %v", err)
}
defer func() {
if cerr := of.Close(); cerr != nil {
if retErr == nil {
retErr = utils.WrapErrorf(codes.Internal, "Не удалось закрыть файл назначения")
}
}
if retErr != nil {
if rerr := s.fs.Remove(info.Uuid); rerr != nil {
logrus.Errorf("Не удалось удалить незавершенную загрузку: %v", rerr)
}
}
}()
if err := filestream.SaveLimit(stream, of, filestream.MaxFileSize); err != nil {
return utils.WrapErrorf(codes.ResourceExhausted, "Не удалось принять файл из потока: %v", err)
}
if err := stream.SendAndClose(info); err != nil {
return utils.WrapErrorf(codes.Internal, "Не удалось отправить ответ и закрыть соединение: %v", err)
}
return nil
}
func (s *Server) DownloadFile(fi *fspb.FileInfo, stream fspb.Service_DownloadFileServer) error {
s.LogRequest(stream.Context(), fi)
if fi == nil {
return utils.WrapErrorf(codes.InvalidArgument, "Требуется идентификатор файла")
}
f, err := s.fs.Open(fi.Uuid)
if err != nil {
return utils.WrapErrorf(codes.NotFound, "Не удалось найти файл с uuid %s: %v", fi.Uuid, err)
}
defer func() {
if err := f.Close(); err != nil {
logrus.Errorf("Не удалось закрыть скачанный файл: %v", err)
}
}()
if err := filestream.Load(f, stream); err != nil {
return utils.WrapErrorf(codes.NotFound, "Не удалось найти файл с uuid %s: %v", fi.Uuid, err)
}
return nil
}
@@ -0,0 +1,72 @@
package server
import (
"fmt"
"strconv"
"github.com/mitchellh/mapstructure"
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
)
func NewLogLineFromValues(vals map[string]interface{}) (*LogLine, error) {
var line LogLine
if err := mapstructure.Decode(vals, &line); err != nil {
return nil, fmt.Errorf("разбор структуры строки журнала: %w", err)
}
return &line, nil
}
func NewLogLineFromProto(p *logspb.LogLine) *LogLine {
return &LogLine{
Exploit: p.Exploit,
Version: strconv.FormatInt(p.Version, 10),
Message: p.Message,
Level: p.Level,
Team: p.Team,
}
}
type LogLine struct {
Exploit string `mapstructure:"exploit"`
Version string `mapstructure:"version"`
Message string `mapstructure:"message"`
Level string `mapstructure:"level"`
Team string `mapstructure:"team"`
}
func (l *LogLine) String() string {
return fmt.Sprintf("Line(%s.v%s)", l.Exploit, l.Version)
}
func (l *LogLine) DumpValues() (map[string]interface{}, error) {
res := make(map[string]interface{})
if err := mapstructure.Decode(l, &res); err != nil {
return nil, fmt.Errorf("кодирование структуры строки журнала: %w", err)
}
return res, nil
}
func (l *LogLine) EstimateSize() int {
const (
estNum = 5
estDenom = 4
structSize = 8 * 5
)
sizeEst := structSize + len(l.Exploit) + len(l.Version) + len(l.Message) + len(l.Level) + len(l.Team)
return sizeEst * estNum / estDenom
}
func (l *LogLine) ToProto() (*logspb.LogLine, error) {
version, err := strconv.ParseInt(l.Version, 10, 64)
if err != nil {
return nil, fmt.Errorf("преобразование версии %v: %w", l.Version, err)
}
return &logspb.LogLine{
Exploit: l.Exploit,
Version: version,
Message: l.Message,
Level: l.Level,
Team: l.Team,
}, nil
}
@@ -0,0 +1,93 @@
package server
import (
"context"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/c4t-but-s4d/neo/v2/internal/server/common"
"github.com/c4t-but-s4d/neo/v2/internal/server/utils"
"github.com/c4t-but-s4d/neo/v2/pkg/gstream"
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
)
const (
logLinesBatchSize = 100
maxMsgSize = 4 * 1024 * 1024
)
func New(storage *LogStorage) *Server {
return &Server{
LoggingServer: common.NewLoggingServer("logs"),
storage: storage,
}
}
type Server struct {
logspb.UnimplementedServiceServer
common.LoggingServer
storage *LogStorage
}
func (s *Server) AddLogLines(ctx context.Context, lines *logspb.AddLogLinesRequest) (*emptypb.Empty, error) {
s.GetMethodLogger(ctx).Infof("New request with %d lines", len(lines.Lines))
decoded := make([]LogLine, 0, len(lines.Lines))
for _, line := range lines.Lines {
decoded = append(decoded, *NewLogLineFromProto(line))
}
if err := s.storage.Add(ctx, decoded); err != nil {
return nil, utils.WrapErrorf(codes.Internal, "добавление строк журнала: %v", err)
}
return &emptypb.Empty{}, nil
}
func (s *Server) SearchLogLines(req *logspb.SearchLogLinesRequest, stream logspb.Service_SearchLogLinesServer) error {
s.LogRequest(stream.Context(), req)
opts := GetOptions{
Exploit: req.Exploit,
Version: req.Version,
}
lines, err := s.storage.Get(stream.Context(), opts)
if err != nil {
return utils.WrapErrorf(codes.Internal, "поиск строк журнала: %v", err)
}
cache := gstream.NewDynamicSizeCache[*LogLine, logspb.SearchLogLinesResponse](
stream,
maxMsgSize,
func(lines []*LogLine) (*logspb.SearchLogLinesResponse, error) {
resp := &logspb.SearchLogLinesResponse{
Lines: make([]*logspb.LogLine, 0, len(lines)),
}
for _, line := range lines {
protoLine, err := line.ToProto()
if err != nil {
return nil, fmt.Errorf("преобразование строки журнала: %w", err)
}
resp.Lines = append(resp.Lines, protoLine)
}
return resp, nil
},
)
for i, line := range lines {
if err := cache.Queue(line); err != nil {
return utils.WrapErrorf(codes.Internal, "добавление строки журнала в очередь: %v", err)
}
if (i-1+logLinesBatchSize)%logLinesBatchSize == 0 {
if err := cache.Flush(); err != nil {
return utils.WrapErrorf(codes.Internal, "отправка накопленных строк: %v", err)
}
}
}
if err := cache.Flush(); err != nil {
return utils.WrapErrorf(codes.Internal, "отправка последних строк: %v", err)
}
return nil
}
@@ -0,0 +1,80 @@
package server
import (
"context"
"fmt"
"strconv"
"github.com/redis/go-redis/v9"
)
const (
linesPerSploitLimit = 100000
)
func NewLogStorage(ctx context.Context, redisURL string) (*LogStorage, error) {
opts, err := redis.ParseURL(redisURL)
if err != nil {
return nil, fmt.Errorf("неверный адрес Redis: %w", err)
}
c := redis.NewClient(opts)
if err := c.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("подключение к Redis: %w", err)
}
return &LogStorage{rdb: c}, nil
}
type LogStorage struct {
rdb *redis.Client
}
func (s *LogStorage) Add(ctx context.Context, lines []LogLine) error {
if _, err := s.rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for _, line := range lines {
key := getRedisStream(line.Exploit, line.Version)
vals, err := line.DumpValues()
if err != nil {
return fmt.Errorf("сериализация строки журнала: %w", err)
}
args := redis.XAddArgs{
Stream: key,
MaxLen: linesPerSploitLimit,
Approx: true,
Values: vals,
}
if err := pipe.XAdd(ctx, &args).Err(); err != nil {
return fmt.Errorf("добавление строки журнала: %w", err)
}
}
return nil
}); err != nil {
return fmt.Errorf("выполнение пакета команд Redis: %w", err)
}
return nil
}
func (s *LogStorage) Get(ctx context.Context, opts GetOptions) ([]*LogLine, error) {
key := getRedisStream(opts.Exploit, strconv.FormatInt(opts.Version, 10))
res, err := s.rdb.XRange(ctx, key, "-", "+").Result()
if err != nil {
return nil, fmt.Errorf("чтение потока %s: %w", key, err)
}
lines := make([]*LogLine, 0, len(res))
for _, msg := range res {
line, err := NewLogLineFromValues(msg.Values)
if err != nil {
return nil, fmt.Errorf("разбор строки журнала из Redis: %w", err)
}
lines = append(lines, line)
}
return lines, nil
}
type GetOptions struct {
Exploit string
Version int64
}
func getRedisStream(exploit string, version string) string {
return fmt.Sprintf("logs:%s:%s", exploit, version)
}
@@ -0,0 +1,13 @@
package utils
import (
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func WrapErrorf(code codes.Code, fmt string, values ...interface{}) error {
err := status.Errorf(code, fmt, values...)
logrus.Errorf("%v", err)
return err // nolint
}