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

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