Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions tavern/internal/c2/api_claim_tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"strings"
"time"

"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"realm.pub/tavern/internal/c2/c2pb"
"realm.pub/tavern/internal/c2/epb"
Expand All @@ -34,8 +37,37 @@ func init() {
prometheus.MustRegister(metricHostCallbacksTotal)
}

func getRemoteIP(ctx context.Context) string {
p, ok := peer.FromContext(ctx)
if !ok {
return "unknown"
}

host, _, err := net.SplitHostPort(p.Addr.String())
if err != nil {
return "unknown"
}

return host
}

func getClientIP(ctx context.Context) string {
md, ok := metadata.FromIncomingContext(ctx)
if ok {
if forwardedFor, exists := md["x-forwarded-for"]; exists && len(forwardedFor) > 0 {
// X-Forwarded-For is a comma-separated list, the first IP is the original client
clientIP := strings.Split(forwardedFor[0], ",")[0]
return strings.TrimSpace(clientIP)
}
}

// Fallback to peer address
return getRemoteIP(ctx)
}

func (srv *Server) ClaimTasks(ctx context.Context, req *c2pb.ClaimTasksRequest) (*c2pb.ClaimTasksResponse, error) {
now := time.Now()
clientIP := getClientIP(ctx)

// Validate input
if req.Beacon == nil {
Expand Down Expand Up @@ -66,6 +98,7 @@ func (srv *Server) ClaimTasks(ctx context.Context, req *c2pb.ClaimTasksRequest)
SetName(req.Beacon.Host.Name).
SetPlatform(req.Beacon.Host.Platform).
SetPrimaryIP(req.Beacon.Host.PrimaryIp).
SetExternalIP(clientIP).
SetLastSeenAt(now).
OnConflict().
UpdateNewValues().
Expand Down
5 changes: 5 additions & 0 deletions tavern/internal/ent/gql_collection.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

62 changes: 62 additions & 0 deletions tavern/internal/ent/gql_where_input.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 12 additions & 1 deletion tavern/internal/ent/host.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions tavern/internal/ent/host/host.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

80 changes: 80 additions & 0 deletions tavern/internal/ent/host/where.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading