237 lines
6.8 KiB
Go
237 lines
6.8 KiB
Go
package exploits
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"github.com/c4t-but-s4d/neo/v2/internal/config"
|
|
"github.com/c4t-but-s4d/neo/v2/internal/server/common"
|
|
serverConfig "github.com/c4t-but-s4d/neo/v2/internal/server/config"
|
|
"github.com/c4t-but-s4d/neo/v2/pkg/gstream"
|
|
"github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
|
|
"github.com/c4t-but-s4d/neo/v2/pkg/pubsub"
|
|
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
|
)
|
|
|
|
func New(cfg *serverConfig.Config, storage *CachedStorage) *Server {
|
|
ems := &Server{
|
|
LoggingServer: common.NewLoggingServer("exploits"),
|
|
storage: storage,
|
|
buckets: hostbucket.New(cfg.FarmConfig.Teams),
|
|
visits: newVisitsMap(),
|
|
singleRunPubSub: pubsub.NewPubSub[*epb.SingleRunRequest](),
|
|
broadcastPubSub: pubsub.NewPubSub[*epb.BroadcastRequest](),
|
|
metrics: NewMetrics(cfg.MetricsNamespace),
|
|
}
|
|
ems.UpdateConfig(cfg)
|
|
return ems
|
|
}
|
|
|
|
type Server struct {
|
|
epb.UnimplementedServiceServer
|
|
common.LoggingServer
|
|
|
|
storage *CachedStorage
|
|
config *config.ExploitsConfig
|
|
cfgMutex sync.RWMutex
|
|
buckets *hostbucket.HostBucket
|
|
visits *visitsMap
|
|
metrics *Metrics
|
|
|
|
singleRunPubSub *pubsub.PubSub[*epb.SingleRunRequest]
|
|
broadcastPubSub *pubsub.PubSub[*epb.BroadcastRequest]
|
|
}
|
|
|
|
func (s *Server) Ping(ctx context.Context, r *epb.PingRequest) (*epb.PingResponse, error) {
|
|
s.LogRequest(ctx, r)
|
|
if r == nil {
|
|
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "требуется запрос Ping")
|
|
}
|
|
|
|
switch p := r.Payload.(type) {
|
|
case *epb.PingRequest_ServerInfoRequest:
|
|
// Пропустить эту запись.
|
|
case *epb.PingRequest_HeartbeatRequest:
|
|
s.cfgMutex.RLock()
|
|
defer s.cfgMutex.RUnlock()
|
|
s.visits.Add(r.ClientId)
|
|
s.buckets.AddNode(r.ClientId, int(p.HeartbeatRequest.Weight))
|
|
case *epb.PingRequest_LeaveRequest:
|
|
s.visits.MarkInvalid(r.ClientId)
|
|
default:
|
|
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неизвестный тип данных: %T", p)
|
|
}
|
|
|
|
return &epb.PingResponse{
|
|
State: &epb.ServerState{
|
|
ClientTeamMap: s.buckets.Buckets(),
|
|
Exploits: s.storage.States(),
|
|
Config: config.ToProto(s.config),
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func (s *Server) Exploit(ctx context.Context, r *epb.ExploitRequest) (*epb.ExploitResponse, error) {
|
|
s.LogRequest(ctx, r)
|
|
if r == nil || !validExploitID(r.ExploitId) {
|
|
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный идентификатор эксплойта")
|
|
}
|
|
|
|
state, ok := s.storage.GetState(r.ExploitId)
|
|
if !ok {
|
|
return nil, s.WrapErrorf(ctx, codes.NotFound, "эксплойт %q не найден", r.ExploitId)
|
|
}
|
|
return &epb.ExploitResponse{
|
|
State: state,
|
|
}, nil
|
|
}
|
|
|
|
func (s *Server) UpdateExploit(ctx context.Context, r *epb.UpdateExploitRequest) (*epb.UpdateExploitResponse, error) {
|
|
s.LogRequest(ctx, r)
|
|
if r == nil || r.State == nil || r.State.Config == nil || r.State.File == nil ||
|
|
!validExploitID(r.State.ExploitId) || !validFileUUID(r.State.File.Uuid) {
|
|
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверное состояние эксплойта")
|
|
}
|
|
if r.State.Config.IsArchive && (r.State.Config.Entrypoint == "" ||
|
|
strings.ContainsAny(r.State.Config.Entrypoint, "\\\x00") || !filepath.IsLocal(r.State.Config.Entrypoint)) {
|
|
return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный путь точки входа в архиве")
|
|
}
|
|
|
|
newState, err := s.storage.UpdateExploitVersion(r.State)
|
|
if err != nil {
|
|
return nil, s.WrapErrorf(ctx, codes.Internal, "Не удалось обновить версию эксплойта: %v", err)
|
|
}
|
|
return &epb.UpdateExploitResponse{State: newState}, nil
|
|
}
|
|
|
|
func validExploitID(id string) bool {
|
|
return id != "" && len(id) <= 128 && id != "." && id != ".." &&
|
|
!strings.ContainsAny(id, "/\\\x00") && filepath.IsLocal(id)
|
|
}
|
|
|
|
func validFileUUID(id string) bool {
|
|
parsed, err := uuid.Parse(id)
|
|
return err == nil && parsed.String() == id
|
|
}
|
|
|
|
func (s *Server) BroadcastCommand(ctx context.Context, r *epb.BroadcastRequest) (*epb.BroadcastResponse, error) {
|
|
s.LogRequest(ctx, r)
|
|
|
|
s.broadcastPubSub.Publish(r)
|
|
return &epb.BroadcastResponse{}, nil
|
|
}
|
|
|
|
func (s *Server) BroadcastSubscribe(r *epb.BroadcastSubscribeRequest, stream epb.Service_BroadcastSubscribeServer) error {
|
|
s.LogRequest(stream.Context(), r)
|
|
|
|
wstream := gstream.Wrap[
|
|
epb.BroadcastRequest,
|
|
epb.BroadcastSubscribeResponse,
|
|
](
|
|
stream,
|
|
func(t *epb.BroadcastRequest) *epb.BroadcastSubscribeResponse {
|
|
return &epb.BroadcastSubscribeResponse{Command: t.Command}
|
|
},
|
|
)
|
|
|
|
sub := s.broadcastPubSub.Subscribe(wstream.Send)
|
|
defer s.broadcastPubSub.Unsubscribe(sub)
|
|
|
|
sub.Run(stream.Context())
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) SingleRun(ctx context.Context, r *epb.SingleRunRequest) (*epb.SingleRunResponse, error) {
|
|
s.LogRequest(ctx, r)
|
|
|
|
s.singleRunPubSub.Publish(r)
|
|
return &epb.SingleRunResponse{}, nil
|
|
}
|
|
|
|
func (s *Server) SingleRunSubscribe(r *epb.SingleRunSubscribeRequest, stream epb.Service_SingleRunSubscribeServer) error {
|
|
s.LogRequest(stream.Context(), r)
|
|
|
|
wstream := gstream.Wrap[
|
|
epb.SingleRunRequest,
|
|
epb.SingleRunSubscribeResponse,
|
|
](
|
|
stream,
|
|
func(t *epb.SingleRunRequest) *epb.SingleRunSubscribeResponse {
|
|
return &epb.SingleRunSubscribeResponse{ExploitId: t.ExploitId}
|
|
},
|
|
)
|
|
|
|
sub := s.singleRunPubSub.Subscribe(wstream.Send)
|
|
defer s.singleRunPubSub.Unsubscribe(sub)
|
|
|
|
sub.Run(stream.Context())
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) HeartBeat(ctx context.Context) {
|
|
ticker := time.NewTicker(s.config.PingEvery)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
s.Logger.Info("Проверка клиентов")
|
|
s.checkClients()
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *Server) UpdateMetrics(ctx context.Context) {
|
|
ticker := time.NewTicker(time.Second * 5)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
s.Logger.Info("Обновление метрик")
|
|
s.updateMetrics()
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *Server) UpdateConfig(cfg *serverConfig.Config) {
|
|
env := make([]string, 0, len(cfg.Environ))
|
|
for k, v := range cfg.Environ {
|
|
env = append(env, fmt.Sprintf("%s=%s", k, v))
|
|
}
|
|
|
|
s.cfgMutex.Lock()
|
|
defer s.cfgMutex.Unlock()
|
|
s.config = &config.ExploitsConfig{
|
|
PingEvery: cfg.PingEvery,
|
|
SubmitEvery: cfg.SubmitEvery,
|
|
FarmURL: cfg.FarmConfig.URL,
|
|
FarmPassword: cfg.FarmConfig.Password,
|
|
FlagRegexp: regexp.MustCompile(cfg.FarmConfig.FlagRegexp),
|
|
Environ: env,
|
|
}
|
|
s.buckets.UpdateTeams(cfg.FarmConfig.Teams)
|
|
}
|
|
|
|
func (s *Server) checkClients() {
|
|
alive, dead := s.visits.Invalidate(time.Now(), s.config.PingEvery)
|
|
s.Logger.Infof("Проверка связи: недоступные клиенты %v, доступные клиенты %v", dead, alive)
|
|
for _, c := range dead {
|
|
s.buckets.DeleteNode(c)
|
|
}
|
|
}
|
|
|
|
func (s *Server) updateMetrics() {
|
|
s.metrics.AliveClients.Set(float64(s.visits.Size()))
|
|
}
|