feat: build wahrwelt A/D toolkit
This commit is contained in:
1 parent
303438d206
commit
653924d8c6
564 files changed
+36310
-49998
No files matched your search
@@ -0,0 +1,203 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type addCLI struct {
|
||||
*baseCLI
|
||||
path string
|
||||
isArchive bool
|
||||
exploitID string
|
||||
runEvery time.Duration
|
||||
timeout time.Duration
|
||||
endless bool
|
||||
disabled bool
|
||||
yes bool
|
||||
}
|
||||
|
||||
func NewAdd(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
c := &addCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
path: args[0],
|
||||
}
|
||||
|
||||
var err error
|
||||
if c.exploitID, err = cmd.Flags().GetString("id"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать идентификатор эксплойта: %v", err)
|
||||
}
|
||||
if c.isArchive, err = cmd.Flags().GetBool("dir"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр каталога: %v", err)
|
||||
}
|
||||
if c.runEvery, err = cmd.Flags().GetDuration("interval"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать интервал запуска: %v", err)
|
||||
}
|
||||
if c.timeout, err = cmd.Flags().GetDuration("timeout"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать тайм-аут запуска: %v", err)
|
||||
}
|
||||
if c.endless, err = cmd.Flags().GetBool("endless"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр бесконечного режима: %v", err)
|
||||
}
|
||||
if c.disabled, err = cmd.Flags().GetBool("disabled"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр отключения: %v", err)
|
||||
}
|
||||
if c.yes, err = cmd.Flags().GetBool("yes"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр --yes: %v", err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (ac *addCLI) Run(ctx context.Context) error {
|
||||
_, err := os.Stat(ac.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось проверить файл %s: %w", ac.path, err)
|
||||
}
|
||||
// Заменить путь на абсолютный.
|
||||
if ac.path, err = filepath.Abs(ac.path); err != nil {
|
||||
return fmt.Errorf("не удалось получить абсолютный путь: %w", err)
|
||||
}
|
||||
|
||||
if errs := ac.validateEntry(ac.path); len(errs) > 0 {
|
||||
for _, v := range errs {
|
||||
logrus.Errorf("%v", v)
|
||||
}
|
||||
return errors.New("эксплойт некорректен")
|
||||
}
|
||||
|
||||
dir, file := path.Split(ac.path)
|
||||
if ac.exploitID == "" {
|
||||
ac.exploitID = file
|
||||
}
|
||||
logrus.Infof("Добавление эксплойта с id = %s", ac.exploitID)
|
||||
|
||||
c, err := ac.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
|
||||
if getExploitFromState(state, ac.exploitID) != nil {
|
||||
confirmed, err := confirmNewVersion(os.Stdin, os.Stdout, ac.yes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось прочитать ответ: %w", err)
|
||||
}
|
||||
if !confirmed {
|
||||
logrus.Fatal("Операция отменена")
|
||||
}
|
||||
}
|
||||
|
||||
var f *os.File
|
||||
if ac.isArchive {
|
||||
f, err = os.CreateTemp("", "ARCHIVE")
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать временный файл: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = os.Remove(f.Name())
|
||||
}()
|
||||
if err := archive.Tar(dir, f); err != nil {
|
||||
return fmt.Errorf("не удалось создать архив tar.gz: %w", err)
|
||||
}
|
||||
|
||||
// Переместить указатель в начало файла перед чтением.
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("не удалось переместить указатель в архиве: %w", err)
|
||||
}
|
||||
} else {
|
||||
f, err = os.Open(ac.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось открыть файл эксплойта: %w", err)
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
fileInfo, err := c.UploadFile(ctx, f)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось загрузить файл эксплойта: %w", err)
|
||||
}
|
||||
|
||||
exState := &epb.ExploitState{
|
||||
ExploitId: ac.exploitID,
|
||||
File: fileInfo,
|
||||
Config: &epb.ExploitConfiguration{
|
||||
Entrypoint: file,
|
||||
IsArchive: ac.isArchive,
|
||||
RunEvery: durationpb.New(ac.runEvery),
|
||||
Timeout: durationpb.New(ac.timeout),
|
||||
Endless: ac.endless,
|
||||
Disabled: ac.disabled,
|
||||
},
|
||||
}
|
||||
newState, err := c.UpdateExploit(ctx, exState)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось обновить эксплойт: %w", err)
|
||||
}
|
||||
logrus.Infof("Эксплойт %s обновлен до версии %d", newState.GetExploitId(), newState.GetVersion())
|
||||
return nil
|
||||
}
|
||||
|
||||
func confirmNewVersion(input io.Reader, output io.Writer, assumeYes bool) (bool, error) {
|
||||
if assumeYes {
|
||||
return true, nil
|
||||
}
|
||||
if _, err := fmt.Fprintln(output, "Эксплойт с таким id уже есть. Добавить новую версию? да/нет"); err != nil {
|
||||
return false, fmt.Errorf("не удалось показать запрос подтверждения: %w", err)
|
||||
}
|
||||
var response string
|
||||
if _, err := fmt.Fscanln(input, &response); err != nil {
|
||||
return false, err
|
||||
}
|
||||
answer := strings.ToLower(strings.TrimSpace(response))
|
||||
return answer == "y" || answer == "yes" || answer == "д" || answer == "да", nil
|
||||
}
|
||||
|
||||
func (ac *addCLI) validateEntry(f string) (errors []string) {
|
||||
data, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
errors = append(errors, err.Error())
|
||||
return
|
||||
}
|
||||
if !isBinary(data) {
|
||||
if !bytes.HasPrefix(data, []byte("#!")) {
|
||||
desc := fmt.Sprintf(
|
||||
"Добавьте в первую строку скрипта shebang, например %s",
|
||||
"#!/usr/bin/env python3",
|
||||
)
|
||||
errors = append(errors, desc)
|
||||
}
|
||||
|
||||
// Для Python задана переменная PYTHONUNBUFFERED=1, поэтому принудительный сброс не нужен.
|
||||
if !bytes.Contains(data, []byte("#!/usr/bin/env python")) {
|
||||
re := regexp.MustCompile(`(?m)flush[(=]`)
|
||||
if !re.Match(data) {
|
||||
desc := "Сбрасывайте вывод явно, например print(..., flush=True) в Python"
|
||||
errors = append(errors, desc)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
func TestValidateEntryHandlesShortFiles(t *testing.T) {
|
||||
for _, content := range []string{"", "#", "#!"} {
|
||||
t.Run(content, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "short-script")
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0600))
|
||||
require.NotPanics(t, func() {
|
||||
require.NotEmpty(t, (&addCLI{}).validateEntry(path))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmNewVersionWithYesDoesNotPromptOrReadInput(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
confirmed, err := confirmNewVersion(strings.NewReader(""), &output, true)
|
||||
require.NoError(t, err)
|
||||
require.True(t, confirmed)
|
||||
require.Empty(t, output.String())
|
||||
}
|
||||
|
||||
func TestConfirmNewVersionKeepsInteractivePrompt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
confirmed bool
|
||||
}{
|
||||
{name: "английское да", input: "y\n", confirmed: true},
|
||||
{name: "английское yes", input: "YES\n", confirmed: true},
|
||||
{name: "русская буква", input: "д\n", confirmed: true},
|
||||
{name: "русское да", input: "Да\n", confirmed: true},
|
||||
{name: "отказ", input: "нет\n", confirmed: false},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
confirmed, err := confirmNewVersion(strings.NewReader(test.input), &output, false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.confirmed, confirmed)
|
||||
require.Contains(t, output.String(), "Добавить новую версию? да/нет")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmNewVersionReturnsEOFWithoutAssumingYes(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
confirmed, err := confirmNewVersion(strings.NewReader(""), &output, false)
|
||||
require.ErrorIs(t, err, io.EOF)
|
||||
require.False(t, confirmed)
|
||||
require.Contains(t, output.String(), "Добавить новую версию? да/нет")
|
||||
}
|
||||
|
||||
func TestNewAddReadsYesFlag(t *testing.T) {
|
||||
command := &cobra.Command{}
|
||||
command.Flags().String("id", "", "")
|
||||
command.Flags().Bool("dir", false, "")
|
||||
command.Flags().Duration("interval", 0, "")
|
||||
command.Flags().Duration("timeout", 0, "")
|
||||
command.Flags().Bool("endless", false, "")
|
||||
command.Flags().Bool("disabled", false, "")
|
||||
command.Flags().Bool("yes", true, "")
|
||||
|
||||
result := NewAdd(command, []string{"job.py"}, &client.Config{})
|
||||
add, ok := result.(*addCLI)
|
||||
require.True(t, ok)
|
||||
require.True(t, add.yes)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
type broadcastCLI struct {
|
||||
*baseCLI
|
||||
cmd string
|
||||
}
|
||||
|
||||
func NewBroadcast(cmd *cobra.Command, _ []string, cfg *client.Config) NeoCLI {
|
||||
command, err := cmd.Flags().GetString("command")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать команду: %v", err)
|
||||
}
|
||||
return &broadcastCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
cmd: command,
|
||||
}
|
||||
}
|
||||
|
||||
func (bc *broadcastCLI) Run(ctx context.Context) error {
|
||||
logrus.Info("Отправка команды всем подключенным клиентам")
|
||||
c, err := bc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
if err := c.BroadcastCommand(ctx, bc.cmd); err != nil {
|
||||
return fmt.Errorf("не удалось отправить широковещательную команду: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/denisbrodbeck/machineid"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/viper"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/encoding/gzip"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/grpcauth"
|
||||
)
|
||||
|
||||
type NeoCLI interface {
|
||||
Run(ctx context.Context) error
|
||||
}
|
||||
|
||||
type baseCLI struct {
|
||||
cfg *client.Config
|
||||
|
||||
clientID string
|
||||
}
|
||||
|
||||
func (cmd *baseCLI) client() (*client.Client, error) {
|
||||
if err := grpcauth.ValidateKey(cmd.cfg.GrpcAuthKey); err != nil {
|
||||
return nil, fmt.Errorf("неверный ключ gRPC: %w", err)
|
||||
}
|
||||
opts := []grpc.DialOption{
|
||||
grpc.WithDefaultCallOptions(
|
||||
grpc.UseCompressor(gzip.Name),
|
||||
),
|
||||
}
|
||||
interceptor := grpcauth.NewClientInterceptor(cmd.cfg.GrpcAuthKey)
|
||||
opts = append(
|
||||
opts,
|
||||
grpc.WithUnaryInterceptor(interceptor.Unary()),
|
||||
grpc.WithStreamInterceptor(interceptor.Stream()),
|
||||
)
|
||||
if !cmd.cfg.UseTLS {
|
||||
opts = append(
|
||||
opts,
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
)
|
||||
} else {
|
||||
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))
|
||||
}
|
||||
conn, err := grpc.Dial(cmd.cfg.Host, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("не удалось подключиться к gRPC-серверу: %w", err)
|
||||
}
|
||||
return client.New(conn, cmd.ClientID()), nil
|
||||
}
|
||||
|
||||
func (cmd *baseCLI) ClientID() string {
|
||||
if cmd.clientID != "" {
|
||||
return cmd.clientID
|
||||
}
|
||||
|
||||
cmd.clientID = viper.GetString("client_id")
|
||||
if cmd.clientID == "" {
|
||||
var err error
|
||||
if cmd.clientID, err = machineid.ID(); err != nil {
|
||||
logrus.Fatalf("Не удалось получить уникальный идентификатор клиента: %v", err)
|
||||
}
|
||||
}
|
||||
logrus.Infof("Идентификатор клиента: %s", cmd.clientID)
|
||||
return cmd.clientID
|
||||
}
|
||||
|
||||
func (cmd *baseCLI) Run(_ context.Context) error {
|
||||
return errors.New("команда не реализована")
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"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/exploit"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/queue"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
|
||||
)
|
||||
|
||||
type dryRunCLI struct {
|
||||
*baseCLI
|
||||
jobs int
|
||||
exploitID string
|
||||
teamID string
|
||||
teamIP string
|
||||
}
|
||||
|
||||
func NewDryRun(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
cfg.ExploitDir = path.Join(cfg.ExploitDir, "dry")
|
||||
if err := os.MkdirAll(cfg.ExploitDir, os.ModePerm); err != nil {
|
||||
logrus.Fatalf("Не удалось создать каталог для локального запуска %v: %v", cfg.ExploitDir, err)
|
||||
}
|
||||
|
||||
cli := &dryRunCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
jobs: parseJobsFlag(cmd, "jobs"),
|
||||
}
|
||||
cli.teamID, _ = cmd.Flags().GetString("team_id")
|
||||
cli.teamIP, _ = cmd.Flags().GetString("team_ip")
|
||||
return cli
|
||||
}
|
||||
|
||||
func (rc *dryRunCLI) Run(ctx context.Context) error {
|
||||
c, err := rc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
cfg, err := config.FromProto(state.Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось разобрать конфигурацию: %w", err)
|
||||
}
|
||||
|
||||
if getExploitFromState(state, rc.exploitID) == nil {
|
||||
return fmt.Errorf("эксплойт %s не найден, сначала добавьте его", rc.exploitID)
|
||||
}
|
||||
|
||||
storage := exploit.NewStorage(exploit.NewCache(), rc.baseCLI.cfg.ExploitDir, c)
|
||||
storage.UpdateExploits(ctx, state.Exploits)
|
||||
ex, ok := storage.Exploit(rc.exploitID)
|
||||
if !ok {
|
||||
return fmt.Errorf("эксплойт %s не найден в хранилище", rc.exploitID)
|
||||
}
|
||||
|
||||
allTeams := make(map[string]string)
|
||||
for _, tbuck := range state.ClientTeamMap {
|
||||
for k, v := range tbuck.Teams {
|
||||
allTeams[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
sender := joblogger.NewDummySender()
|
||||
|
||||
var tasks []*queue.Job
|
||||
if rc.teamIP == "" && rc.teamID == "" {
|
||||
tasks = exploit.CreateExploitJobs(ex, allTeams, cfg.Environ, sender)
|
||||
} else {
|
||||
oneTeamMap := make(map[string]string)
|
||||
for k, v := range allTeams {
|
||||
if k == rc.teamID || v == rc.teamIP {
|
||||
oneTeamMap[k] = v
|
||||
}
|
||||
}
|
||||
tasks = exploit.CreateExploitJobs(ex, oneTeamMap, cfg.Environ, sender)
|
||||
}
|
||||
|
||||
var q queue.Queue
|
||||
if ex.Endless {
|
||||
q = queue.NewEndlessQueue(rc.jobs)
|
||||
} else {
|
||||
q = queue.NewSimpleQueue(rc.jobs)
|
||||
}
|
||||
|
||||
runCtx, runCancel := context.WithCancel(ctx)
|
||||
defer runCancel()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
defer wg.Wait()
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
q.Start(runCtx)
|
||||
logrus.Info("Очередь завершена")
|
||||
}()
|
||||
|
||||
for _, t := range tasks {
|
||||
if err := q.Add(t); err != nil {
|
||||
logrus.Errorf("Не удалось добавить эксплойт %s для цели %s в очередь: %v", t.Exploit.ID, t.Target.IP, err)
|
||||
}
|
||||
}
|
||||
|
||||
tasksDone := 0
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case res, ok := <-q.Results():
|
||||
if !ok || tasksDone+1 == len(tasks) && !ex.Endless {
|
||||
logrus.Info("Запуски завершены, ожидание остановки очереди")
|
||||
break loop
|
||||
}
|
||||
tasksDone++
|
||||
logrus.Infof("Цель = %v, вывод = %v", res.Target, string(res.Out))
|
||||
case <-ctx.Done():
|
||||
logrus.Info("Получен сигнал остановки")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/config"
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
)
|
||||
|
||||
type infoCLI struct {
|
||||
*baseCLI
|
||||
}
|
||||
|
||||
func NewInfo(_ *cobra.Command, _ []string, cfg *client.Config) NeoCLI {
|
||||
return &infoCLI{&baseCLI{cfg: cfg}}
|
||||
}
|
||||
|
||||
func (ic *infoCLI) Run(ctx context.Context) error {
|
||||
c, err := ic.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось запросить конфигурацию сервера: %w", err)
|
||||
}
|
||||
cfg, err := config.FromProto(state.Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось разобрать конфигурацию: %w", err)
|
||||
}
|
||||
fmt.Print(formatServerInfo(cfg, state))
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatServerInfo(cfg *config.ExploitsConfig, state *epb.ServerState) string {
|
||||
var out strings.Builder
|
||||
fmt.Fprintf(&out, "Farm: %s\n", cfg.FarmURL)
|
||||
fmt.Fprintf(&out, "Интервал опроса: %s\n", cfg.PingEvery)
|
||||
fmt.Fprintf(&out, "Интервал отправки флагов: %s\n", cfg.SubmitEvery)
|
||||
fmt.Fprintf(&out, "Правило флага: %s\n", cfg.FlagRegexp)
|
||||
fmt.Fprintf(&out, "Переменных окружения: %d\n", len(cfg.Environ))
|
||||
|
||||
fmt.Fprintln(&out, "Адреса команд:")
|
||||
bucketIDs := make([]string, 0, len(state.ClientTeamMap))
|
||||
for id := range state.ClientTeamMap {
|
||||
bucketIDs = append(bucketIDs, id)
|
||||
}
|
||||
sort.Strings(bucketIDs)
|
||||
for _, bucketID := range bucketIDs {
|
||||
bucket := state.ClientTeamMap[bucketID]
|
||||
teamIDs := make([]string, 0, len(bucket.GetTeams()))
|
||||
for id := range bucket.GetTeams() {
|
||||
teamIDs = append(teamIDs, id)
|
||||
}
|
||||
sort.Strings(teamIDs)
|
||||
for _, teamID := range teamIDs {
|
||||
fmt.Fprintf(&out, " %s: %s\n", teamID, bucket.GetTeams()[teamID])
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintln(&out, "Эксплойты:")
|
||||
for _, exploit := range state.Exploits {
|
||||
if exploit == nil {
|
||||
continue
|
||||
}
|
||||
cfg := exploit.GetConfig()
|
||||
fmt.Fprintf(&out, " %s, версия %d", exploit.GetExploitId(), exploit.GetVersion())
|
||||
if cfg != nil {
|
||||
fmt.Fprintf(&out, ", интервал %s, тайм-аут %s, бесконечный режим %t, отключен %t, точка входа %s",
|
||||
cfg.GetRunEvery().AsDuration(), cfg.GetTimeout().AsDuration(), cfg.GetEndless(), cfg.GetDisabled(), cfg.GetEntrypoint())
|
||||
}
|
||||
fmt.Fprintln(&out)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/config"
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
)
|
||||
|
||||
func TestFormatServerInfoOmitsSecrets(t *testing.T) {
|
||||
const secret = "farm-password-must-not-appear"
|
||||
cfg := &config.ExploitsConfig{
|
||||
FarmURL: "http://farm:5000",
|
||||
FarmPassword: secret,
|
||||
FlagRegexp: regexp.MustCompile(`FLAG\\{.*\\}`),
|
||||
PingEvery: time.Second * 5,
|
||||
SubmitEvery: time.Second * 2,
|
||||
Environ: []string{"TOKEN=environment-secret"},
|
||||
}
|
||||
state := &epb.ServerState{
|
||||
Config: &epb.Config{
|
||||
FarmPassword: secret,
|
||||
Environ: []string{"TOKEN=environment-secret"},
|
||||
},
|
||||
ClientTeamMap: map[string]*epb.TeamBucket{
|
||||
"worker": {Teams: map[string]string{"team-1": "127.0.0.1"}},
|
||||
},
|
||||
Exploits: []*epb.ExploitState{{
|
||||
ExploitId: "check",
|
||||
Version: 1,
|
||||
Config: &epb.ExploitConfiguration{
|
||||
Entrypoint: "check.py",
|
||||
RunEvery: durationpb.New(time.Second * 30),
|
||||
Timeout: durationpb.New(time.Second * 10),
|
||||
},
|
||||
}},
|
||||
}
|
||||
|
||||
output := formatServerInfo(cfg, state)
|
||||
require.NotContains(t, output, secret)
|
||||
require.NotContains(t, output, "environment-secret")
|
||||
require.Contains(t, output, "http://farm:5000")
|
||||
require.Contains(t, output, "team-1: 127.0.0.1")
|
||||
require.Contains(t, output, "check, версия 1")
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/exploit"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
|
||||
)
|
||||
|
||||
const JobsPerCPU = 5
|
||||
|
||||
type runCLI struct {
|
||||
*baseCLI
|
||||
run *exploit.Runner
|
||||
sender *joblogger.RemoteSender
|
||||
}
|
||||
|
||||
func parseJobsFlag(cmd *cobra.Command, name string) int {
|
||||
jobs, err := cmd.Flags().GetInt(name)
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать число заданий: %v", err)
|
||||
}
|
||||
if jobs < 0 {
|
||||
logrus.Fatal("run: число заданий не может быть отрицательным")
|
||||
}
|
||||
return jobs
|
||||
}
|
||||
|
||||
func NewRun(cmd *cobra.Command, _ []string, cfg *client.Config) NeoCLI {
|
||||
cli := &runCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
}
|
||||
neocli, err := cli.client()
|
||||
if err != nil {
|
||||
logrus.Fatalf("run: не удалось создать клиент: %v", err)
|
||||
}
|
||||
|
||||
jobs := parseJobsFlag(cmd, "jobs")
|
||||
endlessJobs := parseJobsFlag(cmd, "endless-jobs")
|
||||
timeoutScaleTarget, err := cmd.Flags().GetFloat64("timeout-autoscale-target")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр timeout-autoscale-target: %v", err)
|
||||
}
|
||||
if timeoutScaleTarget < 0 {
|
||||
logrus.Fatalf("timeout-autoscale-target не может быть отрицательным")
|
||||
}
|
||||
|
||||
neocli.Weight = jobs
|
||||
cli.sender = joblogger.NewRemoteSender(neocli)
|
||||
cli.run = exploit.NewRunner(
|
||||
cli.ClientID(),
|
||||
jobs,
|
||||
endlessJobs,
|
||||
timeoutScaleTarget,
|
||||
cfg,
|
||||
neocli,
|
||||
cli.sender,
|
||||
)
|
||||
|
||||
return cli
|
||||
}
|
||||
|
||||
func (rc *runCLI) Run(ctx context.Context) error {
|
||||
wg := sync.WaitGroup{}
|
||||
defer wg.Wait()
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
rc.sender.Start(ctx)
|
||||
logrus.Info("Отправка журналов завершена")
|
||||
}()
|
||||
|
||||
return rc.run.Run(ctx) // nolint:wrapcheck
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
type setDisabledCli struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
disabled bool
|
||||
}
|
||||
|
||||
func NewSetDisabled(_ *cobra.Command, args []string, cfg *client.Config, disabled bool) NeoCLI {
|
||||
return &setDisabledCli{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
disabled: disabled,
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *setDisabledCli) Run(ctx context.Context) error {
|
||||
c, err := sc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
|
||||
if spl := getExploitFromState(state, sc.exploitID); spl == nil {
|
||||
return fmt.Errorf("эксплойт %s не найден", sc.exploitID)
|
||||
} else if err := c.SetExploitDisabled(ctx, spl.ExploitId, sc.disabled); err != nil {
|
||||
return fmt.Errorf("не удалось изменить состояние эксплойта: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
type singleRunCLI struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
}
|
||||
|
||||
func NewSingleRun(_ *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
return &singleRunCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *singleRunCLI) Run(ctx context.Context) error {
|
||||
c, err := sc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
|
||||
if getExploitFromState(state, sc.exploitID) == nil {
|
||||
logrus.Fatalf("Эксплойт %s не найден. Сначала добавьте его.", sc.exploitID)
|
||||
}
|
||||
if err := c.SingleRun(ctx, sc.exploitID); err != nil {
|
||||
return fmt.Errorf("не удалось выполнить разовый запуск: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
|
||||
)
|
||||
|
||||
type tailCLI struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
version int64
|
||||
count int
|
||||
}
|
||||
|
||||
func NewTail(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
c := &tailCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
}
|
||||
|
||||
var err error
|
||||
if c.version, err = cmd.Flags().GetInt64("version"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать версию эксплойта: %v", err)
|
||||
}
|
||||
if c.count, err = cmd.Flags().GetInt("count"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать число строк: %v", err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (tc *tailCLI) Run(ctx context.Context) error {
|
||||
c, err := tc.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось запросить конфигурацию сервера: %w", err)
|
||||
}
|
||||
found := false
|
||||
for _, ex := range state.Exploits {
|
||||
if ex.ExploitId == tc.exploitID {
|
||||
found = true
|
||||
if tc.version == 0 {
|
||||
tc.version = ex.Version
|
||||
}
|
||||
if ex.Version > tc.version {
|
||||
return fmt.Errorf("запрошена более новая версия, текущая версия: %v", ex.Version)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("эксплойт %v версии %v не найден", tc.exploitID, tc.version)
|
||||
}
|
||||
|
||||
stream, err := c.SearchLogLines(ctx, tc.exploitID, tc.version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось запросить строки журнала: %w", err)
|
||||
}
|
||||
var lines []*logspb.LogLine
|
||||
for batch := range stream {
|
||||
lines = append(lines, batch...)
|
||||
}
|
||||
logrus.Debugf("Получено строк журнала: %d", len(lines))
|
||||
if tc.count != -1 && len(lines) > tc.count {
|
||||
lines = lines[len(lines)-tc.count:]
|
||||
}
|
||||
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
for _, line := range lines {
|
||||
logger := logrus.WithFields(logrus.Fields{
|
||||
"exploit": line.Exploit,
|
||||
"version": line.Version,
|
||||
"team": line.Team,
|
||||
})
|
||||
switch line.Level {
|
||||
case "debug":
|
||||
logger.Debug(line.Message)
|
||||
case "info":
|
||||
logger.Info(line.Message)
|
||||
case "warning":
|
||||
logger.Warning(line.Message)
|
||||
case "error":
|
||||
logger.Error(line.Message)
|
||||
default:
|
||||
logger.Warningf("Неизвестный уровень журнала: %v", line.Level)
|
||||
logger.Warning(line.Message)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/models"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/queue"
|
||||
)
|
||||
|
||||
const (
|
||||
testOutputLimit = 1 << 20
|
||||
testFileLimit = int64(512 << 20)
|
||||
testEntryLimit = 10_000
|
||||
testTimeoutCode = 124
|
||||
testCancelCode = 130
|
||||
testDirPrefix = ".neo-test-"
|
||||
)
|
||||
|
||||
// TestResult содержит ограниченный вывод локального запуска и найденные совпадения.
|
||||
type TestResult struct {
|
||||
Stdout []byte
|
||||
Stderr []byte
|
||||
StdoutTruncated bool
|
||||
StderrTruncated bool
|
||||
ExitCode int
|
||||
TimedOut bool
|
||||
Flags []string
|
||||
}
|
||||
|
||||
type limitedBuffer struct {
|
||||
buf bytes.Buffer
|
||||
limit int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (b *limitedBuffer) Write(p []byte) (int, error) {
|
||||
remaining := b.limit - b.buf.Len()
|
||||
if remaining > len(p) {
|
||||
remaining = len(p)
|
||||
}
|
||||
if remaining > 0 {
|
||||
if _, err := b.buf.Write(p[:remaining]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if remaining < len(p) {
|
||||
b.truncated = true
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (b *limitedBuffer) Bytes() []byte {
|
||||
return b.buf.Bytes()
|
||||
}
|
||||
|
||||
type copyLimits struct {
|
||||
entries int
|
||||
bytes int64
|
||||
}
|
||||
|
||||
func (limits *copyLimits) add(size int64) error {
|
||||
limits.entries++
|
||||
if limits.entries > testEntryLimit {
|
||||
return fmt.Errorf("в каталоге больше %d файлов и папок", testEntryLimit)
|
||||
}
|
||||
if size < 0 || size > testFileLimit-limits.bytes {
|
||||
return fmt.Errorf("данные превышают %d байт", testFileLimit)
|
||||
}
|
||||
limits.bytes += size
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunTest запускает локальную копию файла с адресом цели как единственным аргументом.
|
||||
func RunTest(ctx context.Context, file, host string, timeout time.Duration, flagPattern string, includeDir bool) (TestResult, error) {
|
||||
workDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
return TestResult{}, fmt.Errorf("не удалось получить рабочий каталог: %w", err)
|
||||
}
|
||||
return runTestAt(ctx, workDir, file, host, timeout, flagPattern, includeDir)
|
||||
}
|
||||
|
||||
func runTestAt(ctx context.Context, workDir, file, host string, timeout time.Duration, flagPattern string, includeDir bool) (result TestResult, returnErr error) {
|
||||
if host == "" {
|
||||
return result, errors.New("адрес цели не может быть пустым")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
return result, errors.New("тайм-аут должен быть больше нуля")
|
||||
}
|
||||
if flagPattern == "" {
|
||||
return result, errors.New("параметр --flag-regexp обязателен")
|
||||
}
|
||||
flagRegexp, err := regexp.Compile(flagPattern)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("неверное выражение --flag-regexp: %w", err)
|
||||
}
|
||||
|
||||
absoluteFile, err := filepath.Abs(file)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось получить путь к файлу: %w", err)
|
||||
}
|
||||
info, err := os.Lstat(absoluteFile)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось проверить файл %s: %w", absoluteFile, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return result, errors.New("файл задания должен быть обычным файлом, не ссылкой или каталогом")
|
||||
}
|
||||
resolvedFile, err := filepath.EvalSymlinks(absoluteFile)
|
||||
if err != nil || resolvedFile != absoluteFile {
|
||||
return result, errors.New("путь к файлу задания не должен проходить через символическую ссылку")
|
||||
}
|
||||
|
||||
absoluteWorkDir, err := filepath.Abs(workDir)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось определить рабочий каталог: %w", err)
|
||||
}
|
||||
workingCopy, err := os.MkdirTemp(absoluteWorkDir, testDirPrefix)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось создать рабочую копию в %s: %w", absoluteWorkDir, err)
|
||||
}
|
||||
defer func() {
|
||||
if err := os.RemoveAll(workingCopy); err != nil {
|
||||
returnErr = errors.Join(returnErr, fmt.Errorf("не удалось удалить временную копию: %w", err))
|
||||
}
|
||||
}()
|
||||
|
||||
entrypoint, err := copyTestInput(absoluteFile, workingCopy, includeDir)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось подготовить копию задания: %w", err)
|
||||
}
|
||||
|
||||
stdout := &limitedBuffer{limit: testOutputLimit}
|
||||
stderr := &limitedBuffer{limit: testOutputLimit}
|
||||
job := queue.NewJob(
|
||||
models.NewExploit("local-test", 1, models.ExploitTypeRecurrent),
|
||||
models.NewTarget("local-test", host),
|
||||
entrypoint,
|
||||
workingCopy,
|
||||
nil,
|
||||
timeout,
|
||||
nil,
|
||||
)
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
cmd := job.Command(runCtx)
|
||||
cmd.Stdout = stdout
|
||||
cmd.Stderr = stderr
|
||||
|
||||
runErr := cmd.Run()
|
||||
result.Stdout = stdout.Bytes()
|
||||
result.Stderr = stderr.Bytes()
|
||||
result.StdoutTruncated = stdout.truncated
|
||||
result.StderrTruncated = stderr.truncated
|
||||
switch {
|
||||
case runErr == nil:
|
||||
result.ExitCode = 0
|
||||
case errors.Is(runCtx.Err(), context.DeadlineExceeded):
|
||||
result.ExitCode = testTimeoutCode
|
||||
result.TimedOut = true
|
||||
case errors.Is(runCtx.Err(), context.Canceled):
|
||||
result.ExitCode = testCancelCode
|
||||
default:
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(runErr, &exitErr) {
|
||||
return result, fmt.Errorf("не удалось запустить задание: %w", runErr)
|
||||
}
|
||||
result.ExitCode = exitErr.ExitCode()
|
||||
if result.ExitCode < 0 {
|
||||
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() {
|
||||
result.ExitCode = 128 + int(status.Signal())
|
||||
} else {
|
||||
result.ExitCode = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
result.Flags = findFlags(flagRegexp, result.Stdout, result.Stderr)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func copyTestInput(sourceFile, destination string, includeDir bool) (string, error) {
|
||||
sourceDir := filepath.Dir(sourceFile)
|
||||
entrypoint, err := filepath.Rel(sourceDir, sourceFile)
|
||||
if err != nil || !filepath.IsLocal(entrypoint) {
|
||||
return "", errors.New("небезопасный путь к точке входа")
|
||||
}
|
||||
limits := ©Limits{}
|
||||
if !includeDir {
|
||||
destinationFile := filepath.Join(destination, entrypoint)
|
||||
if err := copyRegularFile(sourceFile, destinationFile, true, limits); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return destinationFile, nil
|
||||
}
|
||||
|
||||
rootInfo, err := os.Lstat(sourceDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("не удалось проверить каталог задания: %w", err)
|
||||
}
|
||||
if !rootInfo.IsDir() {
|
||||
return "", errors.New("родительская папка задания не является обычным каталогом")
|
||||
}
|
||||
resolvedRoot, err := filepath.EvalSymlinks(sourceDir)
|
||||
if err != nil || resolvedRoot != sourceDir {
|
||||
return "", errors.New("путь к папке задания не должен проходить через символическую ссылку")
|
||||
}
|
||||
|
||||
destinationAbs, err := filepath.Abs(destination)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("не удалось определить путь рабочей копии: %w", err)
|
||||
}
|
||||
foundEntrypoint := false
|
||||
err = filepath.WalkDir(sourceDir, func(path string, entry os.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if filepath.Clean(path) == filepath.Clean(destinationAbs) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if filepath.Clean(path) == filepath.Clean(sourceDir) {
|
||||
return nil
|
||||
}
|
||||
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("символическая ссылка запрещена: %s", entry.Name())
|
||||
}
|
||||
relative, err := filepath.Rel(sourceDir, path)
|
||||
if err != nil || !filepath.IsLocal(relative) {
|
||||
return fmt.Errorf("небезопасный путь в папке задания: %s", entry.Name())
|
||||
}
|
||||
target := filepath.Join(destinationAbs, relative)
|
||||
if info.IsDir() {
|
||||
if err := limits.add(0); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Mkdir(target, 0700)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("специальный файл запрещен: %s", entry.Name())
|
||||
}
|
||||
if err := copyRegularFile(path, target, filepath.Clean(path) == filepath.Clean(sourceFile), limits); err != nil {
|
||||
return err
|
||||
}
|
||||
if filepath.Clean(path) == filepath.Clean(sourceFile) {
|
||||
foundEntrypoint = true
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("обход каталога задания: %w", err)
|
||||
}
|
||||
if !foundEntrypoint {
|
||||
return "", errors.New("точка входа не найдена в родительской папке")
|
||||
}
|
||||
return filepath.Join(destinationAbs, entrypoint), nil
|
||||
}
|
||||
|
||||
func copyRegularFile(source, destination string, entrypoint bool, limits *copyLimits) error {
|
||||
info, err := os.Lstat(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось проверить файл %s: %w", filepath.Base(source), err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("обнаружен не обычный файл: %s", filepath.Base(source))
|
||||
}
|
||||
if err := limits.add(info.Size()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
|
||||
return fmt.Errorf("не удалось создать папку рабочей копии: %w", err)
|
||||
}
|
||||
|
||||
src, err := os.Open(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось открыть файл %s: %w", filepath.Base(source), err)
|
||||
}
|
||||
srcInfo, err := src.Stat()
|
||||
if err != nil || !os.SameFile(info, srcInfo) || !srcInfo.Mode().IsRegular() {
|
||||
_ = src.Close()
|
||||
return fmt.Errorf("файл изменился при копировании: %s", filepath.Base(source))
|
||||
}
|
||||
dst, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
_ = src.Close()
|
||||
return fmt.Errorf("не удалось создать файл рабочей копии: %w", err)
|
||||
}
|
||||
_, copyErr := io.CopyN(dst, src, info.Size())
|
||||
if copyErr == nil {
|
||||
var extra [1]byte
|
||||
if n, readErr := src.Read(extra[:]); n != 0 || !errors.Is(readErr, io.EOF) {
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
copyErr = readErr
|
||||
} else {
|
||||
copyErr = errors.New("размер файла изменился при копировании")
|
||||
}
|
||||
}
|
||||
}
|
||||
closeSourceErr := src.Close()
|
||||
closeDestinationErr := dst.Close()
|
||||
if copyErr != nil || closeSourceErr != nil || closeDestinationErr != nil {
|
||||
_ = os.Remove(destination)
|
||||
return errors.Join(copyErr, closeSourceErr, closeDestinationErr)
|
||||
}
|
||||
mode := os.FileMode(0600)
|
||||
if entrypoint || info.Mode().Perm()&0100 != 0 {
|
||||
mode |= 0100
|
||||
}
|
||||
if err := os.Chmod(destination, mode); err != nil {
|
||||
_ = os.Remove(destination)
|
||||
return fmt.Errorf("не удалось подготовить права файла: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findFlags(flagRegexp *regexp.Regexp, streams ...[]byte) []string {
|
||||
seen := make(map[string]struct{})
|
||||
var flags []string
|
||||
for _, stream := range streams {
|
||||
for _, match := range flagRegexp.FindAll(stream, -1) {
|
||||
flag := string(match)
|
||||
if flag == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[flag]; exists {
|
||||
continue
|
||||
}
|
||||
seen[flag] = struct{}{}
|
||||
flags = append(flags, flag)
|
||||
}
|
||||
}
|
||||
return flags
|
||||
}
|
||||
|
||||
// WriteTo показывает оба потока отдельно, код завершения и уникальные совпадения.
|
||||
func (result TestResult) WriteTo(stdout, stderr io.Writer) error {
|
||||
if _, err := fmt.Fprintln(stdout, "stdout:"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeOutput(stdout, result.Stdout, result.StdoutTruncated, "stdout"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintln(stderr, "stderr:"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeOutput(stderr, result.Stderr, result.StderrTruncated, "stderr"); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.TimedOut {
|
||||
if _, err := fmt.Fprintln(stdout, "тайм-аут: истекло время ожидания"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := fmt.Fprintf(stdout, "код выхода: %d\nфлаги:\n", result.ExitCode); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, flag := range result.Flags {
|
||||
if _, err := fmt.Fprintf(stdout, " %s\n", flag); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeOutput(dst io.Writer, output []byte, truncated bool, stream string) error {
|
||||
if len(output) > 0 {
|
||||
if _, err := dst.Write(output); err != nil {
|
||||
return err
|
||||
}
|
||||
if output[len(output)-1] != '\n' {
|
||||
if _, err := fmt.Fprintln(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
_, err := fmt.Fprintf(dst, "[вывод %s обрезан после 1 МиБ]\n", stream)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunTestCapturesStreamsExitCodeFlagsAndFiltersSecrets(t *testing.T) {
|
||||
secrets := []string{"NEO_GRPC_AUTH_KEY", "NEO_WORKER_KEY", "NEO_KEY", "GRPC_AUTH_KEY", "FARM_PASSWORD", "NEO_FARM_PASSWORD"}
|
||||
for _, name := range secrets {
|
||||
t.Setenv(name, "test-secret-"+name)
|
||||
}
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, "#!/bin/sh\nprintf 'stdout: ABC123=\\n'\nprintf 'stderr: ABC123= DEF456=\\n' >&2\n"+
|
||||
"printf 'credentials=%s|%s|%s|%s|%s|%s\\n' \"${NEO_GRPC_AUTH_KEY-unset}\" \"${NEO_WORKER_KEY-unset}\" \"${NEO_KEY-unset}\" \"${GRPC_AUTH_KEY-unset}\" \"${FARM_PASSWORD-unset}\" \"${NEO_FARM_PASSWORD-unset}\" >&2\nexit 7\n")
|
||||
|
||||
result, err := runTestAt(context.Background(), work, file, "192.0.2.10", time.Second, `[A-Z0-9]{6}=`, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка локального запуска: %v", err)
|
||||
}
|
||||
if result.ExitCode != 7 {
|
||||
t.Fatalf("код выхода = %d, ожидался 7", result.ExitCode)
|
||||
}
|
||||
if got := string(result.Stdout); got != "stdout: ABC123=\n" {
|
||||
t.Fatalf("stdout = %q", got)
|
||||
}
|
||||
if got := string(result.Stderr); !strings.Contains(got, "stderr: ABC123= DEF456=") || !strings.Contains(got, "credentials=unset|unset|unset|unset|unset|unset") {
|
||||
t.Fatalf("stderr = %q", got)
|
||||
}
|
||||
for _, name := range secrets {
|
||||
if strings.Contains(string(result.Stderr), "test-secret-"+name) {
|
||||
t.Fatalf("секрет %s попал в окружение запускаемого задания", name)
|
||||
}
|
||||
}
|
||||
if got, want := strings.Join(result.Flags, ","), "ABC123=,DEF456="; got != want {
|
||||
t.Fatalf("флаги = %q, ожидались %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestCopiesSiblingFilesForWritesAndCleansUp(t *testing.T) {
|
||||
stage := t.TempDir()
|
||||
work := t.TempDir()
|
||||
file := filepath.Join(stage, "job.sh")
|
||||
if err := os.WriteFile(file, []byte("#!/bin/sh\nset -eu\ncat resource.txt\nprintf 'host=%s\\n' \"$1\"\nprintf 'created\\n' > result.txt\nprintf 'FLAG123=\\n'\n"), 0444); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource := filepath.Join(stage, "resource.txt")
|
||||
if err := os.WriteFile(resource, []byte("sibling resource\n"), 0444); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := runTestAt(context.Background(), work, file, "target.example", time.Second, `FLAG[0-9]+=`, true)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка запуска копии папки: %v", err)
|
||||
}
|
||||
if result.ExitCode != 0 {
|
||||
t.Fatalf("код выхода = %d, ожидался 0; stderr = %q", result.ExitCode, result.Stderr)
|
||||
}
|
||||
if got, want := string(result.Stdout), "sibling resource\nhost=target.example\nFLAG123=\n"; got != want {
|
||||
t.Fatalf("stdout = %q, ожидалось %q", got, want)
|
||||
}
|
||||
if got, want := strings.Join(result.Flags, ","), "FLAG123="; got != want {
|
||||
t.Fatalf("найденные флаги = %q, ожидался %q", got, want)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(stage, "result.txt")); !os.IsNotExist(err) {
|
||||
t.Fatalf("исходная папка изменена: stat result.txt = %v", err)
|
||||
}
|
||||
entries, err := os.ReadDir(work)
|
||||
if err != nil {
|
||||
t.Fatalf("не удалось проверить очистку рабочей папки: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("временная копия осталась после запуска: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestTimeoutUses124(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, "#!/bin/sh\nsleep 5 &\nwait\n")
|
||||
|
||||
started := time.Now()
|
||||
result, err := runTestAt(context.Background(), work, file, "target", 50*time.Millisecond, `FLAG[0-9]+=`, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка локального запуска: %v", err)
|
||||
}
|
||||
if result.ExitCode != testTimeoutCode || !result.TimedOut {
|
||||
t.Fatalf("результат {код:%d тайм-аут:%t}, ожидался тайм-аут 124", result.ExitCode, result.TimedOut)
|
||||
}
|
||||
if time.Since(started) > 2*time.Second {
|
||||
t.Fatal("дочерний процесс не остановился после тайм-аута")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestCapsEachOutputStream(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, fmt.Sprintf("#!/bin/sh\nhead -c %d /dev/zero | tr '\\000' x\nhead -c %d /dev/zero | tr '\\000' y >&2\n", testOutputLimit+1, testOutputLimit+1))
|
||||
|
||||
result, err := runTestAt(context.Background(), work, file, "target", 5*time.Second, `FLAG[0-9]+=`, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка локального запуска: %v", err)
|
||||
}
|
||||
if len(result.Stdout) != testOutputLimit || len(result.Stderr) != testOutputLimit {
|
||||
t.Fatalf("длины вывода = (%d, %d), обрезан = (%t, %t), ожидалось по %d байт", len(result.Stdout), len(result.Stderr), result.StdoutTruncated, result.StderrTruncated, testOutputLimit)
|
||||
}
|
||||
if !result.StdoutTruncated || !result.StderrTruncated {
|
||||
t.Fatal("оба потока должны иметь отметку об обрезке")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestRejectsInvalidInputs(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, "#!/bin/sh\nexit 0\n")
|
||||
tests := []struct {
|
||||
name string
|
||||
file string
|
||||
host string
|
||||
timeout time.Duration
|
||||
pattern string
|
||||
}{
|
||||
{name: "пустой адрес", file: file, timeout: time.Second, pattern: `FLAG[0-9]+=`},
|
||||
{name: "неположительный тайм-аут", file: file, host: "target", pattern: `FLAG[0-9]+=`},
|
||||
{name: "нет выражения флага", file: file, host: "target", timeout: time.Second},
|
||||
{name: "неверное выражение", file: file, host: "target", timeout: time.Second, pattern: "["},
|
||||
{name: "нет файла", file: filepath.Join(t.TempDir(), "missing"), host: "target", timeout: time.Second, pattern: `FLAG[0-9]+=`},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := runTestAt(context.Background(), work, test.file, test.host, test.timeout, test.pattern, false); err == nil {
|
||||
t.Fatal("ошибка проверки входных данных отсутствует")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestRejectsSymlinksAndSpecialFiles(t *testing.T) {
|
||||
for _, kind := range []string{"символическая ссылка", "FIFO"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
stage := t.TempDir()
|
||||
work := t.TempDir()
|
||||
file := filepath.Join(stage, "job.sh")
|
||||
if err := os.WriteFile(file, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch kind {
|
||||
case "символическая ссылка":
|
||||
if err := os.Symlink("job.sh", filepath.Join(stage, "linked.sh")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "FIFO":
|
||||
if err := syscall.Mkfifo(filepath.Join(stage, "pipe"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := runTestAt(context.Background(), work, file, "target", time.Second, `FLAG[0-9]+=`, true); err == nil {
|
||||
t.Fatal("опасный файл должен отклоняться")
|
||||
}
|
||||
entries, err := os.ReadDir(work)
|
||||
if err != nil {
|
||||
t.Fatalf("не удалось проверить очистку: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("временная копия осталась после ошибки: %v", entries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyLimitsBoundTotalBytesAndEntries(t *testing.T) {
|
||||
var limits copyLimits
|
||||
if err := limits.add(testFileLimit); err != nil {
|
||||
t.Fatalf("допустимый предел байтов отклонен: %v", err)
|
||||
}
|
||||
if err := limits.add(1); err == nil {
|
||||
t.Fatal("превышение предела байтов не обнаружено")
|
||||
}
|
||||
|
||||
limits = copyLimits{}
|
||||
for i := 0; i < testEntryLimit; i++ {
|
||||
if err := limits.add(0); err != nil {
|
||||
t.Fatalf("допустимое число записей отклонено: %v", err)
|
||||
}
|
||||
}
|
||||
if err := limits.add(0); err == nil {
|
||||
t.Fatal("превышение предела записей не обнаружено")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitedBufferKeepsDrainingAfterLimit(t *testing.T) {
|
||||
buffer := &limitedBuffer{limit: testOutputLimit}
|
||||
data := make([]byte, testOutputLimit+1)
|
||||
if n, err := buffer.Write(data); err != nil || n != len(data) {
|
||||
t.Fatalf("Write() = (%d, %v), ожидалось (%d, nil)", n, err, len(data))
|
||||
}
|
||||
if buffer.buf.Len() != testOutputLimit || !buffer.truncated {
|
||||
t.Fatalf("длина буфера = %d, обрезан = %t", buffer.buf.Len(), buffer.truncated)
|
||||
}
|
||||
}
|
||||
|
||||
func writeTestProgram(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
file := filepath.Join(t.TempDir(), "job.sh")
|
||||
if err := os.WriteFile(file, []byte(content), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return file
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/samber/lo"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"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"
|
||||
)
|
||||
|
||||
type updateCLI struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
runEvery *time.Duration
|
||||
timeout *time.Duration
|
||||
endless *bool
|
||||
disabled *bool
|
||||
}
|
||||
|
||||
func NewUpdateCLI(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
c := &updateCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
}
|
||||
|
||||
if cmd.Flags().Changed("interval") {
|
||||
runEvery, err := cmd.Flags().GetDuration("interval")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать интервал запуска: %v", err)
|
||||
}
|
||||
c.runEvery = &runEvery
|
||||
}
|
||||
if cmd.Flags().Changed("timeout") {
|
||||
timeout, err := cmd.Flags().GetDuration("timeout")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать тайм-аут запуска: %v", err)
|
||||
}
|
||||
c.timeout = &timeout
|
||||
}
|
||||
if cmd.Flags().Changed("endless") {
|
||||
endless, err := cmd.Flags().GetBool("endless")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр бесконечного режима: %v", err)
|
||||
}
|
||||
c.endless = &endless
|
||||
}
|
||||
if cmd.Flags().Changed("disabled") {
|
||||
disabled, err := cmd.Flags().GetBool("disabled")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр отключения: %v", err)
|
||||
}
|
||||
c.disabled = &disabled
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (uc *updateCLI) Run(ctx context.Context) error {
|
||||
logrus.Infof("Изменение настроек эксплойта с id = %s", uc.exploitID)
|
||||
|
||||
c, err := uc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.Exploit(ctx, uc.exploitID)
|
||||
if err != nil {
|
||||
logrus.Fatalf("Эксплойт с id = %s не найден", uc.exploitID)
|
||||
}
|
||||
es := resp.GetState()
|
||||
escfg := es.GetConfig()
|
||||
|
||||
runEvery := escfg.GetRunEvery()
|
||||
if uc.runEvery != nil {
|
||||
runEvery = durationpb.New(*uc.runEvery)
|
||||
}
|
||||
timeout := escfg.GetTimeout()
|
||||
if uc.timeout != nil {
|
||||
timeout = durationpb.New(*uc.timeout)
|
||||
}
|
||||
|
||||
newState := &epb.ExploitState{
|
||||
ExploitId: es.GetExploitId(),
|
||||
File: es.GetFile(),
|
||||
Version: es.GetVersion(),
|
||||
Config: &epb.ExploitConfiguration{
|
||||
Entrypoint: escfg.GetEntrypoint(),
|
||||
IsArchive: escfg.GetIsArchive(),
|
||||
RunEvery: runEvery,
|
||||
Timeout: timeout,
|
||||
Endless: lo.FromPtrOr(uc.endless, escfg.GetEndless()),
|
||||
Disabled: lo.FromPtrOr(uc.disabled, escfg.GetDisabled()),
|
||||
},
|
||||
}
|
||||
|
||||
ns, err := c.UpdateExploit(ctx, newState)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось обновить эксплойт: %w", err)
|
||||
}
|
||||
logrus.Infof("Настройки эксплойта %s обновлены", ns.GetExploitId())
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/samber/lo"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
)
|
||||
|
||||
func isBinary(data []byte) bool {
|
||||
return len(data) >= 4 && bytes.Equal(data[:4], []byte("\x7fELF"))
|
||||
}
|
||||
|
||||
func getExploitFromState(state *exploits.ServerState, exploitID string) *exploits.ExploitState {
|
||||
exp, ok := lo.Find(state.Exploits, func(s *exploits.ExploitState) bool {
|
||||
return s.ExploitId == exploitID
|
||||
})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return exp
|
||||
}
|
||||
Reference in new issue
Block a user