diff --git a/.gitignore b/.gitignore index 869a59b..915635e 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ TODO docker-compose.local.yml config.yaml coverage.out -openapi.yaml \ No newline at end of file +openapi.yaml +monitoring/worker/cf.env diff --git a/config.example.yaml b/config.example.yaml index e54e80f..892cbc7 100755 --- a/config.example.yaml +++ b/config.example.yaml @@ -5,6 +5,7 @@ instancer: ansible_dir: "./data/playbooks" # Directory for Ansible playbooks challenge_dir: "./data/challenges" # Directory for challenge files instancer_host: "challs.example.com" # Public hostname of the deployer (will be used in domain names) + compose_project_prefix: "ctf-event" # Readable prefix of instance names/subdomains (default: "ctf-event") db_path: "./data/deployer.sqlite" # Path to SQLite database deployment_ttl: "1h" # Time-to-live for deployments (default: 1h) deployment_ttl_extension: "30m" # Time to extend deployment TTL with on extension request (default: 30m) diff --git a/data/challenges/example/http/challenge.yml b/data/challenges/example/http/challenge.yml index d4f4b8c..3dc604b 100644 --- a/data/challenges/example/http/challenge.yml +++ b/data/challenges/example/http/challenge.yml @@ -6,7 +6,8 @@ type: zync # The 'http' playbook deploys a single container behind Traefik. # Traefik routes traffic based on a generated subdomain: -# . (e.g. polypwn-web-example-http-team1-9448f1e7.challs.example.com) +# . (e.g. ctf-event-web-example-http-team1-9448f1e7.challs.example.com) +# The "ctf-event" prefix can be changed with instancer.compose_project_prefix in config.yaml. playbook_name: http deploy_parameters: diff --git a/data/playbooks/custom_compose.yaml b/data/playbooks/custom_compose.yaml index b1706ea..3452666 100644 --- a/data/playbooks/custom_compose.yaml +++ b/data/playbooks/custom_compose.yaml @@ -66,12 +66,12 @@ tags: - delete - # Instances started by Galvanize v0.7.1 or earlier have another project - # name (legacy_compose_project, set when it differs): remove such a - # leftover too. A no-op when there is none, and never fails the run. - - name: Remove an instance left under its previous project name - ansible.builtin.command: "docker compose -p {{ legacy_compose_project }} down --remove-orphans" - when: legacy_compose_project is defined + # Instances started by earlier Galvanize versions have other project + # names (legacy_compose_projects, those that differ): remove such + # leftovers too. A no-op when there are none, and never fails the run. + - name: Remove an instance left under a previous project name + ansible.builtin.command: "docker compose -p {{ item }} down --remove-orphans" + loop: "{{ legacy_compose_projects | default([]) }}" changed_when: false failed_when: false tags: diff --git a/data/playbooks/http.yaml b/data/playbooks/http.yaml index 2330005..c63ab18 100644 --- a/data/playbooks/http.yaml +++ b/data/playbooks/http.yaml @@ -36,7 +36,7 @@ - name: Build compose definition ansible.builtin.set_fact: - compose_definition: + _compose_def: services: web: "{{ _web_service }}" networks: "{{ {traefik_network: {'external': true}} }}" @@ -46,28 +46,29 @@ - name: Déploiement du docker-compose community.docker.docker_compose_v2: - definition: "{{ compose_definition }}" + definition: "{{ _compose_def }}" project_name: "{{ compose_project }}" pull: missing tags: create - name: Arrêt des conteneurs ansible.builtin.command: "docker compose -p {{ compose_project }} kill" + failed_when: false tags: delete - name: Arrêt et suppression du docker-compose community.docker.docker_compose_v2: - definition: "{{ compose_definition }}" + definition: "{{ _compose_def }}" project_name: "{{ compose_project }}" state: absent tags: delete - # Instances started by Galvanize v0.7.1 or earlier have another project - # name (legacy_compose_project, set when it differs): remove such a - # leftover too. A no-op when there is none, and never fails the run. - - name: Remove an instance left under its previous project name - ansible.builtin.command: "docker compose -p {{ legacy_compose_project }} down --remove-orphans" - when: legacy_compose_project is defined + # Instances started by earlier Galvanize versions have other project + # names (legacy_compose_projects, those that differ): remove such + # leftovers too. A no-op when there are none, and never fails the run. + - name: Remove an instance left under a previous project name + ansible.builtin.command: "docker compose -p {{ item }} down --remove-orphans" + loop: "{{ legacy_compose_projects | default([]) }}" changed_when: false failed_when: false tags: diff --git a/data/playbooks/tcp.yaml b/data/playbooks/tcp.yaml index 1b6494a..5e5875f 100755 --- a/data/playbooks/tcp.yaml +++ b/data/playbooks/tcp.yaml @@ -24,7 +24,7 @@ - name: Build compose definition ansible.builtin.set_fact: - compose_definition: + _compose_def: services: tcp: "{{ _tcp_service }}" tags: @@ -33,24 +33,29 @@ - name: Déploiement du docker-compose community.docker.docker_compose_v2: - definition: "{{ compose_definition }}" + definition: "{{ _compose_def }}" project_name: "{{ compose_project }}" pull: missing tags: create + - name: Arrêt des conteneurs + ansible.builtin.command: "docker compose -p {{ compose_project }} kill" + failed_when: false + tags: delete + - name: Arrêt et suppression du docker-compose community.docker.docker_compose_v2: - definition: "{{ compose_definition }}" + definition: "{{ _compose_def }}" project_name: "{{ compose_project }}" state: absent tags: delete - # Instances started by Galvanize v0.7.1 or earlier have another project - # name (legacy_compose_project, set when it differs): remove such a - # leftover too. A no-op when there is none, and never fails the run. - - name: Remove an instance left under its previous project name - ansible.builtin.command: "docker compose -p {{ legacy_compose_project }} down --remove-orphans" - when: legacy_compose_project is defined + # Instances started by earlier Galvanize versions have other project + # names (legacy_compose_projects, those that differ): remove such + # leftovers too. A no-op when there are none, and never fails the run. + - name: Remove an instance left under a previous project name + ansible.builtin.command: "docker compose -p {{ item }} down --remove-orphans" + loop: "{{ legacy_compose_projects | default([]) }}" changed_when: false failed_when: false tags: diff --git a/galvanize-instancer/Dockerfile b/galvanize-instancer/Dockerfile index e49d899..5303961 100755 --- a/galvanize-instancer/Dockerfile +++ b/galvanize-instancer/Dockerfile @@ -20,7 +20,8 @@ RUN useradd -ms /bin/bash galvanize RUN apt-get update && apt-get install -y curl pipx ssh-client tini \ && rm -rf /var/lib/apt/lists/* \ && pipx ensurepath --global \ - && pipx install --include-deps --global ansible + && pipx install --include-deps --global ansible \ + && ansible-galaxy collection install community.docker -p /usr/share/ansible/collections WORKDIR /app RUN mkdir "data" COPY ./data/playbooks ./data/playbooks diff --git a/galvanize-instancer/internal/ansible/compose_expose.go b/galvanize-instancer/internal/ansible/compose_expose.go index f2cd699..ebbc1f5 100644 --- a/galvanize-instancer/internal/ansible/compose_expose.go +++ b/galvanize-instancer/internal/ansible/compose_expose.go @@ -66,7 +66,7 @@ func applyComposeExposures(conf *config.Config, chall *challenge.Challenge, team return nil, fmt.Errorf("compose definition has no services map") } - project := docker.BuildComposeProject(chall.Unique, chall.Category, chall.Name, teamID) + project := docker.BuildComposeProject(conf.Instancer.ComposeProjectPrefix, chall.Unique, chall.Category, chall.InstanceKey(), teamID) domainRoot := conf.Instancer.InstancerHost traefikNetwork, _ := conf.Instancer.ExtraDeploymentParameters[traefikNetworkParam].(string) @@ -94,7 +94,7 @@ func applyComposeExposures(conf *config.Config, chall *challenge.Challenge, team routerName := project domain := project + "." + domainRoot if httpCount > 1 { - routerName = docker.SanitizeProjectName(exp.Service+"-"+project) + routerName = docker.SanitizeProjectName(exp.Service + "-" + project) domain = docker.SanitizeProjectName(exp.Service+"-"+project) + "." + domainRoot } applyTraefikLabels(svc, routerName, domain, exp.Port) @@ -167,11 +167,17 @@ func normalizeLabels(existing interface{}) map[string]interface{} { } // attachNetwork ensures a service is connected to the named network, preserving -// any existing network configuration. +// any existing network configuration. A service with no networks key is on +// Compose's implicit default network; listing only the new network would drop +// that and isolate it from sibling services (e.g. app → db). func attachNetwork(svc map[string]interface{}, network string) { switch v := svc["networks"].(type) { case nil: - svc["networks"] = []interface{}{network} + if network == "default" { + svc["networks"] = []interface{}{network} + } else { + svc["networks"] = []interface{}{"default", network} + } case []interface{}: for _, n := range v { if s, ok := n.(string); ok && s == network { diff --git a/galvanize-instancer/internal/ansible/compose_expose_test.go b/galvanize-instancer/internal/ansible/compose_expose_test.go index 80a336b..5ae9a58 100644 --- a/galvanize-instancer/internal/ansible/compose_expose_test.go +++ b/galvanize-instancer/internal/ansible/compose_expose_test.go @@ -96,9 +96,10 @@ func TestApplyComposeExposures_HTTPWiresTraefik(t *testing.T) { assert.True(t, ruleFound, "router rule label should be set") assert.True(t, portFound, "loadbalancer port label should be set") - // Service joined the traefik network. + // Service stays on the implicit default network and also joins Traefik. nets, ok := web["networks"].([]interface{}) require.True(t, ok) + assert.Contains(t, nets, "default") assert.Contains(t, nets, "traefik") // Top-level external network declared. diff --git a/galvanize-instancer/internal/ansible/connection_info.go b/galvanize-instancer/internal/ansible/connection_info.go index 1891138..42eab33 100644 --- a/galvanize-instancer/internal/ansible/connection_info.go +++ b/galvanize-instancer/internal/ansible/connection_info.go @@ -2,10 +2,17 @@ package ansible import ( "fmt" + "sort" "strings" ) -func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string) (string, error) { +// GetConnectionInfo returns the first Traefik HTTP URL found, or else the +// published ports. When showTCPPorts is set, the published ports of every +// container are listed after the HTTP URL instead of being hidden by it. +func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string, showTCPPorts bool) (string, error) { + if showTCPPorts { + return getAllConnectionInfo(containerInfos, host, protocolHints) + } traefikLabel := "" for _, ci := range containerInfos { for labelKey, labelValue := range ci.Labels { @@ -23,25 +30,75 @@ func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHint } } // Check if we have published ports - var ports []string - for _, pub := range ci.Publishers { - if pub.PublishedPort != 0 { - // If IP is IPv6, continue - if strings.Contains(pub.URL, ":") { - continue - } - scheme := pub.Protocol - if protocolHints != nil { - if hintedScheme, ok := protocolHints[pub.TargetPort]; ok { - scheme = hintedScheme - } - } - ports = append(ports, fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort)) - } - } + ports := publishedPortURLs(ci.Publishers, host, protocolHints) if len(ports) > 0 { return strings.Join(ports, "\n"), nil } } return "", fmt.Errorf("no connection info found") } + +func getAllConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string) (string, error) { + var lines []string + for _, ci := range containerInfos { + if url := traefikURL(ci.Labels); url != "" { + lines = append(lines, url) + break + } + } + var publishers []PublisherInfo + for _, ci := range containerInfos { + publishers = append(publishers, ci.Publishers...) + } + // Docker does not guarantee publisher order; sort so the output is stable. + sort.SliceStable(publishers, func(i, j int) bool { + if publishers[i].TargetPort != publishers[j].TargetPort { + return publishers[i].TargetPort < publishers[j].TargetPort + } + return publishers[i].PublishedPort < publishers[j].PublishedPort + }) + seen := map[string]bool{} + for _, port := range publishedPortURLs(publishers, host, protocolHints) { + if !seen[port] { + seen[port] = true + lines = append(lines, port) + } + } + if len(lines) == 0 { + return "", fmt.Errorf("no connection info found") + } + return strings.Join(lines, "\n"), nil +} + +func traefikURL(labels map[string]string) string { + for labelKey, labelValue := range labels { + if !strings.HasPrefix(labelKey, "traefik.http.routers.") { + continue + } + labelParts := strings.Split(labelValue, "`") + if len(labelParts) >= 2 { + return "https://" + labelParts[1] + "/" + } + } + return "" +} + +func publishedPortURLs(publishers []PublisherInfo, host string, protocolHints map[int]string) []string { + var ports []string + for _, pub := range publishers { + if pub.PublishedPort != 0 { + // If IP is IPv6, continue + if strings.Contains(pub.URL, ":") { + continue + } + scheme := pub.Protocol + if protocolHints != nil { + if hintedScheme, ok := protocolHints[pub.TargetPort]; ok { + scheme = hintedScheme + } + } + ports = append(ports, fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort)) + } + } + return ports +} diff --git a/galvanize-instancer/internal/ansible/connection_info_test.go b/galvanize-instancer/internal/ansible/connection_info_test.go index 793fef2..40abacf 100644 --- a/galvanize-instancer/internal/ansible/connection_info_test.go +++ b/galvanize-instancer/internal/ansible/connection_info_test.go @@ -48,7 +48,7 @@ func TestGetConnectionInfo_UsesHintedProtocolWhenProvided(t *testing.T) { }, } - conn, err := GetConnectionInfo(containers, "instancer.example.com", map[int]string{22: "ssh"}) + conn, err := GetConnectionInfo(containers, "instancer.example.com", map[int]string{22: "ssh"}, false) require.NoError(t, err) assert.Equal(t, "ssh://instancer.example.com:40022\ntcp://instancer.example.com:40080", conn) } @@ -62,11 +62,53 @@ func TestGetConnectionInfo_UsesDockerProtocolWhenNoHint(t *testing.T) { }, } - conn, err := GetConnectionInfo(containers, "instancer.example.com", nil) + conn, err := GetConnectionInfo(containers, "instancer.example.com", nil, false) require.NoError(t, err) assert.Equal(t, "tcp://instancer.example.com:40022", conn) } +func bouglois() []ContainerInfo { + return []ContainerInfo{ + { + Labels: map[string]string{ + "traefik.enable": "true", + "traefik.http.routers.box.rule": "Host(`box-1.challs.example.com`)", + }, + Publishers: []PublisherInfo{ + {Protocol: "tcp", PublishedPort: 39521, TargetPort: 445, URL: "0.0.0.0"}, + {Protocol: "tcp", PublishedPort: 39521, TargetPort: 445, URL: "::"}, + {Protocol: "tcp", PublishedPort: 51040, TargetPort: 22, URL: "0.0.0.0"}, + {Protocol: "tcp", PublishedPort: 48156, TargetPort: 139, URL: "0.0.0.0"}, + }, + }, + } +} + +func TestGetConnectionInfo_HTTPHidesTCPPortsByDefault(t *testing.T) { + conn, err := GetConnectionInfo(bouglois(), "challs.example.com", nil, false) + require.NoError(t, err) + assert.Equal(t, "https://box-1.challs.example.com/", conn) +} + +func TestGetConnectionInfo_ShowTCPPortsListsHTTPThenPorts(t *testing.T) { + conn, err := GetConnectionInfo(bouglois(), "challs.example.com", map[int]string{22: "tcp", 139: "tcp", 445: "tcp"}, true) + require.NoError(t, err) + assert.Equal(t, "https://box-1.challs.example.com/\n"+ + "tcp://challs.example.com:51040\n"+ + "tcp://challs.example.com:48156\n"+ + "tcp://challs.example.com:39521", conn) +} + +func TestGetConnectionInfo_ShowTCPPortsWithoutHTTP(t *testing.T) { + containers := []ContainerInfo{ + {Publishers: []PublisherInfo{{Protocol: "tcp", PublishedPort: 40022, TargetPort: 22, URL: "0.0.0.0"}}}, + {Publishers: []PublisherInfo{{Protocol: "tcp", PublishedPort: 40001, TargetPort: 1, URL: "0.0.0.0"}}}, + } + conn, err := GetConnectionInfo(containers, "challs.example.com", nil, true) + require.NoError(t, err) + assert.Equal(t, "tcp://challs.example.com:40001\ntcp://challs.example.com:40022", conn) +} + func TestNormalizePublishedPorts_RandomizeHostPorts_WhenEnabled(t *testing.T) { params := map[string]interface{}{ "published_ports": []interface{}{ diff --git a/galvanize-instancer/internal/ansible/deployer.go b/galvanize-instancer/internal/ansible/deployer.go index 0ebd7cd..f04f70b 100644 --- a/galvanize-instancer/internal/ansible/deployer.go +++ b/galvanize-instancer/internal/ansible/deployer.go @@ -35,7 +35,7 @@ type AnsibleDeployer struct{} var _ Deployer = (*AnsibleDeployer)(nil) func deploymentKey(chall *challenge.Challenge, teamID string) string { - return chall.Category + "/" + chall.Name + ":" + teamID + return chall.Category + "/" + chall.InstanceKey() + ":" + teamID } func (a *AnsibleDeployer) Deploy(ctx context.Context, conf *config.Config, chall *challenge.Challenge, teamID string) (string, error) { @@ -93,7 +93,7 @@ func (a *AnsibleDeployer) Deploy(ctx context.Context, conf *config.Config, chall return "", fmt.Errorf("no container info found in Ansible results") } - connInfo, err := GetConnectionInfo(containerInfos, conf.Instancer.InstancerHost, protocolHints) + connInfo, err := GetConnectionInfo(containerInfos, conf.Instancer.InstancerHost, protocolHints, chall.ShowTCPPorts) if err != nil { return "", fmt.Errorf("failed to build connection info: %w", err) } diff --git a/galvanize-instancer/internal/ansible/playbook.go b/galvanize-instancer/internal/ansible/playbook.go index 1e55809..d09bc7e 100644 --- a/galvanize-instancer/internal/ansible/playbook.go +++ b/galvanize-instancer/internal/ansible/playbook.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "maps" "path" + "slices" "github.com/28Pollux28/galvanize/internal/challenge" "github.com/28Pollux28/galvanize/internal/docker" @@ -57,7 +58,7 @@ func BuildResourceOverrides(rl config.ResourceLimits) map[string]interface{} { } func PreparePlaybook(conf *config.Config, tag string, challenge *challenge.Challenge, teamID string, params map[string]interface{}) (execute.Executor, *bytes.Buffer) { - composeProject := docker.BuildComposeProject(challenge.Unique, challenge.Category, challenge.Name, teamID) + composeProject := docker.BuildComposeProject(conf.Instancer.ComposeProjectPrefix, challenge.Unique, challenge.Category, challenge.InstanceKey(), teamID) // Ansible playbook options playbookOpts := &playbook.AnsiblePlaybookOptions{ @@ -80,11 +81,17 @@ func PreparePlaybook(conf *config.Config, tag string, challenge *challenge.Chall maps.Copy(playbookOpts.ExtraVars, params) maps.Copy(playbookOpts.ExtraVars, conf.Instancer.ExtraDeploymentParameters) - // Instances started by Galvanize v0.7.1 or earlier used another project - // name. The playbooks' delete tasks also remove a project left under that - // name, so upgrading does not leave running instances behind. - if legacy := docker.LegacyComposeProject(challenge.Unique, challenge.Name, teamID); legacy != composeProject { - playbookOpts.ExtraVars["legacy_compose_project"] = legacy + // Instances started by earlier Galvanize versions used other project + // names. The playbooks' delete tasks also remove projects left under + // those names, so upgrading does not leave running instances behind. + var legacy []string + for _, name := range docker.LegacyComposeProjects(challenge.Unique, challenge.Category, challenge.Name, teamID) { + if name != composeProject && !slices.Contains(legacy, name) { + legacy = append(legacy, name) + } + } + if len(legacy) > 0 { + playbookOpts.ExtraVars["legacy_compose_projects"] = legacy } // Merge resource limits (challenge overrides config defaults) and pass to Ansible diff --git a/galvanize-instancer/internal/challenge/challenge.go b/galvanize-instancer/internal/challenge/challenge.go index 273da03..0e65de4 100644 --- a/galvanize-instancer/internal/challenge/challenge.go +++ b/galvanize-instancer/internal/challenge/challenge.go @@ -13,6 +13,19 @@ import ( "go.uber.org/zap" ) +// isChallengeDefFile reports whether name is a challenge definition file: +// challenge.yml / challenge.yaml, or a numbered variant such as +// challenge-1.yml, so one directory can hold several challenges. +func isChallengeDefFile(name string) bool { + if name == "challenge.yml" || name == "challenge.yaml" { + return true + } + if !strings.HasPrefix(name, "challenge-") { + return false + } + return strings.HasSuffix(name, ".yml") || strings.HasSuffix(name, ".yaml") +} + // composeFileNames lists the standard Docker Compose file names that are // auto-detected next to a challenge.yml, in the order Docker Compose itself // resolves them. @@ -137,11 +150,26 @@ type Challenge struct { PlaybookName string `yaml:"playbook_name"` Type string `yaml:"type"` Unique bool `yaml:"-"` + InstanceGroup string `yaml:"-"` + ShowTCPPorts bool `yaml:"-"` ResourceLimits config.ResourceLimits `yaml:"-"` Dir string `yaml:"-"` DeployParameters map[string]interface{} `yaml:"deploy_parameters"` } +// InstanceKey is the name deployments of this challenge are stored and +// deployed under: deploy_parameters.instance_group when set (so several +// challenge entries share one instance), the challenge name otherwise. +func (c *Challenge) InstanceKey() string { + if c != nil && strings.TrimSpace(c.InstanceGroup) != "" { + return c.InstanceGroup + } + if c == nil { + return "" + } + return c.Name +} + func NewChallengeIndex(baseDir string) (*ChallengeIndex, error) { idx := &ChallengeIndex{ challs: make(map[string]*Challenge), @@ -187,28 +215,28 @@ func (idx *ChallengeIndex) BuildIndex(baseDir string) error { } return nil } - if d.Name() != "challenge.yml" && d.Name() != "challenge.yaml" { + if !isChallengeDefFile(d.Name()) { return nil } - // Parse challenge.yml to get category and name chall, err := parseChallenge(path) if err != nil { skip(path, err.Error()) - return filepath.SkipDir + // nil, not SkipDir: a directory can hold several challenge-*.yml + // files and one bad file must not hide its siblings. + return nil } if chall.Type != "zync" { - return filepath.SkipDir + return nil } key := chall.Category + "/" + chall.Name if first, ok := paths[key]; ok { skip(path, fmt.Sprintf("duplicate of %s (both declare %s)", first, key)) - return filepath.SkipDir + return nil } challs[key] = chall paths[key] = path zap.S().Infof("Registered challenge: %s", key) - - return filepath.SkipDir + return nil }) if err != nil { return fmt.Errorf("index %s: %w", baseDir, err) @@ -232,11 +260,18 @@ func (idx *ChallengeIndex) Get(category, name string) (*Challenge, error) { key := category + "/" + name idx.mu.RLock() defer idx.mu.RUnlock() - chall, ok := idx.challs[key] - if !ok { - return nil, fmt.Errorf("challenge not found: %s", key) + if chall, ok := idx.challs[key]; ok { + return chall, nil } - return chall, nil + for _, chall := range idx.challs { + if !strings.EqualFold(chall.Category, category) { + continue + } + if chall.Name == name || strings.EqualFold(chall.InstanceGroup, name) { + return chall, nil + } + } + return nil, fmt.Errorf("challenge not found: %s", key) } func (idx *ChallengeIndex) GetAllUnique() []*Challenge { @@ -291,6 +326,26 @@ func parseChallenge(challengeFilePath string) (*Challenge, error) { challenge.Unique = true } } + if group := toStringField(challenge.DeployParameters, "instance_group"); group != "" { + challenge.InstanceGroup = group + } + if show, ok := challenge.DeployParameters["show_tcp_ports"]; ok { + if b, ok := show.(bool); ok && b { + challenge.ShowTCPPorts = true + } + } + if _, hasPorts := challenge.DeployParameters["published_ports"]; !hasPorts { + if port, ok := challenge.DeployParameters["port"]; ok && port != nil { + challenge.DeployParameters["published_ports"] = []interface{}{port} + } + } + if challenge.PlaybookName == "http" { + if _, hasHTTP := challenge.DeployParameters["http_port"]; !hasHTTP { + if port, ok := challenge.DeployParameters["port"]; ok && port != nil { + challenge.DeployParameters["http_port"] = port + } + } + } if rl, ok := challenge.DeployParameters["resource_limits"].(map[string]interface{}); ok { challenge.ResourceLimits = config.ResourceLimits{ diff --git a/galvanize-instancer/internal/challenge/challenge_test.go b/galvanize-instancer/internal/challenge/challenge_test.go index 1c28b78..1ad88e9 100644 --- a/galvanize-instancer/internal/challenge/challenge_test.go +++ b/galvanize-instancer/internal/challenge/challenge_test.go @@ -301,13 +301,90 @@ deploy_parameters: idx, err := NewChallengeIndex(dir) require.NoError(t, err) + got, err := idx.Get("Web", "http") + require.NoError(t, err) + assert.Equal(t, "web", got.Category) + _, err = idx.Get("web", "doesnotexist") assert.Error(t, err) assert.Contains(t, err.Error(), "challenge not found") +} - _, err = idx.Get("nonexistent", "http") - assert.Error(t, err) - assert.Contains(t, err.Error(), "challenge not found") +func TestBuildIndex_NumberedChallengeFiles(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "reverse/custom-os", "challenge-1.yml", ` +name: Custom OS 1 +category: reverse +type: zync +playbook_name: tcp +deploy_parameters: + image: custom-os:latest + port: 31337 + unique: true +`) + writeFile(t, dir, "reverse/custom-os", "challenge-2.yml", ` +name: Custom OS 2 +category: reverse +type: zync +playbook_name: tcp +deploy_parameters: + image: custom-os:latest + port: 31337 + unique: true +`) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + one, err := idx.Get("reverse", "Custom OS 1") + require.NoError(t, err) + assert.True(t, one.Unique) + assert.Equal(t, []interface{}{31337}, one.DeployParameters["published_ports"]) + + _, err = idx.Get("reverse", "Custom OS 2") + require.NoError(t, err) + assert.Len(t, idx.GetAll(), 2) +} + +func TestInstanceGroup_SharedKey(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "reverse/custom-os", "challenge-1.yml", ` +name: Custom OS 1 +category: reverse +type: zync +playbook_name: tcp +deploy_parameters: + image: custom-os:latest + port: 31337 + unique: false + instance_group: custom-os +`) + writeFile(t, dir, "reverse/custom-os", "challenge-2.yml", ` +name: Custom OS 2 +category: reverse +type: zync +playbook_name: tcp +deploy_parameters: + image: custom-os:latest + port: 31337 + unique: false + instance_group: custom-os +`) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + one, err := idx.Get("reverse", "Custom OS 1") + require.NoError(t, err) + two, err := idx.Get("reverse", "Custom OS 2") + require.NoError(t, err) + assert.Equal(t, "custom-os", one.InstanceKey()) + assert.Equal(t, two.InstanceKey(), one.InstanceKey()) + assert.False(t, one.Unique) + + byGroup, err := idx.Get("reverse", "custom-os") + require.NoError(t, err) + assert.Equal(t, "custom-os", byGroup.InstanceKey()) } func TestGetAllUnique(t *testing.T) { @@ -548,3 +625,36 @@ deploy_parameters: assert.True(t, chall.Unique, "challenge with deploy_parameters.unique=true should have Unique=true") assert.Equal(t, "unique_web", chall.Name) } + +func TestBuildIndex_ShowTCPPorts(t *testing.T) { + dir := t.TempDir() + + writeChallenge(t, dir, "misc", ` +name: box +category: misc +playbook_name: http +type: zync +deploy_parameters: + show_tcp_ports: true + image: nginx:latest +`) + writeChallenge(t, dir, "web", ` +name: plain +category: web +playbook_name: http +type: zync +deploy_parameters: + image: nginx:latest +`) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + chall, err := idx.Get("misc", "box") + require.NoError(t, err) + assert.True(t, chall.ShowTCPPorts) + + plain, err := idx.Get("web", "plain") + require.NoError(t, err) + assert.False(t, plain.ShowTCPPorts) +} diff --git a/galvanize-instancer/internal/docker/compose.go b/galvanize-instancer/internal/docker/compose.go index 2b6214b..5523207 100644 --- a/galvanize-instancer/internal/docker/compose.go +++ b/galvanize-instancer/internal/docker/compose.go @@ -42,24 +42,41 @@ const projectSuffixLen = 8 // also the instance's subdomain (.). const maxProjectNameLen = 63 +// DefaultComposeProjectPrefix is the readable prefix of instance project +// names when instancer.compose_project_prefix is not set. +const DefaultComposeProjectPrefix = "ctf-event" + // BuildComposeProject returns the Docker Compose project name of a challenge // instance, which also names its Traefik router and subdomain. It is made of -// a readable part (category, challenge name and team), truncated so the whole +// a readable part (prefix, category, challenge name and team), truncated so the whole // name fits a 63-character DNS label, and the first 8 hex characters of a // SHA-1 of the instance's identity. The hash keeps apart instances whose // readable parts are equal: same-named challenges in different categories, // names that only differ in characters sanitization removes, or names cut by // the truncation. -func BuildComposeProject(unique bool, category, challengeName, teamID string) string { - var readable, identity string +// +// prefix comes from instancer.compose_project_prefix and defaults to +// DefaultComposeProjectPrefix. Team instances are named +// "----" and unique instances +// "-global---". The prefix is not part of the +// hashed identity. +func BuildComposeProject(prefix string, unique bool, category, challengeName, teamID string) string { + if prefix == "" { + prefix = DefaultComposeProjectPrefix + } if unique { - readable = "global-" + category + "-" + challengeName - identity = "unique\x00" + category + "\x00" + challengeName - } else { - readable = "polypwn-" + category + "-" + challengeName + "-" + teamID - identity = "team\x00" + category + "\x00" + challengeName + "\x00" + teamID + return hashedProjectName(prefix+"-global-"+category+"-"+challengeName, unique, category, challengeName, teamID) } + return hashedProjectName(prefix+"-"+category+"-"+challengeName+"-"+teamID, unique, category, challengeName, teamID) +} +// hashedProjectName sanitizes and truncates readable, then appends the hash +// of the instance's identity. +func hashedProjectName(readable string, unique bool, category, challengeName, teamID string) string { + identity := "team\x00" + category + "\x00" + challengeName + "\x00" + teamID + if unique { + identity = "unique\x00" + category + "\x00" + challengeName + } sum := sha1.Sum([]byte(identity)) suffix := hex.EncodeToString(sum[:])[:projectSuffixLen] @@ -70,6 +87,22 @@ func BuildComposeProject(unique bool, category, challengeName, teamID string) st return readable + "-" + suffix } +// LegacyComposeProjects returns the project names earlier Galvanize versions +// gave an instance: v0.7.1 and earlier (see LegacyComposeProject), and v0.7.2 +// to v0.7.4, which used a fixed "polypwn-" prefix for team instances and none +// for unique ones. They are kept only so instances started before an upgrade +// can still be terminated. +func LegacyComposeProjects(unique bool, category, challengeName, teamID string) []string { + v074 := "polypwn-" + category + "-" + challengeName + "-" + teamID + if unique { + v074 = "global-" + category + "-" + challengeName + } + return []string{ + LegacyComposeProject(unique, challengeName, teamID), + hashedProjectName(v074, unique, category, challengeName, teamID), + } +} + // LegacyComposeProject returns the project name Galvanize v0.7.1 and earlier // gave an instance. It ignored the category, and its suffix was constant: // sha1.New().Sum(b) appends the hash of nothing to b instead of hashing b, diff --git a/galvanize-instancer/internal/docker/compose_test.go b/galvanize-instancer/internal/docker/compose_test.go index 708fbf7..719f318 100644 --- a/galvanize-instancer/internal/docker/compose_test.go +++ b/galvanize-instancer/internal/docker/compose_test.go @@ -12,32 +12,32 @@ import ( var validProject = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,62}$`) func TestBuildComposeProject_SameNameDifferentCategories(t *testing.T) { - web := BuildComposeProject(false, "web", "login", "team1") - pwn := BuildComposeProject(false, "pwn", "login", "team1") + web := BuildComposeProject("", false, "web", "login", "team1") + pwn := BuildComposeProject("", false, "pwn", "login", "team1") assert.NotEqual(t, web, pwn) - assert.True(t, strings.HasPrefix(web, "polypwn-web-login-team1-"), web) - assert.True(t, strings.HasPrefix(pwn, "polypwn-pwn-login-team1-"), pwn) + assert.True(t, strings.HasPrefix(web, "ctf-event-web-login-team1-"), web) + assert.True(t, strings.HasPrefix(pwn, "ctf-event-pwn-login-team1-"), pwn) assert.NotEqual(t, - BuildComposeProject(true, "web", "login", ""), - BuildComposeProject(true, "pwn", "login", "")) + BuildComposeProject("", true, "web", "login", ""), + BuildComposeProject("", true, "pwn", "login", "")) } func TestBuildComposeProject_Format(t *testing.T) { // The example in data/challenges/example/http/challenge.yml - assert.Equal(t, "polypwn-web-example-http-team1-9448f1e7", BuildComposeProject(false, "web", "example-http", "team1")) + assert.Equal(t, "ctf-event-web-example-http-team1-9448f1e7", BuildComposeProject("", false, "web", "example-http", "team1")) } func TestBuildComposeProject_SuffixDependsOnIdentity(t *testing.T) { - a := BuildComposeProject(false, "web", "login", "team1") - assert.Equal(t, a, BuildComposeProject(false, "web", "login", "team1"), "deterministic") - assert.NotEqual(t, a, BuildComposeProject(false, "web", "login", "team2")) + a := BuildComposeProject("", false, "web", "login", "team1") + assert.Equal(t, a, BuildComposeProject("", false, "web", "login", "team1"), "deterministic") + assert.NotEqual(t, a, BuildComposeProject("", false, "web", "login", "team2")) // Readable parts equal after sanitization: only the hash keeps them apart assert.NotEqual(t, - BuildComposeProject(false, "web", "Login!", "team1"), - BuildComposeProject(false, "web", "login?", "team1")) + BuildComposeProject("", false, "web", "Login!", "team1"), + BuildComposeProject("", false, "web", "login?", "team1")) // The v0.7.1 suffix was always "706f6c" assert.False(t, strings.HasSuffix(a, "-706f6c"), a) @@ -45,15 +45,15 @@ func TestBuildComposeProject_SuffixDependsOnIdentity(t *testing.T) { func TestBuildComposeProject_UniqueAndTeamInstancesDiffer(t *testing.T) { assert.NotEqual(t, - BuildComposeProject(true, "web", "login", ""), - BuildComposeProject(false, "web", "login", "")) - assert.True(t, strings.HasPrefix(BuildComposeProject(true, "web", "login", ""), "global-web-login-")) + BuildComposeProject("", true, "web", "login", ""), + BuildComposeProject("", false, "web", "login", "")) + assert.True(t, strings.HasPrefix(BuildComposeProject("", true, "web", "login", ""), "ctf-event-global-web-login-")) } func TestBuildComposeProject_FitsOneDNSLabel(t *testing.T) { long := strings.Repeat("very-long-challenge-name-", 6) - a := BuildComposeProject(false, "reverse-engineering", long+"a", "team-with-a-long-identifier") - b := BuildComposeProject(false, "reverse-engineering", long+"b", "team-with-a-long-identifier") + a := BuildComposeProject("", false, "reverse-engineering", long+"a", "team-with-a-long-identifier") + b := BuildComposeProject("", false, "reverse-engineering", long+"b", "team-with-a-long-identifier") for _, p := range []string{a, b} { assert.LessOrEqual(t, len(p), 63, p) @@ -65,15 +65,15 @@ func TestBuildComposeProject_FitsOneDNSLabel(t *testing.T) { func TestBuildComposeProject_ValidForAnyName(t *testing.T) { for _, p := range []string{ - BuildComposeProject(false, "Wéb", "Ünïcode Chall", "Team 1"), - BuildComposeProject(false, "", "", ""), - BuildComposeProject(true, "!!!", "???", ""), + BuildComposeProject("", false, "Wéb", "Ünïcode Chall", "Team 1"), + BuildComposeProject("", false, "", "", ""), + BuildComposeProject("", true, "!!!", "???", ""), } { assert.Regexp(t, validProject, p) } // Nothing readable left after sanitization but the prefix: still unique - assert.Regexp(t, `^global-[0-9a-f]{8}$`, BuildComposeProject(true, "中文", "挑战", "")) - assert.NotEqual(t, BuildComposeProject(true, "中文", "挑战", ""), BuildComposeProject(true, "日本", "語", "")) + assert.Regexp(t, `^ctf-event-global-[0-9a-f]{8}$`, BuildComposeProject("", true, "中文", "挑战", "")) + assert.NotEqual(t, BuildComposeProject("", true, "中文", "挑战", ""), BuildComposeProject("", true, "日本", "語", "")) } func TestLegacyComposeProject_MatchesV071(t *testing.T) { @@ -84,6 +84,30 @@ func TestLegacyComposeProject_MatchesV071(t *testing.T) { } func TestLegacyComposeProject_DiffersFromNewName(t *testing.T) { - assert.NotEqual(t, LegacyComposeProject(false, "login", "team1"), BuildComposeProject(false, "web", "login", "team1")) - assert.NotEqual(t, LegacyComposeProject(true, "login", ""), BuildComposeProject(true, "web", "login", "")) + assert.NotEqual(t, LegacyComposeProject(false, "login", "team1"), BuildComposeProject("", false, "web", "login", "team1")) + assert.NotEqual(t, LegacyComposeProject(true, "login", ""), BuildComposeProject("", true, "web", "login", "")) +} + +func TestBuildComposeProject_CustomPrefix(t *testing.T) { + name := BuildComposeProject("unitedctf", false, "web", "login", "1") + assert.True(t, strings.HasPrefix(name, "unitedctf-web-login-1-"), name) + assert.NotContains(t, name, DefaultComposeProjectPrefix) + + global := BuildComposeProject("unitedctf", true, "web", "shared", "") + assert.True(t, strings.HasPrefix(global, "unitedctf-global-web-shared-"), global) +} + +func TestBuildComposeProject_PrefixKeepsIdentityHash(t *testing.T) { + def := BuildComposeProject("", false, "web", "login", "1") + custom := BuildComposeProject("ctf", false, "web", "login", "1") + assert.Equal(t, def[len(def)-8:], custom[len(custom)-8:]) +} + +func TestLegacyComposeProjects_IncludesV074Names(t *testing.T) { + // What Galvanize v0.7.4 named these instances + assert.Contains(t, LegacyComposeProjects(false, "web", "example-http", "team1"), "polypwn-web-example-http-team1-9448f1e7") + unique := LegacyComposeProjects(true, "web", "login", "") + assert.Contains(t, unique, "global-login") + assert.Regexp(t, `^global-web-login-[0-9a-f]{8}$`, unique[1]) + assert.NotContains(t, unique, BuildComposeProject("", true, "web", "login", "")) } diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index 150c956..8b1b4c7 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -47,19 +47,20 @@ type InstancerConfig struct { AnsibleDir string `mapstructure:"ansible_dir"` // Directory where Ansible playbooks are located ChallengeDir string `mapstructure:"challenge_dir"` // Directory where challenge playbooks are stored InstancerHost string `mapstructure:"instancer_host"` // Hostname of the node where challenges will be deployed + ComposeProjectPrefix string `mapstructure:"compose_project_prefix,omitempty"` // Prefix for compose project / instance subdomains (default: "ctf-event") DBPath string `mapstructure:"db_path"` // Path to the database file DeploymentTTL time.Duration `mapstructure:"deployment_ttl,omitempty"` // Time-to-live for deployments DeploymentTTLExtension time.Duration `mapstructure:"deployment_ttl_extension,omitempty"` // Duration to extend deployment TTL DeploymentMaxExtensions int `mapstructure:"deployment_max_extensions,omitempty"` // Maximum number of TTL extensions allowed DeploymentExtensionWindow time.Duration `mapstructure:"deployment_extension_window,omitempty"` // Time window before expiration when extension is allowed - RandomizePublishedPorts bool `mapstructure:"randomize_published_ports,omitempty"` // Randomize host ports for non-fixed TCP published_ports - RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports, included (default: 20000) - RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports, included (default: 60999) + RandomizePublishedPorts bool `mapstructure:"randomize_published_ports,omitempty"` // Randomize host ports for non-fixed TCP published_ports + RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports, included (default: 20000) + RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports, included (default: 60999) MaxConcurrentAnsible int `mapstructure:"max_concurrent_ansible,omitempty"` // Without Redis: maximum concurrent Ansible runs for team requests and expiries (default: 5); admin actions are not limited Redis RedisConfig `mapstructure:"redis"` // Redis configuration for job queue - NumWorkers int `mapstructure:"num_workers,omitempty"` // Number of Ansible workers (default: 10) - Metrics MetricsConfig `mapstructure:"metrics"` // Metrics endpoint configuration - DefaultResourceLimits ResourceLimits `mapstructure:"default_resource_limits"` // Default container resource limits applied to all deployments + NumWorkers int `mapstructure:"num_workers,omitempty"` // Number of Ansible workers (default: 10) + Metrics MetricsConfig `mapstructure:"metrics"` // Metrics endpoint configuration + DefaultResourceLimits ResourceLimits `mapstructure:"default_resource_limits"` // Default container resource limits applied to all deployments } type RedisConfig struct { @@ -77,8 +78,8 @@ type AnsibleConfig struct { // ResourceLimits defines container resource constraints applied via Docker Compose. // All three map to deploy.resources.limits (cpus, memory, pids) in Docker Compose. type ResourceLimits struct { - CPUs string `mapstructure:"cpus" yaml:"cpus,omitempty"` // e.g. "0.5", "1", "2" - Memory string `mapstructure:"memory" yaml:"memory,omitempty"` // e.g. "256M", "512M", "1G" + CPUs string `mapstructure:"cpus" yaml:"cpus,omitempty"` // e.g. "0.5", "1", "2" + Memory string `mapstructure:"memory" yaml:"memory,omitempty"` // e.g. "256M", "512M", "1G" PidsLimit int `mapstructure:"pids_limit" yaml:"pids_limit,omitempty"` // e.g. 256, 512 } diff --git a/galvanize-instancer/pkg/models/deployment.go b/galvanize-instancer/pkg/models/deployment.go index 6ac9c98..823ff97 100755 --- a/galvanize-instancer/pkg/models/deployment.go +++ b/galvanize-instancer/pkg/models/deployment.go @@ -71,9 +71,9 @@ func GetDeployment(db *gorm.DB, category, challengeName, teamID string, lock boo if lock { result = db.Clauses(clause.Locking{ Strength: "UPDATE", - }).Where("category = ? AND challenge_name = ? AND team_id = ?", category, challengeName, teamID).Limit(1).Find(&deployment) + }).Where("LOWER(category) = LOWER(?) AND challenge_name = ? AND team_id = ?", category, challengeName, teamID).Limit(1).Find(&deployment) } else { - result = db.Where("category = ? AND challenge_name = ? AND team_id = ?", category, challengeName, teamID).Limit(1).Find(&deployment) + result = db.Where("LOWER(category) = LOWER(?) AND challenge_name = ? AND team_id = ?", category, challengeName, teamID).Limit(1).Find(&deployment) } if result.Error != nil { return nil, result.Error @@ -90,9 +90,9 @@ func GetUniqueDeployment(db *gorm.DB, category, challengeName string, lock bool) if lock { result = db.Clauses(clause.Locking{ Strength: "UPDATE", - }).Where("category = ? AND challenge_name = ? AND team_id is NULL", category, challengeName).Limit(1).Find(&deployment) + }).Where("LOWER(category) = LOWER(?) AND challenge_name = ? AND team_id is NULL", category, challengeName).Limit(1).Find(&deployment) } else { - result = db.Where("Category = ? AND challenge_name = ? AND team_id is NULL", category, challengeName).Limit(1).Find(&deployment) + result = db.Where("LOWER(category) = LOWER(?) AND challenge_name = ? AND team_id is NULL", category, challengeName).Limit(1).Find(&deployment) } if result.Error != nil { return nil, result.Error diff --git a/galvanize-instancer/pkg/restserver.go b/galvanize-instancer/pkg/restserver.go index 8d2a564..5749b7e 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -174,12 +174,13 @@ func (s *Server) DeployInstance(ctx echo.Context) error { zap.S().Errorf("Attempt to deploy unique challenge %s for team %s", req.ChallengeName, claims.TeamID) return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")}) } - id := instanceLockKey(chall.Category, chall.Name, claims.TeamID) + instanceKey := chall.InstanceKey() + id := instanceLockKey(chall.Category, instanceKey, claims.TeamID) s.kmu.LockKey(id) - existingDeployment, err := models.GetDeployment(s.db, chall.Category, chall.Name, claims.TeamID, false) + existingDeployment, err := models.GetDeployment(s.db, chall.Category, instanceKey, claims.TeamID, false) if err == nil && existingDeployment != nil { _ = s.kmu.UnlockKey(id) - pkgmetrics.DeployConflictTotal.WithLabelValues(chall.Category, chall.Name).Inc() + pkgmetrics.DeployConflictTotal.WithLabelValues(chall.Category, instanceKey).Inc() return ctx.JSON(409, api.Error{Message: utils.Ptr("Challenge already deployed for this team")}) } if err != nil && !errors.Is(err, models.ErrNotFound) { @@ -189,7 +190,7 @@ func (s *Server) DeployInstance(ctx echo.Context) error { } conf := s.confProv.GetConfig() - deployment, err := models.CreateDeployment(s.db, chall.Name, claims.TeamID, chall.Category, conf.Instancer.DeploymentTTL, conf.Instancer.DeploymentMaxExtensions) + deployment, err := models.CreateDeployment(s.db, instanceKey, claims.TeamID, chall.Category, conf.Instancer.DeploymentTTL, conf.Instancer.DeploymentMaxExtensions) if err != nil { _ = s.kmu.UnlockKey(id) zap.S().Errorf("Failed to create deployment record: %v", err) @@ -199,7 +200,7 @@ func (s *Server) DeployInstance(ctx echo.Context) error { // If we have a job queue, enqueue the deploy job if s.jobQueue != nil { - job := worker.NewDeployJob(chall.Category, chall.Name, claims.TeamID, deployment.ID) + job := worker.NewDeployJob(chall.Category, instanceKey, claims.TeamID, deployment.ID) if err := s.jobQueue.Enqueue(ctx.Request().Context(), job); err != nil { zap.S().Errorf("Failed to enqueue deploy job: %v", err) _ = models.UpdateDeploymentStatus(s.db, deployment, models.DeploymentStatusError, "", "Failed to queue deployment") @@ -258,10 +259,10 @@ func (s *Server) GetInstanceStatus(ctx echo.Context) error { var deployment *models.Deployment if chall.Unique { zap.S().Debugf("Status request received for challenge %s", chall.Name) - deployment, err = models.GetUniqueDeployment(s.db, chall.Category, chall.Name, false) + deployment, err = models.GetUniqueDeployment(s.db, chall.Category, chall.InstanceKey(), false) } else { zap.S().Debugf("Status request received for challenge %s for team %s", claims.ChallengeName, claims.TeamID) - deployment, err = models.GetDeployment(s.db, chall.Category, chall.Name, claims.TeamID, false) + deployment, err = models.GetDeployment(s.db, chall.Category, chall.InstanceKey(), claims.TeamID, false) } if err != nil { if errors.Is(err, models.ErrNotFound) { @@ -314,7 +315,11 @@ func (s *Server) ExtendInstance(ctx echo.Context) error { } zap.S().Debugf("Extend request received for challenge %s for team %s", claims.ChallengeName, claims.TeamID) - d, err := models.GetDeployment(s.db, claims.Category, claims.ChallengeName, claims.TeamID, false) + chall, err := s.challIdx.Get(claims.Category, claims.ChallengeName) + if err != nil { + return ctx.JSON(400, api.Error{Message: utils.Ptr("Invalid challenge")}) + } + d, err := models.GetDeployment(s.db, chall.Category, chall.InstanceKey(), claims.TeamID, false) if err != nil { if errors.Is(err, models.ErrNotFound) { return ctx.NoContent(404) @@ -372,8 +377,13 @@ func (s *Server) TerminateInstance(ctx echo.Context) error { return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")}) } + chall, challErr := s.challIdx.Get(claims.Category, claims.ChallengeName) + if challErr != nil { + return ctx.JSON(400, api.Error{Message: utils.Ptr("Invalid challenge")}) + } + tx := s.db.Begin() - deployment, err := models.GetDeployment(tx, claims.Category, claims.ChallengeName, claims.TeamID, true) + deployment, err := models.GetDeployment(tx, chall.Category, chall.InstanceKey(), claims.TeamID, true) if err != nil { tx.Rollback() if errors.Is(err, models.ErrNotFound) { @@ -396,12 +406,7 @@ func (s *Server) TerminateInstance(ctx echo.Context) error { // If we have a job queue, enqueue the terminate job if s.jobQueue != nil { - chall, challErr := s.challIdx.Get(claims.Category, claims.ChallengeName) - if challErr != nil { - zap.S().Errorf("Failed to get challenge for terminate: %v", challErr) - return ctx.JSON(500, api.Error{Message: utils.HTTP500Debug("Failed to get challenge info")}) - } - job := worker.NewTerminateJob(chall.Category, chall.Name, claims.TeamID, deployment.ID) + job := worker.NewTerminateJob(chall.Category, chall.InstanceKey(), claims.TeamID, deployment.ID) if err := s.jobQueue.Enqueue(ctx.Request().Context(), job); err != nil { zap.S().Errorf("Failed to enqueue terminate job: %v", err) _ = models.UpdateDeploymentStatus(s.db, deployment, models.DeploymentStatusError, "", "Failed to queue termination") diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 1c7c2ec..68db65a 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -109,12 +109,12 @@ func (s *Server) DeployAdminInstance(ctx echo.Context) error { return ctx.JSON(400, api.Error{Message: utils.Ptr("Challenge is not unique")}) } - id := instanceLockKey(chall.Category, chall.Name, "") + id := instanceLockKey(chall.Category, chall.InstanceKey(), "") s.kmu.LockKey(id) - existingDeployment, err := models.GetUniqueDeployment(s.db, chall.Category, chall.Name, false) + existingDeployment, err := models.GetUniqueDeployment(s.db, chall.Category, chall.InstanceKey(), false) if err == nil && existingDeployment != nil { _ = s.kmu.UnlockKey(id) - pkgmetrics.DeployConflictTotal.WithLabelValues(chall.Category, chall.Name).Inc() + pkgmetrics.DeployConflictTotal.WithLabelValues(chall.Category, chall.InstanceKey()).Inc() return ctx.JSON(409, api.Error{Message: utils.Ptr("Challenge already deployed")}) } if err != nil && !errors.Is(err, models.ErrNotFound) { @@ -124,7 +124,7 @@ func (s *Server) DeployAdminInstance(ctx echo.Context) error { } s.wg.Add(1) - _, err = models.CreateUniqueDeployment(s.db, chall.Name, chall.Category) + _, err = models.CreateUniqueDeployment(s.db, chall.InstanceKey(), chall.Category) if err != nil { _ = s.kmu.UnlockKey(id) s.wg.Done() @@ -136,7 +136,7 @@ func (s *Server) DeployAdminInstance(ctx echo.Context) error { conf := s.confProv.GetConfig() go func() { defer s.wg.Done() - deployment, dbErr := models.GetUniqueDeployment(s.db, chall.Category, chall.Name, false) + deployment, dbErr := models.GetUniqueDeployment(s.db, chall.Category, chall.InstanceKey(), false) if dbErr != nil { zap.S().Errorf("Failed to get deployment for update: %v", dbErr) return @@ -187,9 +187,14 @@ func (s *Server) TerminateAdminInstance(ctx echo.Context) error { } zap.S().Infof("Admin terminate request received for challenge %s", req.ChallengeName) + instanceKey := req.ChallengeName + if chall, err := s.challIdx.Get(req.Category, req.ChallengeName); err == nil { + instanceKey = chall.InstanceKey() + } + s.wg.Add(1) tx := s.db.Begin() - deployment, err := models.GetUniqueDeployment(tx, req.Category, req.ChallengeName, true) + deployment, err := models.GetUniqueDeployment(tx, req.Category, instanceKey, true) if err != nil { tx.Rollback() s.wg.Done() @@ -258,7 +263,7 @@ func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { for _, chall := range uniqueChallenges { // Check if already deployed - existingDeployment, err := models.GetUniqueDeployment(s.db, chall.Category, chall.Name, false) + existingDeployment, err := models.GetUniqueDeployment(s.db, chall.Category, chall.InstanceKey(), false) if err == nil && existingDeployment != nil { zap.S().Debugf("Challenge %s already deployed, skipping", chall.Name) continue @@ -266,7 +271,7 @@ func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { // Create deployment record s.wg.Add(1) - _, err = models.CreateUniqueDeployment(s.db, chall.Name, chall.Category) + _, err = models.CreateUniqueDeployment(s.db, chall.InstanceKey(), chall.Category) if err != nil { s.wg.Done() zap.S().Errorf("Failed to create deployment record for %s: %v", chall.Name, err) @@ -282,7 +287,7 @@ func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { // Deploy in goroutine go func(ch *challenge.Challenge) { defer s.wg.Done() - deployment, dbErr := models.GetUniqueDeployment(s.db, ch.Category, ch.Name, false) + deployment, dbErr := models.GetUniqueDeployment(s.db, ch.Category, ch.InstanceKey(), false) if dbErr != nil { zap.S().Errorf("Failed to get deployment for %s: %v", ch.Name, dbErr) return diff --git a/monitoring/docker-stats-exporter/Dockerfile b/monitoring/docker-stats-exporter/Dockerfile new file mode 100644 index 0000000..1f18acb --- /dev/null +++ b/monitoring/docker-stats-exporter/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.12-alpine +WORKDIR /app +COPY exporter.py /app/exporter.py +EXPOSE 8080 +CMD ["python", "-u", "/app/exporter.py"] diff --git a/monitoring/docker-stats-exporter/exporter.py b/monitoring/docker-stats-exporter/exporter.py new file mode 100644 index 0000000..6bdf6f6 --- /dev/null +++ b/monitoring/docker-stats-exporter/exporter.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +import json +import os +import socket +import http.client +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DOCKER_SOCK = os.environ.get("DOCKER_SOCK", "/var/run/docker.sock") +LISTEN = os.environ.get("LISTEN_ADDRESS", "0.0.0.0:8080") + + +class DockerUnixConnection(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost") + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(5) + self.sock.connect(self.path) + + +def docker(path): + conn = DockerUnixConnection(DOCKER_SOCK) + try: + conn.request("GET", path) + resp = conn.getresponse() + body = resp.read() + if resp.status >= 400: + raise RuntimeError(f"docker {resp.status} {path}: {body[:200]!r}") + return json.loads(body) if body else {} + finally: + conn.close() + + +def num(value): + try: + return float(value or 0) + except (TypeError, ValueError): + return 0.0 + + +def collect(): + lines = [ + "# HELP docker_container_network_receive_bytes_total Network bytes received by the container", + "# TYPE docker_container_network_receive_bytes_total counter", + "# HELP docker_container_network_transmit_bytes_total Network bytes sent by the container", + "# TYPE docker_container_network_transmit_bytes_total counter", + "# HELP docker_container_memory_usage_bytes Memory usage of the container", + "# TYPE docker_container_memory_usage_bytes gauge", + "# HELP docker_container_cpu_usage_seconds_total Cumulative CPU time consumed", + "# TYPE docker_container_cpu_usage_seconds_total counter", + ] + containers = docker("/containers/json?all=false") + for c in containers: + name = (c.get("Names") or ["/unknown"])[0].lstrip("/") + labels = c.get("Labels") or {} + project = labels.get("com.docker.compose.project", "") + service = labels.get("com.docker.compose.service", "") + cid = (c.get("Id") or "")[:12] + try: + stats = docker(f"/containers/{c['Id']}/stats?stream=false&one-shot=true") + except Exception: + continue + rx = tx = 0.0 + for iface, net in (stats.get("networks") or {}).items(): + if iface in ("lo", "tunl0"): + continue + rx += num(net.get("rx_bytes")) + tx += num(net.get("tx_bytes")) + mem = num((stats.get("memory_stats") or {}).get("usage")) + cpu = num(((stats.get("cpu_stats") or {}).get("cpu_usage") or {}).get("total_usage")) / 1e9 + label = ( + f'name="{name}",id="{cid}",' + f'compose_project="{project}",compose_service="{service}"' + ) + lines.append(f"docker_container_network_receive_bytes_total{{{label}}} {rx}") + lines.append(f"docker_container_network_transmit_bytes_total{{{label}}} {tx}") + lines.append(f"docker_container_memory_usage_bytes{{{label}}} {mem}") + lines.append(f"docker_container_cpu_usage_seconds_total{{{label}}} {cpu}") + return "\n".join(lines) + "\n" + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, fmt, *args): + return + + def do_GET(self): + if self.path not in ("/metrics", "/"): + self.send_error(404) + return + try: + body = collect().encode() + self.send_response(200) + self.send_header("Content-Type", "text/plain; version=0.0.4") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + except Exception as exc: + err = f"exporter_error {exc}\n".encode() + self.send_response(500) + self.send_header("Content-Type", "text/plain") + self.send_header("Content-Length", str(len(err))) + self.end_headers() + self.wfile.write(err) + + +def main(): + host, port = LISTEN.rsplit(":", 1) + server = ThreadingHTTPServer((host, int(port)), Handler) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/monitoring/grafana/dashboards/ai-usage.json b/monitoring/grafana/dashboards/ai-usage.json new file mode 100644 index 0000000..01768b4 --- /dev/null +++ b/monitoring/grafana/dashboards/ai-usage.json @@ -0,0 +1,530 @@ +{ + "uid": "ai-usage", + "title": "AI / bot usage", + "description": "HTTP User-Agent + path from Traefik. TCP: inbound connect + first payload on published challenge ports.", + "tags": [ + "unitedctf", + "ai", + "accesslog" + ], + "timezone": "browser", + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "schemaVersion": 39, + "version": 5, + "templating": { + "list": [] + }, + "panels": [ + { + "id": 3, + "type": "stat", + "title": "All HTTP (1h)", + "gridPos": { + "x": 0, + "y": 0, + "w": 6, + "h": 4 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "blue", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "area" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "sum(count_over_time({job=\"worker-traefik-access\"} [1h]))", + "queryType": "instant" + } + ] + }, + { + "id": 1, + "type": "stat", + "title": "AI / LLM User-Agents (1h)", + "gridPos": { + "x": 6, + "y": 0, + "w": 6, + "h": 4 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 1 + }, + { + "color": "red", + "value": 10 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "sum(count_over_time({job=\"worker-traefik-access\"} |~ \"(?i)chatgpt|gptbot|oai-searchbot|claude|anthropic|openai.com/bot|perplexity|gemini|google-extended|bytespider|copilot|cursor/|browser-use|playwright|puppeteer|headlesschrome\" !~ \"(?i)ClaudeBot/|GPTBot/|OAI-SearchBot/\" !~ \"216\\\\.73\\\\.21[67]\\\\.\" [1h]))", + "queryType": "instant" + } + ] + }, + { + "id": 2, + "type": "stat", + "title": "Phishy / recon paths (1h)", + "gridPos": { + "x": 12, + "y": 0, + "w": 6, + "h": 4 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 1 + }, + { + "color": "red", + "value": 20 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "sum(count_over_time({job=\"worker-traefik-access\"} |~ \"(?i)/\\\\.env|/\\\\.git|/wp-admin|/wp-login|/phpmyadmin|/flag|/actuator|/server-status|/cgi-bin\" [1h]))", + "queryType": "instant" + } + ] + }, + { + "id": 7, + "type": "stat", + "title": "TCP events (1h)", + "gridPos": { + "x": 18, + "y": 0, + "w": 6, + "h": 4 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "blue", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "area" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "sum(count_over_time({job=\"worker-tcp-access\"} [1h]))", + "queryType": "instant" + } + ] + }, + { + "id": 6, + "type": "logs", + "title": "All challenge HTTP (method, host, path, User-Agent)", + "description": "Every Traefik request. If this panel is empty, logs are not arriving. Click a line for full JSON.", + "gridPos": { + "x": 0, + "y": 4, + "w": 24, + "h": 12 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "{job=\"worker-traefik-access\"} | json | line_format \"{{.RequestMethod}} {{.RequestHost}}{{.RequestPath}} [{{.DownstreamStatus}}] {{.request_User_Agent}} ({{.ClientHost}})\"", + "queryType": "range", + "maxLines": 200 + } + ] + }, + { + "id": 4, + "type": "logs", + "title": "Likely AI / LLM User-Agents", + "description": "Raw-line match on ChatGPT, Claude, Gemini, Perplexity, Cursor, Playwright, Puppeteer, headless Chrome. Official crawlers excluded: ClaudeBot, GPTBot, OAI-SearchBot. ChatGPT-User / Claude-User (model fetch on behalf of a person) still show. CEO Exchange's intended solver is Playwright.", + "gridPos": { + "x": 0, + "y": 16, + "w": 24, + "h": 10 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "{job=\"worker-traefik-access\"} |~ \"(?i)chatgpt|gptbot|oai-searchbot|claude|anthropic|openai.com/bot|perplexity|gemini|google-extended|bytespider|copilot|cursor/|browser-use|playwright|puppeteer|headlesschrome\" !~ \"(?i)ClaudeBot/|GPTBot/|OAI-SearchBot/\" !~ \"216\\\\.73\\\\.21[67]\\\\.\" | json | line_format \"{{.RequestMethod}} {{.RequestHost}}{{.RequestPath}} [{{.DownstreamStatus}}] {{.request_User_Agent}} ({{.ClientHost}})\"", + "queryType": "range", + "maxLines": 200 + } + ] + }, + { + "id": 5, + "type": "logs", + "title": "Phishy / recon paths", + "description": ".env, .git, wp-admin, flag, actuator, metadata. Internet scanners hit these too, not only AI.", + "gridPos": { + "x": 0, + "y": 26, + "w": 24, + "h": 9 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "{job=\"worker-traefik-access\"} |~ \"(?i)/\\\\.env|/\\\\.git|/wp-admin|/wp-login|/phpmyadmin|/flag|/actuator|/server-status|/cgi-bin\" | json | line_format \"{{.RequestMethod}} {{.RequestHost}}{{.RequestPath}} [{{.DownstreamStatus}}] {{.request_User_Agent}} ({{.ClientHost}})\"", + "queryType": "range", + "maxLines": 200 + } + ] + }, + { + "id": 9, + "type": "logs", + "title": "TCP payloads that look like HTTP / AI / scripts", + "gridPos": { + "x": 0, + "y": 35, + "w": 24, + "h": 9 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "{job=\"worker-tcp-access\"} |~ \"(?i)GET |POST |User-Agent|chatgpt|claude|openai|anthropic|playwright|puppeteer|curl/|python-requests|httpx\" | json | line_format \"{{.container}}:{{.DstPort}} {{.event}} {{.preview}} ({{.ClientHost}})\"", + "queryType": "range", + "maxLines": 200 + } + ] + }, + { + "id": 10, + "type": "logs", + "title": "All TCP challenge traffic (connect + first payload)", + "description": "Inbound SYN and first 256 payload bytes to unitedctf-* published ports. Click a line for hex.", + "gridPos": { + "x": 0, + "y": 44, + "w": 24, + "h": 10 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "{job=\"worker-tcp-access\"} | json | line_format \"{{.container}}:{{.DstPort}} {{.event}} {{.preview}} ({{.ClientHost}})\"", + "queryType": "range", + "maxLines": 200 + } + ] + }, + { + "id": 11, + "type": "stat", + "title": "Markdown links pasted into a challenge (24h)", + "description": "Request path contains ](http, the Markdown link syntax AI chats produce. A player copied a payload or link out of a chat answer that knew their instance URL (H4rshpv, File Library, 2026-10-10).", + "gridPos": { + "x": 0, + "y": 54, + "w": 6, + "h": 8 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "sum(count_over_time({job=\"worker-traefik-access\"} |~ `(?i)(\\]|%5d)(\\(|%28)https?(:|%3a)` [24h]))", + "queryType": "instant" + } + ] + }, + { + "id": 12, + "type": "logs", + "title": "Markdown links pasted into a challenge \u2014 AI chat copy-paste", + "description": "Instance owner = number in the hostname. Check the client IP against the owner's CTFd IPs before acting.", + "gridPos": { + "x": 6, + "y": 54, + "w": 18, + "h": 8 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "options": { + "showTime": true, + "showLabels": false, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending", + "dedupStrategy": "none" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "editorMode": "code", + "expr": "{job=\"worker-traefik-access\"} |~ `(?i)(\\]|%5d)(\\(|%28)https?(:|%3a)` | json | line_format \"{{.RequestMethod}} {{.RequestHost}}{{.RequestPath}} [{{.DownstreamStatus}}] {{.request_User_Agent}} ({{.ClientHost}})\"", + "queryType": "range", + "maxLines": 200 + } + ] + } + ] +} \ No newline at end of file diff --git a/monitoring/grafana/dashboards/worker-traffic.json b/monitoring/grafana/dashboards/worker-traffic.json new file mode 100644 index 0000000..b32251e --- /dev/null +++ b/monitoring/grafana/dashboards/worker-traffic.json @@ -0,0 +1,236 @@ +{ + "uid": "worker-traffic", + "title": "Challenge container traffic", + "description": "Incoming and outgoing traffic for UnitedCTF challenge containers on the worker", + "tags": ["unitedctf", "worker", "traffic"], + "timezone": "browser", + "refresh": "30s", + "time": { "from": "now-1h", "to": "now" }, + "timepicker": {}, + "schemaVersion": 38, + "version": 1, + "templating": { + "list": [ + { + "name": "datasource", + "type": "datasource", + "label": "Datasource", + "pluginId": "prometheus", + "query": "prometheus", + "current": {}, + "hide": 0, + "includeAll": false, + "multi": false, + "refresh": 1 + } + ] + }, + "panels": [ + { + "id": 1, + "type": "stat", + "title": "RX in (players → containers)", + "gridPos": { "x": 0, "y": 0, "w": 6, "h": 4 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "Bps", "color": { "mode": "thresholds" }, "thresholds": { "mode": "absolute", "steps": [{ "color": "blue", "value": null }] } }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background", "graphMode": "area" }, + "targets": [ + { + "expr": "sum(rate(docker_container_network_receive_bytes_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m])) or vector(0)", + "legendFormat": "RX", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 2, + "type": "stat", + "title": "TX out (containers → players / internet)", + "gridPos": { "x": 6, "y": 0, "w": 6, "h": 4 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "Bps", "color": { "mode": "thresholds" }, "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] } }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background", "graphMode": "area" }, + "targets": [ + { + "expr": "sum(rate(docker_container_network_transmit_bytes_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m])) or vector(0)", + "legendFormat": "TX", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 3, + "type": "stat", + "title": "HTTP requests (Traefik)", + "gridPos": { "x": 12, "y": 0, "w": 6, "h": 4 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "reqps", "color": { "mode": "thresholds" }, "thresholds": { "mode": "absolute", "steps": [{ "color": "purple", "value": null }] } }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background", "graphMode": "area" }, + "targets": [ + { + "expr": "sum(rate(traefik_entrypoint_requests_total{job=\"worker-traefik\",entrypoint=~\"web|websecure\"}[5m])) or vector(0)", + "legendFormat": "HTTP", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 4, + "type": "stat", + "title": "Live challenge containers", + "gridPos": { "x": 18, "y": 0, "w": 6, "h": 4 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "short", "color": { "mode": "thresholds" }, "thresholds": { "mode": "absolute", "steps": [{ "color": "blue", "value": null }] } }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background", "graphMode": "none" }, + "targets": [ + { + "expr": "count(count by (name) (docker_container_memory_usage_bytes{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"})) or vector(0)", + "legendFormat": "containers", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 5, + "type": "timeseries", + "title": "Traffic in / out (all challenge containers)", + "gridPos": { "x": 0, "y": 4, "w": 16, "h": 9 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "Bps", "custom": { "fillOpacity": 15, "lineWidth": 2 } }, + "overrides": [] + }, + "options": { "legend": { "displayMode": "list", "placement": "bottom" } }, + "targets": [ + { + "expr": "sum(rate(docker_container_network_receive_bytes_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m]))", + "legendFormat": "RX in", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + }, + { + "expr": "sum(rate(docker_container_network_transmit_bytes_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m]))", + "legendFormat": "TX out", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "B" + } + ] + }, + { + "id": 6, + "type": "timeseries", + "title": "HTTP requests by entrypoint", + "gridPos": { "x": 16, "y": 4, "w": 8, "h": 9 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "reqps", "custom": { "fillOpacity": 15, "lineWidth": 2 } }, + "overrides": [] + }, + "options": { "legend": { "displayMode": "list", "placement": "bottom" } }, + "targets": [ + { + "expr": "sum by (entrypoint) (rate(traefik_entrypoint_requests_total{job=\"worker-traefik\",entrypoint=~\"web|websecure\"}[5m]))", + "legendFormat": "{{entrypoint}}", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 7, + "type": "timeseries", + "title": "RX in by container", + "gridPos": { "x": 0, "y": 13, "w": 12, "h": 10 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "Bps", "custom": { "fillOpacity": 10, "lineWidth": 1 } }, + "overrides": [] + }, + "options": { "legend": { "displayMode": "table", "placement": "right", "calcs": ["mean", "max"] } }, + "targets": [ + { + "expr": "sum by (name) (rate(docker_container_network_receive_bytes_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m]))", + "legendFormat": "{{name}}", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 8, + "type": "timeseries", + "title": "TX out by container", + "gridPos": { "x": 12, "y": 13, "w": 12, "h": 10 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "Bps", "custom": { "fillOpacity": 10, "lineWidth": 1 } }, + "overrides": [] + }, + "options": { "legend": { "displayMode": "table", "placement": "right", "calcs": ["mean", "max"] } }, + "targets": [ + { + "expr": "sum by (name) (rate(docker_container_network_transmit_bytes_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m]))", + "legendFormat": "{{name}}", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 9, + "type": "timeseries", + "title": "CPU (challenge containers)", + "gridPos": { "x": 0, "y": 23, "w": 12, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "percentunit", "custom": { "fillOpacity": 10, "lineWidth": 1 }, "min": 0 }, + "overrides": [] + }, + "options": { "legend": { "displayMode": "table", "placement": "right", "calcs": ["mean", "max"] } }, + "targets": [ + { + "expr": "sum by (name) (rate(docker_container_cpu_usage_seconds_total{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"}[5m]))", + "legendFormat": "{{name}}", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + }, + { + "id": 10, + "type": "timeseries", + "title": "Memory working set", + "gridPos": { "x": 12, "y": 23, "w": 12, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "fieldConfig": { + "defaults": { "unit": "bytes", "custom": { "fillOpacity": 10, "lineWidth": 1 } }, + "overrides": [] + }, + "options": { "legend": { "displayMode": "table", "placement": "right", "calcs": ["lastNotNull", "max"] } }, + "targets": [ + { + "expr": "sum by (name) (docker_container_memory_usage_bytes{job=\"worker-cadvisor\",name=~\"unitedctf-.+\"})", + "legendFormat": "{{name}}", + "datasource": { "type": "prometheus", "uid": "${datasource}" }, + "refId": "A" + } + ] + } + ] +} diff --git a/monitoring/grafana/provisioning/datasources/loki.yml b/monitoring/grafana/provisioning/datasources/loki.yml new file mode 100644 index 0000000..1dd6b6b --- /dev/null +++ b/monitoring/grafana/provisioning/datasources/loki.yml @@ -0,0 +1,11 @@ +apiVersion: 1 +datasources: + - name: Loki + type: loki + access: proxy + url: http://loki:3100 + uid: loki + isDefault: false + editable: false + jsonData: + maxLines: 1000 diff --git a/monitoring/loki.yml b/monitoring/loki.yml new file mode 100644 index 0000000..041456f --- /dev/null +++ b/monitoring/loki.yml @@ -0,0 +1,43 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2020-10-24 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + reject_old_samples: true + reject_old_samples_max_age: 168h + retention_period: 168h + allow_structured_metadata: false + volume_enabled: true + max_query_series: 500 + ingestion_rate_mb: 8 + ingestion_burst_size_mb: 16 + +compactor: + working_directory: /loki/compactor + compaction_interval: 10m + retention_enabled: true + retention_delete_delay: 2h + delete_request_store: filesystem diff --git a/monitoring/prometheus.yml b/monitoring/prometheus.yml index 33569b1..49cc2c7 100644 --- a/monitoring/prometheus.yml +++ b/monitoring/prometheus.yml @@ -11,3 +11,26 @@ scrape_configs: # basic_auth: # username: prometheus # password: + + # Worker challenge traffic. Ports are UFW-restricted to the control plane. + # docker-stats-exporter (monitoring/docker-stats-exporter): per-container + # CPU, memory and network counters with cAdvisor-style metric names. + - job_name: worker-cadvisor + scrape_interval: 15s + static_configs: + - targets: + - :8088 + labels: + role: worker + metric_relabel_configs: + - source_labels: [__name__] + regex: docker_container_.+ + action: keep + + - job_name: worker-traefik + scrape_interval: 15s + static_configs: + - targets: + - :8082 + labels: + role: worker diff --git a/monitoring/promtail.yml b/monitoring/promtail.yml new file mode 100644 index 0000000..64f93d6 --- /dev/null +++ b/monitoring/promtail.yml @@ -0,0 +1,53 @@ +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +positions: + filename: /tmp/positions.yaml + +clients: + - url: http://:3100/loki/api/v1/push + backoff_config: + max_retries: 10 + +scrape_configs: + - job_name: traefik-access + static_configs: + - targets: + - localhost + labels: + job: worker-traefik-access + host: worker + __path__: /var/log/traefik/access.log + pipeline_stages: + - drop: + expression: '^[^\{]' + - json: + expressions: + RequestHost: RequestHost + RequestPath: RequestPath + RequestMethod: RequestMethod + ClientHost: ClientHost + DownstreamStatus: DownstreamStatus + - labels: + RequestMethod: + + - job_name: tcp-access + static_configs: + - targets: + - localhost + labels: + job: worker-tcp-access + host: worker + __path__: /var/log/tcp-access/access.log + pipeline_stages: + - drop: + expression: '^[^\{]' + - json: + expressions: + ClientHost: ClientHost + DstPort: DstPort + container: container + event: event + - labels: + event: diff --git a/monitoring/tcp-access-logger/Dockerfile b/monitoring/tcp-access-logger/Dockerfile new file mode 100644 index 0000000..8dfa73f --- /dev/null +++ b/monitoring/tcp-access-logger/Dockerfile @@ -0,0 +1,4 @@ +FROM python:3.12-alpine +WORKDIR /app +COPY logger.py /app/logger.py +CMD ["python", "-u", "/app/logger.py"] diff --git a/monitoring/tcp-access-logger/logger.py b/monitoring/tcp-access-logger/logger.py new file mode 100644 index 0000000..d9a368d --- /dev/null +++ b/monitoring/tcp-access-logger/logger.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Log inbound TCP to published challenge ports (connect + first payload).""" +import json +import os +import socket +import struct +import time +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path + +DOCKER_SOCK = os.environ.get("DOCKER_SOCK", "/var/run/docker.sock") +IFACE = os.environ.get("CAPTURE_IFACE", "eth0") +LOG_PATH = Path(os.environ.get("LOG_PATH", "/var/log/tcp-access/access.log")) +MAX_PREVIEW = int(os.environ.get("MAX_PREVIEW", "256")) +MAX_EVENTS_PER_FLOW = int(os.environ.get("MAX_EVENTS_PER_FLOW", "8")) +FLOW_TTL = int(os.environ.get("FLOW_TTL", "120")) +PORT_REFRESH = float(os.environ.get("PORT_REFRESH", "4")) +SKIP_PORTS = {22, 80, 443, 8082, 8088, 2375, 2376, 9080, 3100} + +ETH_P_ALL = 3 +ETH_P_IP = 0x0800 +ETH_P_IPV6 = 0x86DD + + +class DockerUnixConnection: + def __init__(self, path): + self.path = path + + def get(self, url): + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(5) + sock.connect(self.path) + try: + req = f"GET {url} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" + sock.sendall(req.encode()) + buf = b"" + while True: + chunk = sock.recv(65536) + if not chunk: + break + buf += chunk + finally: + sock.close() + head, _, body = buf.partition(b"\r\n\r\n") + if b" 200 " not in head.split(b"\r\n", 1)[0]: + raise RuntimeError(head.split(b"\r\n", 1)[0].decode("latin1", "replace")) + if b"chunked" in head.lower(): + body = _unchunk(body) + return json.loads(body.decode()) + + +def _unchunk(data): + out = b"" + while data: + line, _, rest = data.partition(b"\r\n") + try: + n = int(line.split(b";", 1)[0], 16) + except ValueError: + break + if n == 0: + break + out += rest[:n] + data = rest[n + 2 :] + return out + + +def docker_ports(): + mapping = {} + try: + containers = DockerUnixConnection(DOCKER_SOCK).get("/containers/json?all=false") + except Exception as exc: + print(f"docker port map failed: {exc}", flush=True) + return mapping + for c in containers: + name = (c.get("Names") or ["/unknown"])[0].lstrip("/") + if not name.startswith("unitedctf-"): + continue + for p in c.get("Ports") or []: + pub = p.get("PublicPort") + if pub and p.get("Type", "tcp") == "tcp" and pub not in SKIP_PORTS: + mapping[int(pub)] = name + return mapping + + +def preview(data): + text = "".join(chr(b) if 32 <= b < 127 or b in (9, 10, 13) else "." for b in data) + return text.replace("\r", "\\r").replace("\n", "\\n") + + +def utcnow(): + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +class Writer: + def __init__(self, path): + path.parent.mkdir(parents=True, exist_ok=True) + self.path = path + self.fh = path.open("a", buffering=1) + + def emit(self, rec): + self.fh.write(json.dumps(rec, separators=(",", ":")) + "\n") + self.fh.flush() + + +def parse_ipv4(pkt): + if len(pkt) < 20: + return None + ihl = (pkt[0] & 0x0F) * 4 + if pkt[0] >> 4 != 4 or pkt[9] != 6 or len(pkt) < ihl + 20: + return None + src = socket.inet_ntoa(pkt[12:16]) + return src, pkt[ihl:] + + +def parse_ipv6(pkt): + if len(pkt) < 40 or pkt[6] != 6: + return None + src = socket.inet_ntop(socket.AF_INET6, pkt[8:24]) + return src, pkt[40:] + + +def parse_tcp(tcp): + if len(tcp) < 20: + return None + sport, dport = struct.unpack_from("!HH", tcp, 0) + offset = (tcp[12] >> 4) * 4 + flags = tcp[13] + return sport, dport, flags, tcp[offset:] + + +def main(): + writer = Writer(LOG_PATH) + ports = docker_ports() + next_refresh = time.monotonic() + PORT_REFRESH + flows = defaultdict(lambda: {"n": 0, "seen": 0.0}) + sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL)) + sock.bind((IFACE, 0)) + print(f"listening on {IFACE}, {len(ports)} challenge ports, log={LOG_PATH}", flush=True) + while True: + raw, _ = sock.recvfrom(2048) + now = time.monotonic() + if now >= next_refresh: + ports = docker_ports() + next_refresh = now + PORT_REFRESH + dead = [k for k, v in flows.items() if now - v["seen"] > FLOW_TTL] + for k in dead: + del flows[k] + if len(raw) < 14: + continue + eth = struct.unpack_from("!H", raw, 12)[0] + if eth == ETH_P_IP: + parsed = parse_ipv4(raw[14:]) + elif eth == ETH_P_IPV6: + parsed = parse_ipv6(raw[14:]) + else: + continue + if not parsed: + continue + src, tcp = parsed + parsed_tcp = parse_tcp(tcp) + if not parsed_tcp: + continue + sport, dport, flags, payload = parsed_tcp + if dport in SKIP_PORTS or dport not in ports: + continue + syn = bool(flags & 0x02) and not (flags & 0x10) + psh = bool(flags & 0x08) and payload + if not syn and not psh: + continue + key = (src, sport, dport) + flow = flows[key] + if flow["n"] >= MAX_EVENTS_PER_FLOW: + continue + flow["n"] += 1 + flow["seen"] = now + data = payload[:MAX_PREVIEW] + rec = { + "time": utcnow(), + "event": "connect" if syn and not payload else "data", + "ClientHost": src, + "ClientPort": sport, + "DstPort": dport, + "container": ports.get(dport, ""), + "bytes": len(payload), + "preview": preview(data), + "hex": data.hex(), + } + writer.emit(rec) + + +if __name__ == "__main__": + main() diff --git a/monitoring/worker/cf.env.example b/monitoring/worker/cf.env.example new file mode 100644 index 0000000..5c1e910 --- /dev/null +++ b/monitoring/worker/cf.env.example @@ -0,0 +1,3 @@ +# Cloudflare API token with Zone:DNS:Edit, used by Traefik for the +# DNS-01 challenge of the *.challs. wildcard certificate. +CF_DNS_API_TOKEN= diff --git a/monitoring/worker/docker-compose.yml b/monitoring/worker/docker-compose.yml new file mode 100644 index 0000000..ac782f8 --- /dev/null +++ b/monitoring/worker/docker-compose.yml @@ -0,0 +1,113 @@ +# Worker ("chall-edge") stack: runs next to the challenge containers on the +# Ansible target host. Traefik routes *.challs. to instances and +# writes the JSON access log Promtail ships to Loki; docker-stats-exporter +# (:8088) and Traefik metrics (:8082) are scraped by the control-plane +# Prometheus (see ../prometheus.yml). Restrict 8082/8088 to the control plane. +# +# cp cf.env.example cf.env # Cloudflare token for the DNS-01 wildcard cert +# docker network create traefik +# docker compose up -d + +name: chall-edge + +services: + traefik: + image: traefik:v3.6.2 + container_name: traefik + restart: unless-stopped + env_file: + - cf.env + command: + - --providers.docker=true + - --providers.docker.exposedbydefault=false + - --providers.docker.network=traefik + - --providers.file.directory=/etc/traefik/dynamic + - --providers.file.watch=true + - --entrypoints.web.address=:80 + - --entrypoints.websecure.address=:443 + - --entrypoints.web.http.redirections.entrypoint.to=websecure + - --entrypoints.web.http.redirections.entrypoint.scheme=https + - --entrypoints.websecure.http.tls=true + - --certificatesresolvers.le.acme.email=admin@example.com + - --certificatesresolvers.le.acme.storage=/letsencrypt/acme.json + - --certificatesresolvers.le.acme.dnschallenge=true + - --certificatesresolvers.le.acme.dnschallenge.provider=cloudflare + - --certificatesresolvers.le.acme.dnschallenge.resolvers=1.1.1.1:53,8.8.8.8:53 + - --ping=true + - --metrics.prometheus=true + - --metrics.prometheus.entryPoint=metrics + - --metrics.prometheus.addEntryPointsLabels=true + - --metrics.prometheus.addRoutersLabels=false + - --metrics.prometheus.addServicesLabels=false + - --entrypoints.metrics.address=:8082 + - --accesslog=true + - --accesslog.format=json + - --accesslog.filepath=/var/log/traefik/access.log + - --accesslog.bufferingsize=100 + - --accesslog.fields.headers.defaultmode=drop + - --accesslog.fields.headers.names.User-Agent=keep + - --accesslog.fields.headers.names.Referer=keep + ports: + - "80:80" + - "443:443" + - "8082:8082" + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + - letsencrypt:/letsencrypt + - ./dynamic:/etc/traefik/dynamic:ro + - /var/log/traefik:/var/log/traefik + networks: + - traefik + healthcheck: + test: ["CMD", "traefik", "healthcheck", "--ping"] + interval: 10s + timeout: 5s + retries: 5 + + docker-stats: + build: ../docker-stats-exporter + image: galvanize/docker-stats-exporter:latest + container_name: docker-stats-exporter + restart: unless-stopped + environment: + LISTEN_ADDRESS: 0.0.0.0:8080 + ports: + - "8088:8080" + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + + + tcp-access: + build: ../tcp-access-logger + image: galvanize/tcp-access-logger:latest + container_name: tcp-access-logger + restart: unless-stopped + network_mode: host + cap_add: + - NET_RAW + - NET_ADMIN + environment: + CAPTURE_IFACE: eth0 + LOG_PATH: /var/log/tcp-access/access.log + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + - /var/log/tcp-access:/var/log/tcp-access + + promtail: + image: grafana/promtail:3.1.1 + container_name: promtail + restart: unless-stopped + command: + - -config.file=/etc/promtail/config.yml + volumes: + - ../promtail.yml:/etc/promtail/config.yml:ro + - /var/log/traefik:/var/log/traefik:ro + - /var/log/tcp-access:/var/log/tcp-access:ro + +networks: + traefik: + name: traefik + external: true + +volumes: + letsencrypt: diff --git a/monitoring/worker/dynamic/tls.yml b/monitoring/worker/dynamic/tls.yml new file mode 100644 index 0000000..9e04d42 --- /dev/null +++ b/monitoring/worker/dynamic/tls.yml @@ -0,0 +1,18 @@ +http: + routers: + acme-wildcard: + rule: "Host(`acme-wildcard.challs.example.com`)" + entryPoints: + - websecure + service: acme-noop + tls: + certResolver: le + domains: + - main: "challs.example.com" + sans: + - "*.challs.example.com" + services: + acme-noop: + loadBalancer: + servers: + - url: "http://127.0.0.1:9"