gzcli

package
v0.0.0-...-aa8cfd3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GZCTF_DIR        = ".gzctf"
	CONFIG_FILE      = "conf.yaml"
	APPSETTINGS_FILE = "appsettings.json"
)
View Source
const (
	DefaultScriptTimeout = 5 * time.Minute
	MaxScriptTimeout     = 30 * time.Minute
)

Script execution timeout constants

View Source
const (
	MinInterval = 30 * time.Second
	MaxInterval = 24 * time.Hour
)

Interval validation constants

Variables

View Source
var (
	CHALLENGE_CATEGORY = []string{
		"Misc", "Crypto", "Pwn",
		"Web", "Reverse", "Blockchain",
		"Forensics", "Hardware", "Mobile", "PPC",
		"OSINT", "Game Hacking", "AI", "Pentest",
	}
)
View Source
var DefaultWatcherConfig = WatcherConfig{
	PollInterval:              5 * time.Second,
	DebounceTime:              2 * time.Second,
	IgnorePatterns:            []string{},
	WatchPatterns:             []string{},
	NewChallengeCheckInterval: 10 * time.Second,
	DaemonMode:                true,
	PidFile:                   "/tmp/gzctf-watcher.pid",
	LogFile:                   "/tmp/gzctf-watcher.log",
	GitPullEnabled:            true,
	GitPullInterval:           1 * time.Minute,
	GitRepository:             ".",

	DatabaseEnabled: true,
	DatabasePath:    "/tmp/gzctf-watcher.db",

	SocketEnabled: true,
	SocketPath:    "/tmp/gzctf-watcher.sock",
}
View Source
var LeetSpeakMap = map[rune]rune{
	'a': '4',
	'e': '3',
	'i': '1',
	'o': '0',
	's': '5',
	't': '7',
	'g': '9',
}

LeetSpeakMap defines rune replacements for leetspeak transformations

Functions

func DeleteCache

func DeleteCache(key string) error

DeleteCache removes cache files with minimal syscalls

func GetCache

func GetCache(key string, data any) error

GetCache reads cached data using optimized file access

func GetClient

func GetClient(api *gzapi.GZAPI) (*gzapi.GZAPI, error)

func GetFileHashHex

func GetFileHashHex(file string) (string, error)

func MustRunScripts

func MustRunScripts(script string)

MustRunScripts executes scripts or fatally logs error

func NormalizeFileName

func NormalizeFileName(name string) string

func ParseYamlFromBytes

func ParseYamlFromBytes(b []byte, data any) error

func ParseYamlFromFile

func ParseYamlFromFile(confPath string, data any) error

func RunScripts

func RunScripts(script string) error

Optimized script runner with worker pool

Types

type AppSettings

type AppSettings struct {
	AllowedHosts      string `json:"AllowedHosts"`
	ConnectionStrings struct {
		Database   string `json:"Database"`
		RedisCache string `json:"RedisCache"`
	} `json:"ConnectionStrings"`
	Logging struct {
		LogLevel struct {
			Default                  string `json:"Default"`
			Microsoft                string `json:"Microsoft"`
			MicrosoftHostingLifetime string `json:"Microsoft.Hosting.Lifetime"`
		} `json:"LogLevel"`
		Loki struct {
			Enable             bool     `json:"Enable"`
			EndpointUri        string   `json:"EndpointUri"`
			Labels             []Label  `json:"Labels"`
			PropertiesAsLabels []string `json:"PropertiesAsLabels"`
			Credentials        struct {
				Login    string `json:"Login"`
				Password string `json:"Password"`
			} `json:"Credentials"`
			Tenant       string `json:"Tenant"`
			MinimumLevel string `json:"MinimumLevel"`
		} `json:"Loki"`
	} `json:"Logging"`
	Telemetry struct {
		Prometheus struct {
			Enable                     bool `json:"Enable"`
			Port                       int  `json:"Port"`
			TotalNameSuffixForCounters bool `json:"TotalNameSuffixForCounters"`
		} `json:"Prometheus"`
		OpenTelemetry struct {
			Enable      bool   `json:"Enable"`
			Protocol    string `json:"Protocol"`
			EndpointUri string `json:"EndpointUri"`
		} `json:"OpenTelemetry"`
		AzureMonitor struct {
			Enable           bool   `json:"Enable"`
			ConnectionString string `json:"ConnectionString"`
		} `json:"AzureMonitor"`
		Console struct {
			Enable bool `json:"Enable"`
		} `json:"Console"`
	} `json:"Telemetry"`
	EmailConfig struct {
		SenderAddress string `json:"SenderAddress"`
		SenderName    string `json:"SenderName"`
		UserName      string `json:"UserName"`
		Password      string `json:"Password"`
		Smtp          struct {
			Host             string `json:"Host"`
			Port             int    `json:"Port"`
			BypassCertVerify bool   `json:"BypassCertVerify"`
		} `json:"Smtp"`
	} `json:"EmailConfig"`
	XorKey            string `json:"XorKey"`
	ContainerProvider struct {
		Type                 string `json:"Type"`
		PortMappingType      string `json:"PortMappingType"`
		EnableTrafficCapture bool   `json:"EnableTrafficCapture"`
		PublicEntry          string `json:"PublicEntry"`
		DockerConfig         struct {
			SwarmMode        bool   `json:"SwarmMode"`
			ChallengeNetwork string `json:"ChallengeNetwork"`
			Uri              string `json:"Uri"`
			UserName         string `json:"UserName"`
			Password         string `json:"Password"`
		} `json:"DockerConfig"`
		KubernetesConfig struct {
			Namespace  string   `json:"Namespace"`
			ConfigPath string   `json:"ConfigPath"`
			AllowCIDR  []string `json:"AllowCIDR"`
			DNS        []string `json:"DNS"`
		} `json:"KubernetesConfig"`
	} `json:"ContainerProvider"`
	RequestLogging   bool `json:"RequestLogging"`
	DisableRateLimit bool `json:"DisableRateLimit"`
	RegistryConfig   struct {
		UserName      string `json:"UserName"`
		Password      string `json:"Password"`
		ServerAddress string `json:"ServerAddress"`
	} `json:"RegistryConfig"`
	CaptchaConfig struct {
		Provider        string `json:"Provider"`
		SiteKey         string `json:"SiteKey"`
		SecretKey       string `json:"SecretKey"`
		GoogleRecaptcha struct {
			VerifyAPIAddress   string `json:"VerifyAPIAddress"`
			RecaptchaThreshold string `json:"RecaptchaThreshold"`
		} `json:"GoogleRecaptcha"`
	} `json:"CaptchaConfig"`
	ForwardedOptions struct {
		ForwardedHeaders       int      `json:"ForwardedHeaders"`
		ForwardLimit           int      `json:"ForwardLimit"`
		ForwardedForHeaderName string   `json:"ForwardedForHeaderName"`
		TrustedNetworks        []string `json:"TrustedNetworks"`
		TrustedProxies         []string `json:"TrustedProxies"`
	} `json:"ForwardedOptions"`
	Kestrel struct {
		Endpoints struct {
			Web struct {
				Url string `json:"Url"`
			} `json:"Web"`
			Prometheus struct {
				Url string `json:"Url"`
			} `json:"Prometheus"`
		} `json:"Endpoints"`
		Limits struct {
			MaxResponseBufferSize            int    `json:"MaxResponseBufferSize"`
			MaxRequestBufferSize             int    `json:"MaxRequestBufferSize"`
			MaxRequestLineSize               int    `json:"MaxRequestLineSize"`
			MaxRequestHeadersTotalSize       int    `json:"MaxRequestHeadersTotalSize"`
			MaxRequestHeaderCount            int    `json:"MaxRequestHeaderCount"`
			MaxRequestBodySize               int64  `json:"MaxRequestBodySize"`
			KeepAliveTimeout                 string `json:"KeepAliveTimeout"`
			RequestHeadersTimeout            string `json:"RequestHeadersTimeout"`
			MaxConcurrentConnections         *int   `json:"MaxConcurrentConnections"`
			MaxConcurrentUpgradedConnections *int   `json:"MaxConcurrentUpgradedConnections"`
		} `json:"Limits"`
		AddServerHeader                bool    `json:"AddServerHeader"`
		AllowResponseHeaderCompression bool    `json:"AllowResponseHeaderCompression"`
		AllowSynchronousIO             bool    `json:"AllowSynchronousIO"`
		AllowAlternateSchemes          bool    `json:"AllowAlternateSchemes"`
		DisableStringReuse             bool    `json:"DisableStringReuse"`
		ConfigurationLoader            *string `json:"ConfigurationLoader"`
	} `json:"Kestrel"`
}

type CTFTimeFeed

type CTFTimeFeed struct {
	Tasks     []string   `json:"tasks"`
	Standings []Standing `json:"standings"`
}

type ChallengeState

type ChallengeState struct {
	ID            int64     `json:"id"`
	ChallengeName string    `json:"challenge_name"`
	Status        string    `json:"status"` // watching, updating, deploying, error
	LastUpdate    time.Time `json:"last_update"`
	ErrorMessage  string    `json:"error_message,omitempty"`
	ScriptStates  string    `json:"script_states"` // JSON of active interval scripts
}

type ChallengeYaml

type ChallengeYaml struct {
	Name        string                 `yaml:"name"`
	Author      string                 `yaml:"author"`
	Description string                 `yaml:"description"`
	Flags       []string               `yaml:"flags"`
	Value       int                    `yaml:"value"`
	Provide     *string                `yaml:"provide,omitempty"`
	Visible     *bool                  `yaml:"visible"`
	Type        string                 `yaml:"type"`
	Hints       []string               `yaml:"hints"`
	Container   Container              `yaml:"container"`
	Scripts     map[string]ScriptValue `yaml:"scripts"`
	Category    string                 `yaml:"-"`
	Cwd         string                 `yaml:"-"`
}

func GetChallengesYaml

func GetChallengesYaml(config *Config) ([]ChallengeYaml, error)

type Config

type Config struct {
	Url   string      `yaml:"url"`
	Creds gzapi.Creds `yaml:"creds"`
	Event gzapi.Game  `yaml:"event"`
	// contains filtered or unexported fields
}

func GetConfig

func GetConfig(api *gzapi.GZAPI) (*Config, error)

type Container

type Container struct {
	FlagTemplate         string `yaml:"flagTemplate"`
	ContainerImage       string `yaml:"containerImage"`
	MemoryLimit          int    `yaml:"memoryLimit"`
	CpuCount             int    `yaml:"cpuCount"`
	StorageLimit         int    `yaml:"storageLimit"`
	ContainerExposePort  int    `yaml:"containerExposePort"`
	EnableTrafficCapture bool   `yaml:"enableTrafficCapture"`
}

type GZ

type GZ struct {
	UpdateGame bool
	// contains filtered or unexported fields
}

func Init

func Init() (*GZ, error)

func MustInit

func MustInit() *GZ

MustInit initializes GZ or fatally logs error

func (*GZ) CreateTeams

func (gz *GZ) CreateTeams(csvURL string, isSendEmail bool) error

func (*GZ) CreteTeamAndUser

func (gz *GZ) CreteTeamAndUser(teamCreds *TeamCreds, config *Config, existingTeamNames, existingUserNames map[string]struct{}, credsCache []*TeamCreds, isSendEmail bool) (*TeamCreds, error)

CreteTeamAndUser creates a team and user, ensuring the team name is unique and within the specified length.

func (*GZ) DeleteAllUser

func (gz *GZ) DeleteAllUser() error

func (*GZ) GenerateStructure

func (gz *GZ) GenerateStructure() error

func (*GZ) GetWatcherStatus

func (gz *GZ) GetWatcherStatus() map[string]interface{}

GetWatcherStatus returns the status of the watcher service

func (*GZ) IsWatcherRunning

func (gz *GZ) IsWatcherRunning() bool

IsWatcherRunning returns true if the watcher is currently running

func (*GZ) MustCreateTeams

func (gz *GZ) MustCreateTeams(url string, sendEmail bool)

MustCreateTeams creates teams or fatally logs error

func (*GZ) MustDeleteAllUser

func (gz *GZ) MustDeleteAllUser()

MustDeleteAllUser removes all users or fatally logs error

func (*GZ) MustScoreboard2CTFTimeFeed

func (gz *GZ) MustScoreboard2CTFTimeFeed() *CTFTimeFeed

func (*GZ) MustStartWatcher

func (gz *GZ) MustStartWatcher(config WatcherConfig)

MustStartWatcher starts the watcher or fatally logs error

func (*GZ) MustStopWatcher

func (gz *GZ) MustStopWatcher()

MustStopWatcher stops the watcher or fatally logs error

func (*GZ) MustSync

func (gz *GZ) MustSync()

MustSync synchronizes data or fatally logs error

func (*GZ) RemoveAllEvent

func (gz *GZ) RemoveAllEvent() error

Bulk game deletion with parallel execution

func (*GZ) Scoreboard2CTFTimeFeed

func (gz *GZ) Scoreboard2CTFTimeFeed() (*CTFTimeFeed, error)

Preallocated scoreboard generation

func (*GZ) StartWatcher

func (gz *GZ) StartWatcher(config WatcherConfig) error

StartWatcher starts the file watcher service

func (*GZ) StopWatcher

func (gz *GZ) StopWatcher() error

StopWatcher stops the file watcher service

func (*GZ) Sync

func (gz *GZ) Sync() error

type Label

type Label struct {
	Key   string `json:"Key"`
	Value string `json:"Value"`
}

type ScriptConfig

type ScriptConfig struct {
	Execute  string        `yaml:"execute,omitempty"`
	Interval time.Duration `yaml:"interval,omitempty"`
}

ScriptConfig represents a script configuration that can be either a simple string or a complex object with interval and execute parameters

type ScriptExecution

type ScriptExecution struct {
	ID            int64     `json:"id"`
	Timestamp     time.Time `json:"timestamp"`
	ChallengeName string    `json:"challenge_name"`
	ScriptName    string    `json:"script_name"`
	ScriptType    string    `json:"script_type"` // one-time, interval
	Command       string    `json:"command"`
	Status        string    `json:"status"`             // started, completed, failed, cancelled
	Duration      int64     `json:"duration,omitempty"` // nanoseconds
	Output        string    `json:"output,omitempty"`
	ErrorOutput   string    `json:"error_output,omitempty"`
	ExitCode      int       `json:"exit_code,omitempty"`
	Success       bool      `json:"success"` // computed field based on status and exit code
}

type ScriptMetrics

type ScriptMetrics struct {
	LastExecution  time.Time
	ExecutionCount int64
	LastError      error
	LastDuration   time.Duration
	TotalDuration  time.Duration
	Interval       time.Duration `json:"interval,omitempty"` // For interval scripts
	IsInterval     bool          `json:"is_interval"`        // Whether this is an interval script
}

ScriptMetrics tracks execution statistics for scripts

type ScriptValue

type ScriptValue struct {
	Simple  string
	Complex *ScriptConfig
}

ScriptValue holds either a simple command string or a complex ScriptConfig

func (*ScriptValue) GetCommand

func (sv *ScriptValue) GetCommand() string

GetCommand returns the command to execute

func (*ScriptValue) GetInterval

func (sv *ScriptValue) GetInterval() time.Duration

GetInterval returns the execution interval for complex scripts

func (*ScriptValue) HasInterval

func (sv *ScriptValue) HasInterval() bool

HasInterval returns true if this script has an interval configured

func (*ScriptValue) IsSimple

func (sv *ScriptValue) IsSimple() bool

IsSimple returns true if this is a simple string command

func (*ScriptValue) UnmarshalYAML

func (sv *ScriptValue) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements custom YAML unmarshaling for ScriptValue

type Standing

type Standing struct {
	Pos   int    `json:"pos"`
	Team  string `json:"team"`
	Score int    `json:"score"`
}

type TeamCreds

type TeamCreds struct {
	Username           string `json:"username" yaml:"username"`
	Password           string `json:"password" yaml:"password"`
	Email              string `json:"email" yaml:"email"`
	TeamName           string `json:"team_name" yaml:"team_name"`
	IsEmailAlreadySent bool   `json:"is_email_already_sent" yaml:"is_email_already_sent"`
	IsTeamCreated      bool   `json:"is_team_created" yaml:"is_team_created"`
}

TeamCreds stores team credentials

type UpdateType

type UpdateType int

UpdateType represents the type of update needed based on file changes

const (
	UpdateNone UpdateType = iota
	UpdateAttachment
	UpdateMetadata
	UpdateFullRedeploy
)

type Watcher

type Watcher struct {
	// contains filtered or unexported fields
}

func NewWatcher

func NewWatcher(gz *GZ) (*Watcher, error)

NewWatcher creates a new file watcher instance

func (*Watcher) FollowLogs

func (w *Watcher) FollowLogs(logFile string) error

FollowLogs follows a log file and displays new content in real-time

func (*Watcher) GetActiveIntervalScripts

func (w *Watcher) GetActiveIntervalScripts() map[string][]string

GetActiveIntervalScripts returns a list of currently running interval scripts

func (*Watcher) GetDaemonStatus

func (w *Watcher) GetDaemonStatus(pidFile string) map[string]interface{}

GetDaemonStatus returns the status of the daemon watcher

func (*Watcher) GetScriptMetrics

func (w *Watcher) GetScriptMetrics() map[string]map[string]*ScriptMetrics

GetScriptMetrics returns script execution metrics for monitoring

func (*Watcher) GetWatchedChallenges

func (w *Watcher) GetWatchedChallenges() []string

GetWatchedChallenges returns the list of currently watched challenge directories

func (*Watcher) IsWatching

func (w *Watcher) IsWatching() bool

IsWatching returns true if the watcher is currently active

func (*Watcher) ShowStatus

func (w *Watcher) ShowStatus(pidFile, logFile string, jsonOutput bool) error

ShowStatus displays the watcher status

func (*Watcher) Start

func (w *Watcher) Start(config WatcherConfig) error

Start starts the file watcher with the given configuration

func (*Watcher) Stop

func (w *Watcher) Stop() error

Stop stops the file watcher with improved graceful shutdown

func (*Watcher) StopDaemon

func (w *Watcher) StopDaemon(pidFile string) error

StopDaemon stops the daemon watcher

type WatcherClient

type WatcherClient struct {
	// contains filtered or unexported fields
}

WatcherClient provides a client interface to communicate with the watcher daemon

func NewWatcherClient

func NewWatcherClient(socketPath string) *WatcherClient

NewWatcherClient creates a new watcher client

func (*WatcherClient) GetLogs

func (c *WatcherClient) GetLogs(limit int) (*WatcherResponse, error)

GetLogs gets recent logs from the database

func (*WatcherClient) GetMetrics

func (c *WatcherClient) GetMetrics() (*WatcherResponse, error)

GetMetrics gets script execution metrics

func (*WatcherClient) GetScriptExecutions

func (c *WatcherClient) GetScriptExecutions(challengeName string, limit int) (*WatcherResponse, error)

GetScriptExecutions gets script execution history

func (*WatcherClient) IsWatcherRunning

func (c *WatcherClient) IsWatcherRunning() bool

IsWatcherRunning checks if the watcher daemon is running

func (*WatcherClient) ListChallenges

func (c *WatcherClient) ListChallenges() (*WatcherResponse, error)

ListChallenges gets the list of watched challenges

func (*WatcherClient) PrintChallenges

func (c *WatcherClient) PrintChallenges() error

PrintChallenges prints a formatted list of challenges

func (*WatcherClient) PrintLogs

func (c *WatcherClient) PrintLogs(limit int) error

PrintLogs prints formatted recent logs

func (*WatcherClient) PrintMetrics

func (c *WatcherClient) PrintMetrics() error

PrintMetrics prints formatted script metrics

func (*WatcherClient) PrintStatus

func (c *WatcherClient) PrintStatus() error

PrintStatus prints a formatted status report

func (*WatcherClient) RestartChallenge

func (c *WatcherClient) RestartChallenge(challengeName string) (*WatcherResponse, error)

RestartChallenge triggers a full restart of a challenge

func (*WatcherClient) SendCommand

func (c *WatcherClient) SendCommand(action string, data map[string]interface{}) (*WatcherResponse, error)

SendCommand sends a command to the watcher and returns the response

func (*WatcherClient) SetTimeout

func (c *WatcherClient) SetTimeout(timeout time.Duration)

SetTimeout sets the connection timeout for the client

func (*WatcherClient) Status

func (c *WatcherClient) Status() (*WatcherResponse, error)

Status gets the current watcher status

func (*WatcherClient) StopScript

func (c *WatcherClient) StopScript(challengeName, scriptName string) (*WatcherResponse, error)

StopScript stops a specific interval script

func (*WatcherClient) StreamLiveLogs

func (c *WatcherClient) StreamLiveLogs(limit int, interval time.Duration) error

StreamLiveLogs streams database logs in real-time

func (*WatcherClient) WaitForWatcher

func (c *WatcherClient) WaitForWatcher(maxWait time.Duration) error

WaitForWatcher waits for the watcher to become available

type WatcherCommand

type WatcherCommand struct {
	Action string                 `json:"action"`
	Data   map[string]interface{} `json:"data,omitempty"`
}

WatcherCommand represents commands that can be sent to the watcher via socket

type WatcherConfig

type WatcherConfig struct {
	PollInterval              time.Duration
	DebounceTime              time.Duration
	IgnorePatterns            []string
	WatchPatterns             []string
	NewChallengeCheckInterval time.Duration // New field for checking new challenges
	DaemonMode                bool          // Run watcher as daemon
	PidFile                   string        // PID file location
	LogFile                   string        // Log file location
	GitPullEnabled            bool          // Enable automatic git pull
	GitPullInterval           time.Duration // Interval for git pull (default: 1 minute)
	GitRepository             string        // Git repository path (default: current directory)
	// Database configuration
	DatabaseEnabled bool   // Enable database logging
	DatabasePath    string // SQLite database file path
	// Socket configuration
	SocketEnabled bool   // Enable socket server
	SocketPath    string // Unix socket path for communication
}

type WatcherLog

type WatcherLog struct {
	ID        int64     `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	Level     string    `json:"level"`
	Component string    `json:"component"`
	Challenge string    `json:"challenge,omitempty"`
	Script    string    `json:"script,omitempty"`
	Message   string    `json:"message"`
	Error     string    `json:"error,omitempty"`
	Duration  int64     `json:"duration,omitempty"` // milliseconds
}

Database models for persistent storage

type WatcherResponse

type WatcherResponse struct {
	Success bool                   `json:"success"`
	Message string                 `json:"message,omitempty"`
	Data    map[string]interface{} `json:"data,omitempty"`
	Error   string                 `json:"error,omitempty"`
}

WatcherResponse represents responses from the watcher

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL