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

+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"
}