From 41d86f5c55e2769063aec1ba48946f914a154782 Mon Sep 17 00:00:00 2001 From: LounnM Date: Tue, 27 Oct 2026 14:32:53 -0400 Subject: [PATCH 01/11] Build and publish multi-arch Docker images (amd64, arm64) --- .github/workflows/build.yml | 3 +++ .github/workflows/release.yml | 4 ++++ CHANGELOG.md | 3 +++ galvanize-instancer/Dockerfile | 5 ++++- 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 564750a..88d1880 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -42,6 +42,8 @@ jobs: run: | VERSION=$(grep -oP 'Version = "\K[0-9]+\.[0-9]+\.[0-9]+' galvanize-instancer/constants.go) echo "version=${VERSION}" >> "$GITHUB_OUTPUT" + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 @@ -62,6 +64,7 @@ jobs: with: context: . file: galvanize-instancer/Dockerfile + platforms: linux/amd64,linux/arm64 push: true tags: ${{ env.REGISTRY }}/${{ steps.image.outputs.name }}:${{ steps.version.outputs.version }}-B${{ github.run_number }} labels: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 71e607b..7e894f6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,6 +36,9 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 @@ -65,6 +68,7 @@ jobs: with: context: . file: galvanize-instancer/Dockerfile + platforms: linux/amd64,linux/arm64 push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 066120f..54c8745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## vX.X.X (YYYY-MM-DD) +### Added +- Multi-arch Docker images (linux/amd64, linux/arm64) + ## v0.7.3 (2026-10-01) ### Fixed diff --git a/galvanize-instancer/Dockerfile b/galvanize-instancer/Dockerfile index ffd3511..3177ac7 100755 --- a/galvanize-instancer/Dockerfile +++ b/galvanize-instancer/Dockerfile @@ -1,10 +1,13 @@ -FROM golang:1.25 AS builder +FROM --platform=$BUILDPLATFORM golang:1.25 AS builder +ARG TARGETOS TARGETARCH WORKDIR /app # Copy go mod files first for better caching COPY ./galvanize-instancer/go.mod ./galvanize-instancer/go.sum ./ RUN go mod download +COPY ./galvanize-instancer . +RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o galvanize . # Copy source code COPY ./galvanize-instancer . From 9f1cde57d954a5bb8ded520f1beb6d6383d24301 Mon Sep 17 00:00:00 2001 From: LounnM Date: Tue, 27 Oct 2026 15:03:40 -0400 Subject: [PATCH 02/11] removed leftover duplicate build code --- galvanize-instancer/Dockerfile | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/galvanize-instancer/Dockerfile b/galvanize-instancer/Dockerfile index 3177ac7..e49d899 100755 --- a/galvanize-instancer/Dockerfile +++ b/galvanize-instancer/Dockerfile @@ -6,12 +6,10 @@ WORKDIR /app # Copy go mod files first for better caching COPY ./galvanize-instancer/go.mod ./galvanize-instancer/go.sum ./ RUN go mod download -COPY ./galvanize-instancer . -RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o galvanize . # Copy source code COPY ./galvanize-instancer . -RUN go build -o galvanize . +RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o galvanize . FROM debian:stable-slim LABEL authors="28Pollux28" From 3bcb972accfb7adfc7663c4986f7aff69b0de718 Mon Sep 17 00:00:00 2001 From: Kalnyia Date: Tue, 27 Oct 2026 19:07:23 -0400 Subject: [PATCH 03/11] Bump version to 0.7.4 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ galvanize-instancer/api/openapi.yaml.in | 2 +- galvanize-instancer/constants.go | 2 +- galvanize-instancer/pkg/api/api.gen.go | 4 ++-- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 54c8745..f8583ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## vX.X.X (YYYY-MM-DD) +## v0.7.4 (2026-10-27) + ### Added - Multi-arch Docker images (linux/amd64, linux/arm64) diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 2edaf5b..36acaf8 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -1,7 +1,7 @@ openapi: 3.0.3 info: title: Galvanize Instancer - version: 0.7.3 + version: 0.7.4 description: API for deploying CTF challenges using Ansible paths: diff --git a/galvanize-instancer/constants.go b/galvanize-instancer/constants.go index 3333d47..cf99851 100644 --- a/galvanize-instancer/constants.go +++ b/galvanize-instancer/constants.go @@ -1,5 +1,5 @@ package main const ( - Version = "0.7.3" + Version = "0.7.4" ) diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index 9831889..abc3891 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -489,7 +489,7 @@ var swaggerSpec = []string{ "AFmSQTsEGOcGHuJis4jhQ/TkpPgQuR+Psw/Ro8Xe1czK5ZZ9Ka4T9WnIFRibCdOv5HD0GEQKlcxFIWZb", "3Wn/F2j64n6RpDwfjAJf4oIViyo0aSgMsGnH6uJRqn77sVYqRybDvds5sqLLcnvg0a1w+KF61BMGTtJ3", "1wqM4qWrv/2NTePGORaTSgu7feN25Y2xRqZRP6ts1j29bALhX+/OnZ9JOjqtv3YKZdaW0c5N3ITZcOfP", - "flnS3rxebqfPz1/2S3Fl3Mtn0oh1TsEmbO4mfsXySybFbwhLaSyTCa16idr4iU8Wf1s8cUZXJUpWiug0", + "flnS3rxebqfPz1/2S3Fl3Mtn0oh1TsEmbO4mfsXySybFbwhLaSyTCa16idr4iU8Wf1s8dUZXJUpWiug0", "erI4WTyJYsoetDFvyuNEyVRsjpIMkwv3ulS+9KmGe1lyV8dJ6jkJOet66NA8P5ycBOq+KopKumbTVxqb", "wX+3MgFTJQkak1a50+7pyePp0LeSVTZTWvyG3As9mQq9VHotOEcJR0C0GTCaGFrH7+Lox5BmS2lRS5aD", "QX2J2rfGA+dHp++Hbn//cfcxjkxVFMwdaiIyAyThLdJUtW3rijhrVR80pH/jx8hjF439SfFtnawteuKJ", @@ -507,7 +507,7 @@ var swaggerSpec = []string{ "8+aBVM1hTPAtB/OfiP89jMXt/XmF7EFX0feR0+1yhWggQrCiK00+D6sX9H0Aq1tKB6Mr51AT2l75klLY", "Pzzm21noPPfnaT9o0Pq513VTFoNVCpDpfBtDwb7073q1u2J2nAHaZPHoGhi7qmrcZobxjvP/fGjsptLB", "sdIjIEOW26zX3g4B8ArtP73E7/T98Ia4uwC/8j+DUyC8QX0pEnQnYq/9dmybgSm8/uAvKGnP3epze24Q", - "/6b5n9UfiHsvQX9ZEXiJ/HYQ+N3nMnfQGl7W0AHb+fM6Te/3VyJvvtW9iyY0WFF2u/8NACkB0i+eMgAA", + "/6b5n9UfiHsvQX9ZEXiJ/HYQ+N3nMnfQGl7W0AHb+fM6Te/3VyJvvtW9iyY0WFF2u/8NAEL3ksyeMgAA", } // GetSwagger returns the content of the embedded swagger specification file From 386abc760c5bd2ed98b75cab33e881b5edc600fb Mon Sep 17 00:00:00 2001 From: SenequeZ <148022515+SenequeZ@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:51:46 -0500 Subject: [PATCH 04/11] Instance groups, configurable compose prefix, deploy fixes, and worker observability Instancer: - Add optional instancer.compose_project_prefix. Unset keeps upstream names; set, it prefixes team and unique instance projects. - Load numbered challenge definition files (challenge-*.yml) and keep walking a directory after a match, parse error, duplicate or non-zync file instead of skipping its remaining siblings. - Add deploy_parameters.instance_group so several challenge entries share one deployment; deployments, locks and jobs use InstanceKey(), including the admin unique-challenge endpoints. - Case-insensitive category lookups in the index and deployment queries. - Infer published_ports / http_port from deploy_parameters.port. - Keep services on the compose default network when attaching Traefik. - Extend/Terminate resolve the challenge before the deployment lookup. Playbooks / image: - Rename the compose_definition fact (it collided with the extra-var), tolerate kill failures on delete, add kill step to tcp delete, and install community.docker in the instancer image. Monitoring / extras: - Worker cAdvisor + Traefik scrape jobs, Loki, Promtail, TCP access logger, AI-usage and worker-traffic Grafana dashboards. - School scoreboard service and CTFd theme header/footer snippets. --- config.example.yaml | 1 + data/challenges/example/http/challenge.yml | 1 + data/playbooks/http.yaml | 7 +- data/playbooks/tcp.yaml | 11 +- galvanize-instancer/Dockerfile | 3 +- .../internal/ansible/compose_expose.go | 14 +- .../internal/ansible/compose_expose_test.go | 3 +- .../internal/ansible/deployer.go | 2 +- .../internal/ansible/playbook.go | 2 +- .../internal/challenge/challenge.go | 71 +++++- .../internal/challenge/challenge_test.go | 83 +++++- .../internal/docker/compose.go | 22 +- .../internal/docker/compose_test.go | 59 +++-- galvanize-instancer/pkg/config/config.go | 17 +- galvanize-instancer/pkg/models/deployment.go | 8 +- galvanize-instancer/pkg/restserver.go | 35 +-- galvanize-instancer/pkg/restserver_admin.go | 23 +- monitoring/grafana/dashboards/ai-usage.json | 239 ++++++++++++++++++ .../grafana/dashboards/worker-traffic.json | 236 +++++++++++++++++ .../grafana/provisioning/datasources/loki.yml | 11 + monitoring/loki.yml | 43 ++++ monitoring/prometheus.yml | 21 ++ monitoring/promtail.yml | 53 ++++ monitoring/tcp-access-logger/Dockerfile | 4 + monitoring/tcp-access-logger/logger.py | 193 ++++++++++++++ school-scoreboard/Dockerfile | 11 + school-scoreboard/app.py | 165 ++++++++++++ school-scoreboard/requirements.txt | 3 + school-scoreboard/templates/index.html | 192 ++++++++++++++ theme/selectstar-theme-footer.html | 33 +++ theme/selectstar-theme-header.html | 136 ++++++++++ 31 files changed, 1613 insertions(+), 89 deletions(-) create mode 100644 monitoring/grafana/dashboards/ai-usage.json create mode 100644 monitoring/grafana/dashboards/worker-traffic.json create mode 100644 monitoring/grafana/provisioning/datasources/loki.yml create mode 100644 monitoring/loki.yml create mode 100644 monitoring/promtail.yml create mode 100644 monitoring/tcp-access-logger/Dockerfile create mode 100644 monitoring/tcp-access-logger/logger.py create mode 100644 school-scoreboard/Dockerfile create mode 100644 school-scoreboard/app.py create mode 100644 school-scoreboard/requirements.txt create mode 100644 school-scoreboard/templates/index.html create mode 100644 theme/selectstar-theme-footer.html create mode 100644 theme/selectstar-theme-header.html diff --git a/config.example.yaml b/config.example.yaml index e54e80f..2897517 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: "myctf" # Optional readable prefix of instance names/subdomains (default: "polypwn-" for team instances, none for unique ones) 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..1f7fb02 100644 --- a/data/challenges/example/http/challenge.yml +++ b/data/challenges/example/http/challenge.yml @@ -7,6 +7,7 @@ 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) +# The "polypwn" prefix can be changed with instancer.compose_project_prefix in config.yaml. playbook_name: http deploy_parameters: diff --git a/data/playbooks/http.yaml b/data/playbooks/http.yaml index 2330005..7012ecc 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,18 +46,19 @@ - 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 diff --git a/data/playbooks/tcp.yaml b/data/playbooks/tcp.yaml index 1b6494a..3ba4228 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,14 +33,19 @@ - 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 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/deployer.go b/galvanize-instancer/internal/ansible/deployer.go index 0ebd7cd..09e0f8d 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) { diff --git a/galvanize-instancer/internal/ansible/playbook.go b/galvanize-instancer/internal/ansible/playbook.go index 1e55809..a54c830 100644 --- a/galvanize-instancer/internal/ansible/playbook.go +++ b/galvanize-instancer/internal/ansible/playbook.go @@ -57,7 +57,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{ diff --git a/galvanize-instancer/internal/challenge/challenge.go b/galvanize-instancer/internal/challenge/challenge.go index 273da03..dc1c55b 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,25 @@ type Challenge struct { PlaybookName string `yaml:"playbook_name"` Type string `yaml:"type"` Unique bool `yaml:"-"` + InstanceGroup string `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 +214,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 +259,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 + } + 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 chall, nil + return nil, fmt.Errorf("challenge not found: %s", key) } func (idx *ChallengeIndex) GetAllUnique() []*Challenge { @@ -291,6 +325,21 @@ func parseChallenge(challengeFilePath string) (*Challenge, error) { challenge.Unique = true } } + if group := toStringField(challenge.DeployParameters, "instance_group"); group != "" { + challenge.InstanceGroup = group + } + 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..cfc426d 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) { diff --git a/galvanize-instancer/internal/docker/compose.go b/galvanize-instancer/internal/docker/compose.go index 2b6214b..59de146 100644 --- a/galvanize-instancer/internal/docker/compose.go +++ b/galvanize-instancer/internal/docker/compose.go @@ -42,21 +42,37 @@ const projectSuffixLen = 8 // also the instance's subdomain (.). const maxProjectNameLen = 63 +// DefaultComposeProjectPrefix is the readable prefix of team instance project +// names when instancer.compose_project_prefix is not set. +const DefaultComposeProjectPrefix = "polypwn" + // 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 { +// +// prefix comes from instancer.compose_project_prefix. When it is empty, names +// are unchanged: team instances use "polypwn-" and unique instances have no +// prefix ("global-..."). When it is set, both start with it, so several +// events sharing a worker get distinct, recognizable names. The prefix is +// not part of the hashed identity. +func BuildComposeProject(prefix string, unique bool, category, challengeName, teamID string) string { var readable, identity string if unique { readable = "global-" + category + "-" + challengeName + if prefix != "" { + readable = prefix + "-" + readable + } identity = "unique\x00" + category + "\x00" + challengeName } else { - readable = "polypwn-" + category + "-" + challengeName + "-" + teamID + if prefix == "" { + prefix = DefaultComposeProjectPrefix + } + readable = prefix + "-" + category + "-" + challengeName + "-" + teamID identity = "team\x00" + category + "\x00" + challengeName + "\x00" + teamID } diff --git a/galvanize-instancer/internal/docker/compose_test.go b/galvanize-instancer/internal/docker/compose_test.go index 708fbf7..5ddc4f3 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.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, "polypwn-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", ""), "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, `^global-[0-9a-f]{8}$`, BuildComposeProject("", true, "中文", "挑战", "")) + assert.NotEqual(t, BuildComposeProject("", true, "中文", "挑战", ""), BuildComposeProject("", true, "日本", "語", "")) } func TestLegacyComposeProject_MatchesV071(t *testing.T) { @@ -84,6 +84,21 @@ 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, "polypwn") + + 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:]) } diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index 150c956..61d74b5 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: "polypwn") 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/grafana/dashboards/ai-usage.json b/monitoring/grafana/dashboards/ai-usage.json new file mode 100644 index 0000000..24ebf38 --- /dev/null +++ b/monitoring/grafana/dashboards/ai-usage.json @@ -0,0 +1,239 @@ +{ + "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": 4, + "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 + } + ] + } + ] +} 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..965a573 100644 --- a/monitoring/prometheus.yml +++ b/monitoring/prometheus.yml @@ -11,3 +11,24 @@ scrape_configs: # basic_auth: # username: prometheus # password: + + # Worker challenge traffic. Ports are UFW-restricted to the control plane. + - 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/school-scoreboard/Dockerfile b/school-scoreboard/Dockerfile new file mode 100644 index 0000000..cdc463c --- /dev/null +++ b/school-scoreboard/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.12-alpine +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY app.py . +COPY templates ./templates +RUN adduser -D -u 1000 app +USER app +ENV PYTHONUNBUFFERED=1 +EXPOSE 8080 +CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "2", "--threads", "4", "app:app"] diff --git a/school-scoreboard/app.py b/school-scoreboard/app.py new file mode 100644 index 0000000..842e4f7 --- /dev/null +++ b/school-scoreboard/app.py @@ -0,0 +1,165 @@ +import os +import re +import time +import unicodedata +from datetime import datetime, timezone + +import pymysql +from flask import Flask, jsonify, render_template + +app = Flask(__name__) + +CACHE_TTL = int(os.environ.get("CACHE_TTL", "10")) +_cache = {"ts": 0.0, "payload": None} + + +def fold(value: str) -> str: + text = unicodedata.normalize("NFKD", value or "") + text = "".join(ch for ch in text if not unicodedata.combining(ch)) + text = text.lower().replace("&", " ").replace("'", " ").replace("’", " ") + return " ".join(re.sub(r"[^a-z0-9]+", " ", text).split()) + + +def canonical_school(affiliation: str) -> str | None: + raw = (affiliation or "").strip() + if not raw: + return None + key = fold(raw) + if not key: + return None + + if "jdis" in key or key in {"udes", "uds"} or "sherbrooke" in key: + return "Université de Sherbrooke" + if key in {"ulaval"} or "laval" in key: + return "Université Laval" + if key in {"ets", "dci"} or "ets" in key or "dddccc" in key: + return "ÉTS" + if "concordia" in key: + return "Concordia University" + if "poly" in key: + return "Polytechnique Montréal" + if key == "uqam": + return "UQAM" + if key == "udem": + return "Université de Montréal" + if "foy" in key: + return "Cégep de Sainte-Foy" + if "csi" in key and "jean" in key: + return "CSI Saint-Jean" + if "fish" in key and "fric" in key: + return "Fish & Fric" + return raw + + +def db_conn(): + return pymysql.connect( + host=os.environ.get("MYSQL_HOST", "db"), + user=os.environ.get("MYSQL_USER", "ctfd"), + password=os.environ["MYSQL_PASSWORD"], + database=os.environ.get("MYSQL_DATABASE", "ctfd"), + charset="utf8mb4", + cursorclass=pymysql.cursors.DictCursor, + connect_timeout=5, + read_timeout=10, + ) + + +def load_scoreboard(): + sql = """ + SELECT + u.id AS user_id, + u.name AS username, + u.affiliation AS affiliation, + COALESCE(SUM(c.value), 0) AS chall_score, + COALESCE(( + SELECT SUM(a.value) FROM awards a WHERE a.user_id = u.id + ), 0) AS award_score, + COUNT(c.id) AS solves, + MAX(s.date) AS last_solve + FROM users u + LEFT JOIN submissions s + ON s.user_id = u.id AND s.type = 'correct' + LEFT JOIN challenges c + ON c.id = s.challenge_id AND c.state = 'visible' + WHERE u.hidden = 0 + AND u.banned = 0 + AND u.type = 'user' + GROUP BY u.id, u.name, u.affiliation + """ + with db_conn() as conn: + with conn.cursor() as cur: + cur.execute(sql) + rows = cur.fetchall() + + schools: dict[str, dict] = {} + unaffiliated = 0 + for row in rows: + score = int(row["chall_score"] or 0) + int(row["award_score"] or 0) + school = canonical_school(row["affiliation"]) + if school is None: + unaffiliated += 1 + continue + entry = schools.setdefault( + school, + { + "school": school, + "players": [], + "affiliations": set(), + }, + ) + last = row["last_solve"] + last_iso = last.isoformat(sep=" ") if last else None + if row["affiliation"]: + entry["affiliations"].add(row["affiliation"].strip()) + entry["players"].append( + { + "name": row["username"], + "score": score, + "solves": int(row["solves"] or 0), + "affiliation": (row["affiliation"] or "").strip(), + "last_solve": last_iso, + } + ) + + ranked = [] + for entry in schools.values(): + entry["players"].sort( + key=lambda p: (-p["score"], p["last_solve"] or "9999", p["name"].lower()) + ) + for i, player in enumerate(entry["players"], start=1): + player["rank"] = i + entry["player_count"] = len(entry["players"]) + entry["affiliations"] = sorted(entry["affiliations"], key=str.lower) + ranked.append(entry) + + ranked.sort(key=lambda s: (-s["player_count"], s["school"].lower())) + + return { + "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"), + "schools": ranked, + "unaffiliated_players": unaffiliated, + "school_count": len(ranked), + } + + +def scoreboard(): + now = time.time() + if _cache["payload"] is None or now - _cache["ts"] > CACHE_TTL: + _cache["payload"] = load_scoreboard() + _cache["ts"] = now + return _cache["payload"] + + +@app.get("/") +def index(): + return render_template("index.html") + + +@app.get("/api/scoreboard") +def api_scoreboard(): + return jsonify(scoreboard()) + + +@app.get("/health") +def health(): + return {"ok": True} diff --git a/school-scoreboard/requirements.txt b/school-scoreboard/requirements.txt new file mode 100644 index 0000000..4f3f3d8 --- /dev/null +++ b/school-scoreboard/requirements.txt @@ -0,0 +1,3 @@ +flask==3.0.3 +pymysql==1.1.1 +gunicorn==23.0.0 diff --git a/school-scoreboard/templates/index.html b/school-scoreboard/templates/index.html new file mode 100644 index 0000000..bf2a66b --- /dev/null +++ b/school-scoreboard/templates/index.html @@ -0,0 +1,192 @@ + + + + + + UnitedCTF — Classement par école + + + +
+
+
+

UnitedCTF 2026

+

Classement par école

+

Même classement que CTFd, limité aux joueurs d’une école. Les variantes d’affiliation (UDES / JDIS, ÉTS / DCI, Polytechnique, …) sont regroupées.

+
+
+ + + CTFd +
+
+
+ + +
+
+ + + + + + + + + + +
#JoueurPointsSolves
+ +
+ + + diff --git a/theme/selectstar-theme-footer.html b/theme/selectstar-theme-footer.html new file mode 100644 index 0000000..8c78cb0 --- /dev/null +++ b/theme/selectstar-theme-footer.html @@ -0,0 +1,33 @@ + + diff --git a/theme/selectstar-theme-header.html b/theme/selectstar-theme-header.html new file mode 100644 index 0000000..04ae87d --- /dev/null +++ b/theme/selectstar-theme-header.html @@ -0,0 +1,136 @@ + + + + From c1bf3c947cc3d6baefd8b92d3e9dd7e2ac60a43a Mon Sep 17 00:00:00 2001 From: SenequeZ <148022515+SenequeZ@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:17:26 -0500 Subject: [PATCH 05/11] Add show_tcp_ports to list TCP ports alongside the HTTP URL Connection info normally stops at the first Traefik HTTP URL, hiding every published TCP port of the instance. deploy_parameters.show_tcp_ports lists the HTTP URL first, then each published port (sorted, deduplicated, IPv6 binds skipped), one per line. Also update the AI-usage Grafana dashboard to the version used live (markdown links to instances). --- .../internal/ansible/connection_info.go | 91 ++++- .../internal/ansible/connection_info_test.go | 46 ++- .../internal/ansible/deployer.go | 2 +- .../internal/challenge/challenge.go | 6 + .../internal/challenge/challenge_test.go | 33 ++ monitoring/grafana/dashboards/ai-usage.json | 379 ++++++++++++++++-- 6 files changed, 493 insertions(+), 64 deletions(-) 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 09e0f8d..f04f70b 100644 --- a/galvanize-instancer/internal/ansible/deployer.go +++ b/galvanize-instancer/internal/ansible/deployer.go @@ -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/challenge/challenge.go b/galvanize-instancer/internal/challenge/challenge.go index dc1c55b..0e65de4 100644 --- a/galvanize-instancer/internal/challenge/challenge.go +++ b/galvanize-instancer/internal/challenge/challenge.go @@ -151,6 +151,7 @@ type Challenge struct { 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"` @@ -328,6 +329,11 @@ func parseChallenge(challengeFilePath string) (*Challenge, error) { 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} diff --git a/galvanize-instancer/internal/challenge/challenge_test.go b/galvanize-instancer/internal/challenge/challenge_test.go index cfc426d..1ad88e9 100644 --- a/galvanize-instancer/internal/challenge/challenge_test.go +++ b/galvanize-instancer/internal/challenge/challenge_test.go @@ -625,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/monitoring/grafana/dashboards/ai-usage.json b/monitoring/grafana/dashboards/ai-usage.json index 24ebf38..01768b4 100644 --- a/monitoring/grafana/dashboards/ai-usage.json +++ b/monitoring/grafana/dashboards/ai-usage.json @@ -2,32 +2,70 @@ "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"], + "tags": [ + "unitedctf", + "ai", + "accesslog" + ], "timezone": "browser", "refresh": "30s", - "time": { "from": "now-6h", "to": "now" }, + "time": { + "from": "now-6h", + "to": "now" + }, "schemaVersion": 39, - "version": 4, - "templating": { "list": [] }, + "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" }, + "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 }] } + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "blue", + "value": null + } + ] + } }, "overrides": [] }, - "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background", "graphMode": "area" }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "area" + }, "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "editorMode": "code", "expr": "sum(count_over_time({job=\"worker-traefik-access\"} [1h]))", "queryType": "instant" @@ -38,20 +76,57 @@ "id": 1, "type": "stat", "title": "AI / LLM User-Agents (1h)", - "gridPos": { "x": 6, "y": 0, "w": 6, "h": 4 }, - "datasource": { "type": "loki", "uid": "loki" }, + "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 }] } + "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" }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "none" + }, "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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" @@ -62,20 +137,57 @@ "id": 2, "type": "stat", "title": "Phishy / recon paths (1h)", - "gridPos": { "x": 12, "y": 0, "w": 6, "h": 4 }, - "datasource": { "type": "loki", "uid": "loki" }, + "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 }] } + "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" }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "none" + }, "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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" @@ -86,20 +198,49 @@ "id": 7, "type": "stat", "title": "TCP events (1h)", - "gridPos": { "x": 18, "y": 0, "w": 6, "h": 4 }, - "datasource": { "type": "loki", "uid": "loki" }, + "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 }] } + "color": { + "mode": "thresholds" + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "blue", + "value": null + } + ] + } }, "overrides": [] }, - "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background", "graphMode": "area" }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "background", + "graphMode": "area" + }, "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "editorMode": "code", "expr": "sum(count_over_time({job=\"worker-tcp-access\"} [1h]))", "queryType": "instant" @@ -111,8 +252,16 @@ "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" }, + "gridPos": { + "x": 0, + "y": 4, + "w": 24, + "h": 12 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "options": { "showTime": true, "showLabels": false, @@ -124,7 +273,10 @@ "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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", @@ -137,8 +289,16 @@ "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" }, + "gridPos": { + "x": 0, + "y": 16, + "w": 24, + "h": 10 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "options": { "showTime": true, "showLabels": false, @@ -150,7 +310,10 @@ "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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", @@ -163,8 +326,16 @@ "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" }, + "gridPos": { + "x": 0, + "y": 26, + "w": 24, + "h": 9 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "options": { "showTime": true, "showLabels": false, @@ -176,7 +347,10 @@ "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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", @@ -188,8 +362,16 @@ "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" }, + "gridPos": { + "x": 0, + "y": 35, + "w": 24, + "h": 9 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "options": { "showTime": true, "showLabels": false, @@ -201,7 +383,10 @@ "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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", @@ -214,8 +399,16 @@ "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" }, + "gridPos": { + "x": 0, + "y": 44, + "w": 24, + "h": 10 + }, + "datasource": { + "type": "loki", + "uid": "loki" + }, "options": { "showTime": true, "showLabels": false, @@ -227,13 +420,111 @@ "targets": [ { "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, + "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 From b2595a6fea60ee5b723e3b944c730609f55032df Mon Sep 17 00:00:00 2001 From: SenequeZ <148022515+SenequeZ@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:25:32 -0500 Subject: [PATCH 06/11] Add worker stack and docker-stats-exporter used by the monitoring setup - monitoring/worker: the worker-side compose (Traefik with JSON access log keeping User-Agent/Referer, Prometheus metrics on :8082, DNS-01 wildcard cert via Cloudflare; docker-stats-exporter; tcp-access-logger; Promtail), dynamic/tls.yml for the wildcard cert, cf.env.example. - monitoring/docker-stats-exporter: small exporter reading the Docker socket, exposing per-container CPU/memory/network with cAdvisor-style names. This is what the worker-cadvisor scrape job targets on :8088. --- .gitignore | 3 +- monitoring/docker-stats-exporter/Dockerfile | 5 + monitoring/docker-stats-exporter/exporter.py | 115 +++++++++++++++++++ monitoring/prometheus.yml | 2 + monitoring/worker/cf.env.example | 3 + monitoring/worker/docker-compose.yml | 113 ++++++++++++++++++ monitoring/worker/dynamic/tls.yml | 18 +++ 7 files changed, 258 insertions(+), 1 deletion(-) create mode 100644 monitoring/docker-stats-exporter/Dockerfile create mode 100644 monitoring/docker-stats-exporter/exporter.py create mode 100644 monitoring/worker/cf.env.example create mode 100644 monitoring/worker/docker-compose.yml create mode 100644 monitoring/worker/dynamic/tls.yml 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/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/prometheus.yml b/monitoring/prometheus.yml index 965a573..49cc2c7 100644 --- a/monitoring/prometheus.yml +++ b/monitoring/prometheus.yml @@ -13,6 +13,8 @@ scrape_configs: # 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: 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" From 4c4feeabaed6967720a6048e08a37cd0cff1bb0a Mon Sep 17 00:00:00 2001 From: SenequeZ <148022515+SenequeZ@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:38:56 -0500 Subject: [PATCH 07/11] Address review: generic ctf-event default prefix, drop scoreboard and theme - compose_project_prefix defaults to "ctf-event" and applies to both team and unique instances (-global-...). No PolyCyber-specific default. - Instances named by v0.7.2-v0.7.4 (polypwn-/global- names) are added to the upgrade cleanup next to the v0.7.1 names: playbooks now loop over legacy_compose_projects. - Remove school-scoreboard/ and theme/, which are event-specific. --- config.example.yaml | 2 +- data/challenges/example/http/challenge.yml | 4 +- data/playbooks/custom_compose.yaml | 12 +- data/playbooks/http.yaml | 12 +- data/playbooks/tcp.yaml | 12 +- .../internal/ansible/playbook.go | 17 +- .../internal/docker/compose.go | 55 +++-- .../internal/docker/compose_test.go | 21 +- galvanize-instancer/pkg/config/config.go | 2 +- school-scoreboard/Dockerfile | 11 - school-scoreboard/app.py | 165 --------------- school-scoreboard/requirements.txt | 3 - school-scoreboard/templates/index.html | 192 ------------------ theme/selectstar-theme-footer.html | 33 --- theme/selectstar-theme-header.html | 136 ------------- 15 files changed, 85 insertions(+), 592 deletions(-) delete mode 100644 school-scoreboard/Dockerfile delete mode 100644 school-scoreboard/app.py delete mode 100644 school-scoreboard/requirements.txt delete mode 100644 school-scoreboard/templates/index.html delete mode 100644 theme/selectstar-theme-footer.html delete mode 100644 theme/selectstar-theme-header.html diff --git a/config.example.yaml b/config.example.yaml index 2897517..892cbc7 100755 --- a/config.example.yaml +++ b/config.example.yaml @@ -5,7 +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: "myctf" # Optional readable prefix of instance names/subdomains (default: "polypwn-" for team instances, none for unique ones) + 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 1f7fb02..3dc604b 100644 --- a/data/challenges/example/http/challenge.yml +++ b/data/challenges/example/http/challenge.yml @@ -6,8 +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) -# The "polypwn" prefix can be changed with instancer.compose_project_prefix in config.yaml. +# . (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 7012ecc..c63ab18 100644 --- a/data/playbooks/http.yaml +++ b/data/playbooks/http.yaml @@ -63,12 +63,12 @@ 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 3ba4228..5e5875f 100755 --- a/data/playbooks/tcp.yaml +++ b/data/playbooks/tcp.yaml @@ -50,12 +50,12 @@ 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/internal/ansible/playbook.go b/galvanize-instancer/internal/ansible/playbook.go index a54c830..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" @@ -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/docker/compose.go b/galvanize-instancer/internal/docker/compose.go index 59de146..5523207 100644 --- a/galvanize-instancer/internal/docker/compose.go +++ b/galvanize-instancer/internal/docker/compose.go @@ -42,9 +42,9 @@ const projectSuffixLen = 8 // also the instance's subdomain (.). const maxProjectNameLen = 63 -// DefaultComposeProjectPrefix is the readable prefix of team instance project +// DefaultComposeProjectPrefix is the readable prefix of instance project // names when instancer.compose_project_prefix is not set. -const DefaultComposeProjectPrefix = "polypwn" +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 @@ -55,27 +55,28 @@ const DefaultComposeProjectPrefix = "polypwn" // names that only differ in characters sanitization removes, or names cut by // the truncation. // -// prefix comes from instancer.compose_project_prefix. When it is empty, names -// are unchanged: team instances use "polypwn-" and unique instances have no -// prefix ("global-..."). When it is set, both start with it, so several -// events sharing a worker get distinct, recognizable names. The prefix is -// not part of the hashed identity. +// 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 { - var readable, identity string + if prefix == "" { + prefix = DefaultComposeProjectPrefix + } if unique { - readable = "global-" + category + "-" + challengeName - if prefix != "" { - readable = prefix + "-" + readable - } - identity = "unique\x00" + category + "\x00" + challengeName - } else { - if prefix == "" { - prefix = DefaultComposeProjectPrefix - } - readable = prefix + "-" + 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] @@ -86,6 +87,22 @@ func BuildComposeProject(prefix string, unique bool, category, challengeName, te 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 5ddc4f3..719f318 100644 --- a/galvanize-instancer/internal/docker/compose_test.go +++ b/galvanize-instancer/internal/docker/compose_test.go @@ -16,8 +16,8 @@ func TestBuildComposeProject_SameNameDifferentCategories(t *testing.T) { 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", ""), @@ -26,7 +26,7 @@ func TestBuildComposeProject_SameNameDifferentCategories(t *testing.T) { 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) { @@ -47,7 +47,7 @@ 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-")) + assert.True(t, strings.HasPrefix(BuildComposeProject("", true, "web", "login", ""), "ctf-event-global-web-login-")) } func TestBuildComposeProject_FitsOneDNSLabel(t *testing.T) { @@ -72,7 +72,7 @@ func TestBuildComposeProject_ValidForAnyName(t *testing.T) { 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.Regexp(t, `^ctf-event-global-[0-9a-f]{8}$`, BuildComposeProject("", true, "中文", "挑战", "")) assert.NotEqual(t, BuildComposeProject("", true, "中文", "挑战", ""), BuildComposeProject("", true, "日本", "語", "")) } @@ -91,7 +91,7 @@ func TestLegacyComposeProject_DiffersFromNewName(t *testing.T) { 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, "polypwn") + assert.NotContains(t, name, DefaultComposeProjectPrefix) global := BuildComposeProject("unitedctf", true, "web", "shared", "") assert.True(t, strings.HasPrefix(global, "unitedctf-global-web-shared-"), global) @@ -102,3 +102,12 @@ func TestBuildComposeProject_PrefixKeepsIdentityHash(t *testing.T) { 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 61d74b5..8b1b4c7 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -47,7 +47,7 @@ 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: "polypwn") + 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 diff --git a/school-scoreboard/Dockerfile b/school-scoreboard/Dockerfile deleted file mode 100644 index cdc463c..0000000 --- a/school-scoreboard/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM python:3.12-alpine -WORKDIR /app -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt -COPY app.py . -COPY templates ./templates -RUN adduser -D -u 1000 app -USER app -ENV PYTHONUNBUFFERED=1 -EXPOSE 8080 -CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "2", "--threads", "4", "app:app"] diff --git a/school-scoreboard/app.py b/school-scoreboard/app.py deleted file mode 100644 index 842e4f7..0000000 --- a/school-scoreboard/app.py +++ /dev/null @@ -1,165 +0,0 @@ -import os -import re -import time -import unicodedata -from datetime import datetime, timezone - -import pymysql -from flask import Flask, jsonify, render_template - -app = Flask(__name__) - -CACHE_TTL = int(os.environ.get("CACHE_TTL", "10")) -_cache = {"ts": 0.0, "payload": None} - - -def fold(value: str) -> str: - text = unicodedata.normalize("NFKD", value or "") - text = "".join(ch for ch in text if not unicodedata.combining(ch)) - text = text.lower().replace("&", " ").replace("'", " ").replace("’", " ") - return " ".join(re.sub(r"[^a-z0-9]+", " ", text).split()) - - -def canonical_school(affiliation: str) -> str | None: - raw = (affiliation or "").strip() - if not raw: - return None - key = fold(raw) - if not key: - return None - - if "jdis" in key or key in {"udes", "uds"} or "sherbrooke" in key: - return "Université de Sherbrooke" - if key in {"ulaval"} or "laval" in key: - return "Université Laval" - if key in {"ets", "dci"} or "ets" in key or "dddccc" in key: - return "ÉTS" - if "concordia" in key: - return "Concordia University" - if "poly" in key: - return "Polytechnique Montréal" - if key == "uqam": - return "UQAM" - if key == "udem": - return "Université de Montréal" - if "foy" in key: - return "Cégep de Sainte-Foy" - if "csi" in key and "jean" in key: - return "CSI Saint-Jean" - if "fish" in key and "fric" in key: - return "Fish & Fric" - return raw - - -def db_conn(): - return pymysql.connect( - host=os.environ.get("MYSQL_HOST", "db"), - user=os.environ.get("MYSQL_USER", "ctfd"), - password=os.environ["MYSQL_PASSWORD"], - database=os.environ.get("MYSQL_DATABASE", "ctfd"), - charset="utf8mb4", - cursorclass=pymysql.cursors.DictCursor, - connect_timeout=5, - read_timeout=10, - ) - - -def load_scoreboard(): - sql = """ - SELECT - u.id AS user_id, - u.name AS username, - u.affiliation AS affiliation, - COALESCE(SUM(c.value), 0) AS chall_score, - COALESCE(( - SELECT SUM(a.value) FROM awards a WHERE a.user_id = u.id - ), 0) AS award_score, - COUNT(c.id) AS solves, - MAX(s.date) AS last_solve - FROM users u - LEFT JOIN submissions s - ON s.user_id = u.id AND s.type = 'correct' - LEFT JOIN challenges c - ON c.id = s.challenge_id AND c.state = 'visible' - WHERE u.hidden = 0 - AND u.banned = 0 - AND u.type = 'user' - GROUP BY u.id, u.name, u.affiliation - """ - with db_conn() as conn: - with conn.cursor() as cur: - cur.execute(sql) - rows = cur.fetchall() - - schools: dict[str, dict] = {} - unaffiliated = 0 - for row in rows: - score = int(row["chall_score"] or 0) + int(row["award_score"] or 0) - school = canonical_school(row["affiliation"]) - if school is None: - unaffiliated += 1 - continue - entry = schools.setdefault( - school, - { - "school": school, - "players": [], - "affiliations": set(), - }, - ) - last = row["last_solve"] - last_iso = last.isoformat(sep=" ") if last else None - if row["affiliation"]: - entry["affiliations"].add(row["affiliation"].strip()) - entry["players"].append( - { - "name": row["username"], - "score": score, - "solves": int(row["solves"] or 0), - "affiliation": (row["affiliation"] or "").strip(), - "last_solve": last_iso, - } - ) - - ranked = [] - for entry in schools.values(): - entry["players"].sort( - key=lambda p: (-p["score"], p["last_solve"] or "9999", p["name"].lower()) - ) - for i, player in enumerate(entry["players"], start=1): - player["rank"] = i - entry["player_count"] = len(entry["players"]) - entry["affiliations"] = sorted(entry["affiliations"], key=str.lower) - ranked.append(entry) - - ranked.sort(key=lambda s: (-s["player_count"], s["school"].lower())) - - return { - "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"), - "schools": ranked, - "unaffiliated_players": unaffiliated, - "school_count": len(ranked), - } - - -def scoreboard(): - now = time.time() - if _cache["payload"] is None or now - _cache["ts"] > CACHE_TTL: - _cache["payload"] = load_scoreboard() - _cache["ts"] = now - return _cache["payload"] - - -@app.get("/") -def index(): - return render_template("index.html") - - -@app.get("/api/scoreboard") -def api_scoreboard(): - return jsonify(scoreboard()) - - -@app.get("/health") -def health(): - return {"ok": True} diff --git a/school-scoreboard/requirements.txt b/school-scoreboard/requirements.txt deleted file mode 100644 index 4f3f3d8..0000000 --- a/school-scoreboard/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -flask==3.0.3 -pymysql==1.1.1 -gunicorn==23.0.0 diff --git a/school-scoreboard/templates/index.html b/school-scoreboard/templates/index.html deleted file mode 100644 index bf2a66b..0000000 --- a/school-scoreboard/templates/index.html +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - UnitedCTF — Classement par école - - - -
-
-
-

UnitedCTF 2026

-

Classement par école

-

Même classement que CTFd, limité aux joueurs d’une école. Les variantes d’affiliation (UDES / JDIS, ÉTS / DCI, Polytechnique, …) sont regroupées.

-
-
- - - CTFd -
-
-
- - -
-
- - - - - - - - - - -
#JoueurPointsSolves
- -
- - - diff --git a/theme/selectstar-theme-footer.html b/theme/selectstar-theme-footer.html deleted file mode 100644 index 8c78cb0..0000000 --- a/theme/selectstar-theme-footer.html +++ /dev/null @@ -1,33 +0,0 @@ - - diff --git a/theme/selectstar-theme-header.html b/theme/selectstar-theme-header.html deleted file mode 100644 index 04ae87d..0000000 --- a/theme/selectstar-theme-header.html +++ /dev/null @@ -1,136 +0,0 @@ - - - - From 210db846c05d12ef979496f247cea934324ad3dd Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 21:53:25 -0400 Subject: [PATCH 08/11] fix: report every endpoint of an instance in its connection info GetConnectionInfo returned at the first container that had a Traefik router label or a published port, so an instance with several user-facing services (e.g. a web front end and an SSH service, both exposed with expose:) reported only one of them, whichever Ansible listed first. To find a route, it also took the first traefik.http.routers.* label of a map, in random order: with author-written router labels besides the rule (entrypoints, tls, middlewares), the route was found or missed at random. It now goes through every container, ordered by compose service then name, and lists each Host() of each router rule as https:///, then each published IPv4 port as ://: (the port's protocol hint, or its protocol), one per line without duplicates. Only .rule labels are read, and containers with traefik.enable=false are skipped. An instance with a single endpoint reports it as before. --- CHANGELOG.md | 3 + .../example/custom_compose/challenge.yml | 5 + .../internal/ansible/connection_info.go | 151 +++++++++--------- .../internal/ansible/connection_info_test.go | 94 +++++++++++ 4 files changed, 176 insertions(+), 77 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8583ec..a2dea7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## vX.X.X (YYYY-MM-DD) +### Fixed +- Connection info lists every HTTP endpoint of an instance, one per line, ordered by compose service: each host of each Traefik router rule as `https:///`. Only the first container with a route was reported, so a challenge with several web services showed only one of them, depending on the order Ansible listed the containers. Without any route, the published ports of every container are listed, sorted by container port, instead of only the first container's; with `show_tcp_ports`, they follow the HTTP endpoints as before. Only routers' `.rule` labels are read, so other Traefik labels set by challenge authors (entrypoints, tls, middlewares) no longer make the route random, and containers with `traefik.enable=false` are skipped + ## v0.7.4 (2026-10-27) ### Added diff --git a/data/challenges/example/custom_compose/challenge.yml b/data/challenges/example/custom_compose/challenge.yml index a60a311..9e922dd 100644 --- a/data/challenges/example/custom_compose/challenge.yml +++ b/data/challenges/example/custom_compose/challenge.yml @@ -30,6 +30,11 @@ deploy_parameters: # # You no longer need to hand-write Traefik labels, attach the external # network, or pick host ports yourself. + # + # Several services can be exposed: players get every https:/// + # endpoint, one per line, ordered by service name. Published tcp ports + # (://:) are listed when nothing is exposed over + # http, or after the http endpoints with `show_tcp_ports: true`. expose: - service: web port: 80 diff --git a/galvanize-instancer/internal/ansible/connection_info.go b/galvanize-instancer/internal/ansible/connection_info.go index 42eab33..1f4b7b3 100644 --- a/galvanize-instancer/internal/ansible/connection_info.go +++ b/galvanize-instancer/internal/ansible/connection_info.go @@ -2,103 +2,100 @@ package ansible import ( "fmt" + "regexp" "sort" "strings" ) -// 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. +// hostRule matches each Host(`name`) of a Traefik router rule +var hostRule = regexp.MustCompile("Host\\(`([^`]+)`\\)") + +// GetConnectionInfo returns how players reach a deployed instance, one +// endpoint per line. Every container routed by Traefik gives https:/// +// for each Host() of its routers' rules, containers taken in compose service +// order so the result does not depend on the order Ansible reports them in. +// Published ports give ://:, the scheme being the port's +// protocol hint, or else the port's protocol (tcp, udp), sorted by container +// port. They are listed when no container is routed by Traefik, or after the +// HTTP URLs when showTCPPorts is set. 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 { - if strings.HasPrefix(labelKey, "traefik.http.routers.") { - traefikLabel = labelValue - break - } - } - // Check if we have a traefik label - if traefikLabel != "" { - labelParts := strings.Split(traefikLabel, "`") - if len(labelParts) >= 2 { - domainName := "https://" + labelParts[1] + "/" - return domainName, nil - } - } - // Check if we have published ports - ports := publishedPortURLs(ci.Publishers, host, protocolHints) - if len(ports) > 0 { - return strings.Join(ports, "\n"), nil + containers := append([]ContainerInfo(nil), containerInfos...) + sort.SliceStable(containers, func(i, j int) bool { + return containerSortKey(containers[i]) < containerSortKey(containers[j]) + }) + + var endpoints []string + seen := map[string]bool{} + add := func(endpoint string) { + if !seen[endpoint] { + seen[endpoint] = true + endpoints = append(endpoints, endpoint) } } - 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 + for _, ci := range containers { + for _, domain := range traefikDomains(ci.Labels) { + add("https://" + domain + "/") } } - 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 + + if len(endpoints) == 0 || showTCPPorts { + var publishers []PublisherInfo + for _, ci := range containers { + publishers = append(publishers, ci.Publishers...) } - 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) + // 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 + }) + for _, pub := range publishers { + // Docker lists each port for IPv4 and IPv6: keep the IPv4 one + if pub.PublishedPort == 0 || strings.Contains(pub.URL, ":") { + continue + } + scheme := pub.Protocol + if hinted, ok := protocolHints[pub.TargetPort]; ok { + scheme = hinted + } + add(fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort)) } } - if len(lines) == 0 { + + if len(endpoints) == 0 { return "", fmt.Errorf("no connection info found") } - return strings.Join(lines, "\n"), nil + return strings.Join(endpoints, "\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] + "/" +// traefikDomains returns the hosts of the container's Traefik HTTP router +// rules, sorted by router. Other router labels (entrypoints, tls, +// middlewares...) are not rules and are ignored, as are containers Traefik is +// told to leave alone. +func traefikDomains(labels map[string]string) []string { + if strings.EqualFold(labels["traefik.enable"], "false") { + return nil + } + var ruleKeys []string + for key := range labels { + if strings.HasPrefix(key, "traefik.http.routers.") && strings.HasSuffix(key, ".rule") { + ruleKeys = append(ruleKeys, key) } } - return "" -} + sort.Strings(ruleKeys) -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)) + var domains []string + for _, key := range ruleKeys { + for _, m := range hostRule.FindAllStringSubmatch(labels[key], -1) { + domains = append(domains, m[1]) } } - return ports + return domains +} + +// containerSortKey orders containers by compose service, then by name +func containerSortKey(ci ContainerInfo) string { + return ci.Labels["com.docker.compose.service"] + "\x00" + ci.Name } diff --git a/galvanize-instancer/internal/ansible/connection_info_test.go b/galvanize-instancer/internal/ansible/connection_info_test.go index 40abacf..0257550 100644 --- a/galvanize-instancer/internal/ansible/connection_info_test.go +++ b/galvanize-instancer/internal/ansible/connection_info_test.go @@ -161,3 +161,97 @@ func isRandomBindingFor(portDef string, target string) bool { } return defaultPortRange.contains(hostPort) } + +func webContainer(service, project, domain string) ContainerInfo { + return ContainerInfo{ + Name: project + "-" + service + "-1", + Labels: map[string]string{ + "com.docker.compose.service": service, + "traefik.enable": "true", + "traefik.http.routers." + project + ".rule": "Host(`" + domain + "`)", + "traefik.http.services." + project + ".loadbalancer.server.port": "80", + }, + } +} + +func sshContainer(project string, port int) ContainerInfo { + return ContainerInfo{ + Name: project + "-ssh-1", + Labels: map[string]string{"com.docker.compose.service": "ssh"}, + Publishers: []PublisherInfo{ + {Protocol: "tcp", PublishedPort: port, TargetPort: 22, URL: "0.0.0.0"}, + {Protocol: "tcp", PublishedPort: port, TargetPort: 22, URL: "::"}, + }, + } +} + +func TestGetConnectionInfo_SingleWebChallengeUnchanged(t *testing.T) { + conn, err := GetConnectionInfo([]ContainerInfo{webContainer("web", "p", "p.challs.example.com")}, "challs.example.com", nil, false) + require.NoError(t, err) + assert.Equal(t, "https://p.challs.example.com/", conn) +} + +// A web front end and an SSH service with show_tcp_ports: both endpoints, +// whatever order Ansible reports the containers in. +func TestGetConnectionInfo_WebAndSSHServices(t *testing.T) { + web := webContainer("web", "p", "p.challs.example.com") + ssh := sshContainer("p", 40022) + want := "https://p.challs.example.com/\ntcp://challs.example.com:40022" + hints := map[int]string{} + + for _, order := range [][]ContainerInfo{{web, ssh}, {ssh, web}} { + conn, err := GetConnectionInfo(order, "challs.example.com", hints, true) + require.NoError(t, err) + assert.Equal(t, want, conn) + } + + hints[22] = "ssh" + conn, err := GetConnectionInfo([]ContainerInfo{web, ssh}, "challs.example.com", hints, true) + require.NoError(t, err) + assert.Equal(t, "https://p.challs.example.com/\nssh://challs.example.com:40022", conn) +} + +func TestGetConnectionInfo_SeveralWebServices(t *testing.T) { + conn, err := GetConnectionInfo([]ContainerInfo{ + webContainer("web", "web-p", "web-p.challs.example.com"), + webContainer("api", "api-p", "api-p.challs.example.com"), + }, "challs.example.com", nil, false) + require.NoError(t, err) + assert.Equal(t, "https://api-p.challs.example.com/\nhttps://web-p.challs.example.com/", conn) +} + +// Router labels other than rules (an author's own entrypoints, tls, +// middlewares) were picked at random among the router labels +func TestGetConnectionInfo_OnlyRouterRules(t *testing.T) { + web := webContainer("web", "p", "p.challs.example.com") + web.Labels["traefik.http.routers.p.entrypoints"] = "websecure" + web.Labels["traefik.http.routers.p.tls"] = "true" + web.Labels["traefik.http.routers.p.middlewares"] = "auth" + + for range 20 { + conn, err := GetConnectionInfo([]ContainerInfo{web}, "challs.example.com", nil, false) + require.NoError(t, err) + require.Equal(t, "https://p.challs.example.com/", conn) + } +} + +func TestGetConnectionInfo_RuleWithSeveralHosts(t *testing.T) { + web := webContainer("web", "p", "") + web.Labels["traefik.http.routers.p.rule"] = "Host(`a.challs.example.com`) || (Host(`b.challs.example.com`) && PathPrefix(`/x`))" + conn, err := GetConnectionInfo([]ContainerInfo{web}, "challs.example.com", nil, false) + require.NoError(t, err) + assert.Equal(t, "https://a.challs.example.com/\nhttps://b.challs.example.com/", conn) +} + +func TestGetConnectionInfo_TraefikDisabledIgnored(t *testing.T) { + web := webContainer("web", "p", "p.challs.example.com") + web.Labels["traefik.enable"] = "false" + conn, err := GetConnectionInfo([]ContainerInfo{web, sshContainer("p", 40022)}, "challs.example.com", map[int]string{22: "ssh"}, false) + require.NoError(t, err) + assert.Equal(t, "ssh://challs.example.com:40022", conn) +} + +func TestGetConnectionInfo_NoEndpoint(t *testing.T) { + _, err := GetConnectionInfo([]ContainerInfo{{Name: "db", Labels: map[string]string{"com.docker.compose.service": "db"}}}, "challs.example.com", nil, false) + assert.Error(t, err) +} From 09e96293370fd90f5df09311679eddfac7042645 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Fri, 2 Oct 2026 00:28:24 -0400 Subject: [PATCH 09/11] feat: report the version to admins on /admin/version Zync needs Galvanize's version to check that the two are compatible. The project is open source, so a version also tells anyone which known issues a deployment has: it is reported to admins only. GET /admin/version returns {"version": "..."}, the version set at startup (ServerOpts.Version, from the binary's Version). Like every route but /health and /metrics, it requires a valid HS256 token signed with the JWT secret, and the handler refuses any role but admin, so requests without a valid token get 401 and player tokens 403, without the version. /health is unchanged. The JWT middleware setup moves to jwtMiddleware, so tests send real requests through it: no token, a wrong key, an unsigned (alg none) token, an expired admin token, player and role-less tokens. --- CHANGELOG.md | 3 + galvanize-instancer/api/openapi.yaml.in | 28 ++++++ galvanize-instancer/cmd/serve.go | 26 +++-- galvanize-instancer/cmd/version_test.go | 82 ++++++++++++++++ galvanize-instancer/pkg/api/api.gen.go | 100 ++++++++++++-------- galvanize-instancer/pkg/restserver.go | 4 + galvanize-instancer/pkg/restserver_admin.go | 19 ++++ 7 files changed, 214 insertions(+), 48 deletions(-) create mode 100644 galvanize-instancer/cmd/version_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a2dea7f..8563576 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## vX.X.X (YYYY-MM-DD) +### Added +- `GET /admin/version` returns the running version (e.g. `{"version": "0.7.5"}`), for Zync to check compatibility. It requires an admin token: requests without a valid token get 401 and player tokens 403, so the version is never disclosed to players or unauthenticated clients + ### Fixed - Connection info lists every HTTP endpoint of an instance, one per line, ordered by compose service: each host of each Traefik router rule as `https:///`. Only the first container with a route was reported, so a challenge with several web services showed only one of them, depending on the order Ansible listed the containers. Without any route, the published ports of every container are listed, sorted by container port, instead of only the first container's; with `show_tcp_ports`, they follow the HTTP endpoints as before. Only routers' `.rule` labels are read, so other Traefik labels set by challenge authors (entrypoints, tls, middlewares) no longer make the route random, and containers with `traefik.enable=false` are skipped diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 36acaf8..babe8a6 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -244,6 +244,25 @@ paths: '500': description: Internal server error + /admin/version: + get: + summary: Galvanize version + description: Returns the version of the running Galvanize, e.g. for Zync to check that it is compatible. Admins only, so that neither players nor unauthenticated clients learn which version, and so which known issues, a deployment has. + operationId: getVersion + security: + - bearerAuth: [ ] + responses: + '200': + description: Galvanize version + content: + application/json: + schema: + $ref: '#/components/schemas/VersionResponse' + '401': + description: Unauthorized + '403': + description: Forbidden - Admin access required + /admin/config-check: post: summary: Check communication with Zync @@ -554,6 +573,15 @@ components: - created_at - updated_at + VersionResponse: + type: object + properties: + version: + type: string + description: Version of the running Galvanize (e.g. 0.7.3). + required: + - version + ReloadChallengesResponse: type: object properties: diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 16b0a71..c052589 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -83,16 +83,7 @@ var serveCmd = &cobra.Command{ cfg.Instancer.AnsibleDir = ansiblePath // 4. Auth - jwtConfig := echojwt.Config{ - NewClaimsFunc: func(c echo.Context) jwt.Claims { - return new(auth.Claims) - }, - SigningKey: []byte(jwtSecret), - Skipper: func(c echo.Context) bool { - return c.Path() == "/health" || c.Path() == "/metrics" - }, - } - e.Use(echojwt.WithConfig(jwtConfig)) + e.Use(jwtMiddleware(jwtSecret)) if err := utils.RegisterSSHHosts(cfg); err != nil { zap.S().Fatalf("Failed to register SSH hosts: %v", err) @@ -191,6 +182,7 @@ var serveCmd = &cobra.Command{ TeamDeployer: teamDeployer, ExpiryScheduler: expirySched, JobQueue: jobQueue, + Version: rootCmd.Version, }) api.RegisterHandlers(e, srv) @@ -280,6 +272,20 @@ func configureQueueless(cfg *config.Config, jobQueue *worker.Queue, expirySched return teamDeployer } +// jwtMiddleware requires a valid HS256 token signed with secret on every +// route but /health and /metrics; handlers then check the claims' role. +func jwtMiddleware(secret string) echo.MiddlewareFunc { + return echojwt.WithConfig(echojwt.Config{ + NewClaimsFunc: func(c echo.Context) jwt.Claims { + return new(auth.Claims) + }, + SigningKey: []byte(secret), + Skipper: func(c echo.Context) bool { + return c.Path() == "/health" || c.Path() == "/metrics" + }, + }) +} + // useMiddleware installs the request logger, panic recovery and CORS. // // Recover turns a panic in a handler into a 500 response, logged with its diff --git a/galvanize-instancer/cmd/version_test.go b/galvanize-instancer/cmd/version_test.go new file mode 100644 index 0000000..462d1d7 --- /dev/null +++ b/galvanize-instancer/cmd/version_test.go @@ -0,0 +1,82 @@ +package cmd + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/28Pollux28/galvanize/internal/auth" + server "github.com/28Pollux28/galvanize/pkg" + "github.com/28Pollux28/galvanize/pkg/api" + "github.com/golang-jwt/jwt/v5" + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testSecret = "test-jwt-secret" + +// newAPI serves Galvanize's API behind the same JWT middleware as serve +func newAPI(version string) *echo.Echo { + e := echo.New() + e.Use(jwtMiddleware(testSecret)) + api.RegisterHandlers(e, server.NewServerWithOpts(server.ServerOpts{Version: version})) + return e +} + +func signed(t *testing.T, method jwt.SigningMethod, key interface{}, role string, expires time.Time) string { + t.Helper() + claims := &auth.Claims{Role: role, TeamID: "team1", RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(expires)}} + token, err := jwt.NewWithClaims(method, claims).SignedString(key) + require.NoError(t, err) + return token +} + +func get(e *echo.Echo, path, token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + return rec +} + +func TestVersion_OnlyForAdmins(t *testing.T) { + e := newAPI("9.8.7") + hour := time.Now().Add(time.Hour) + + rec := get(e, "/admin/version", signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", hour)) + assert.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `{"version":"9.8.7"}`, rec.Body.String()) + + for name, tc := range map[string]struct { + token string + code int + }{ + "no token": {"", http.StatusUnauthorized}, + "wrong key": {signed(t, jwt.SigningMethodHS256, []byte("another-secret"), "admin", hour), http.StatusUnauthorized}, + "unsigned (none)": {signed(t, jwt.SigningMethodNone, jwt.UnsafeAllowNoneSignatureType, "admin", hour), http.StatusUnauthorized}, + "expired admin": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(-time.Minute)), http.StatusUnauthorized}, + "player": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "player", hour), http.StatusForbidden}, + "no role": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "", hour), http.StatusForbidden}, + } { + t.Run(name, func(t *testing.T) { + rec := get(e, "/admin/version", tc.token) + assert.Equal(t, tc.code, rec.Code) + assert.NotContains(t, rec.Body.String(), "9.8.7", "the version is not disclosed") + }) + } +} + +func TestVersion_NotInHealth(t *testing.T) { + rec := get(newAPI("9.8.7"), "/health", "") + assert.Equal(t, http.StatusOK, rec.Code) + assert.NotContains(t, rec.Body.String(), "9.8.7") +} + +func TestVersion_UnknownWhenUnset(t *testing.T) { + rec := get(newAPI(""), "/admin/version", signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(time.Hour))) + assert.JSONEq(t, `{"version":"unknown"}`, rec.Body.String()) +} diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index abc3891..f9162f7 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -189,6 +189,12 @@ type TeamDeploymentsResponse struct { TeamId string `json:"team_id"` } +// VersionResponse defines model for VersionResponse. +type VersionResponse struct { + // Version Version of the running Galvanize (e.g. 0.7.3). + Version string `json:"version"` +} + // DeployAdminInstanceJSONRequestBody defines body for DeployAdminInstance for application/json ContentType. type DeployAdminInstanceJSONRequestBody = AdminDeployRequest @@ -236,6 +242,9 @@ type ServerInterface interface { // Terminate all unique challenges (admin only) // (POST /admin/terminate-all) TerminateAllAdminInstances(ctx echo.Context) error + // Galvanize version + // (GET /admin/version) + GetVersion(ctx echo.Context) error // Deploy a challenge instance // (POST /deploy) DeployInstance(ctx echo.Context) error @@ -368,6 +377,17 @@ func (w *ServerInterfaceWrapper) TerminateAllAdminInstances(ctx echo.Context) er return err } +// GetVersion converts echo context to params. +func (w *ServerInterfaceWrapper) GetVersion(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetVersion(ctx) + return err +} + // DeployInstance converts echo context to params. func (w *ServerInterfaceWrapper) DeployInstance(ctx echo.Context) error { var err error @@ -459,6 +479,7 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL router.GET(baseURL+"/admin/team-deployments", wrapper.ListTeamDeployments) router.POST(baseURL+"/admin/terminate", wrapper.TerminateAdminInstance) router.POST(baseURL+"/admin/terminate-all", wrapper.TerminateAllAdminInstances) + router.GET(baseURL+"/admin/version", wrapper.GetVersion) router.POST(baseURL+"/deploy", wrapper.DeployInstance) router.POST(baseURL+"/extend", wrapper.ExtendInstance) router.GET(baseURL+"/health", wrapper.GetHealth) @@ -470,44 +491,47 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "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", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/galvanize-instancer/pkg/restserver.go b/galvanize-instancer/pkg/restserver.go index 5749b7e..cb382bf 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -35,6 +35,7 @@ type Server struct { kmu keymutex.KeyMutex wg sync.WaitGroup jobQueue *worker.Queue // Redis job queue (optional, nil means use direct goroutines) + version string // reported to admins only } // ServerOpts holds the dependencies needed to construct a Server. @@ -50,6 +51,8 @@ type ServerOpts struct { ExpiryScheduler *scheduler.ExpiryScheduler KeyMutex keymutex.KeyMutex JobQueue *worker.Queue // Optional: if provided, jobs are queued to Redis + // Version of the running Galvanize, reported to admins only + Version string } var _ api.ServerInterface = (*Server)(nil) @@ -79,6 +82,7 @@ func NewServerWithOpts(opts ServerOpts) *Server { expirySched: opts.ExpiryScheduler, kmu: kmu, jobQueue: opts.JobQueue, + version: opts.Version, } } diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 68db65a..82fb534 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -236,6 +236,25 @@ func (s *Server) TerminateAdminInstance(ctx echo.Context) error { return ctx.NoContent(200) } +// GetVersion reports the running Galvanize version, to admins only: the +// project is open source, so a version tells anyone its known issues. +// Requests without a valid token never get here (the JWT middleware rejects +// them); player tokens are refused. +func (s *Server) GetVersion(ctx echo.Context) error { + claims, err := auth.GetClaims(ctx) + if err != nil { + return ctx.JSON(401, api.Error{Message: utils.Ptr("Unauthorized")}) + } + if claims.Role != "admin" { + return ctx.JSON(403, api.Error{Message: utils.Ptr("Forbidden - Admin access required")}) + } + version := s.version + if version == "" { + version = "unknown" + } + return ctx.JSON(200, api.VersionResponse{Version: version}) +} + func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { claims, err := auth.GetClaims(ctx) if err != nil { From b16c96e916da80286c3a37609b4d941f88b3b7d8 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Fri, 2 Oct 2026 00:30:04 -0400 Subject: [PATCH 10/11] fix: stop serving metrics on the API port The API served /metrics on its own port, skipped by the JWT middleware, so anyone who could reach the API read every metric: challenge names, team IDs, deployment counts. The route predates the metrics server on :5001 (basic auth when metrics.password is set), added later with the Prometheus and Grafana stack, which scrapes instancer:5001 as the README documents. Nothing else uses the API port's route: not the monitoring stack, the load test, Zync, nor ctfd-management, whose Traefik router already excludes /metrics. It is removed, along with its JWT exemption: the API port now answers /metrics with 401, or 404 with a token. Request metrics are still gathered and served on :5001, unchanged. --- CHANGELOG.md | 3 ++ galvanize-instancer/cmd/metrics_test.go | 47 +++++++++++++++++++++++++ galvanize-instancer/cmd/serve.go | 8 ++--- 3 files changed, 54 insertions(+), 4 deletions(-) create mode 100644 galvanize-instancer/cmd/metrics_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 8563576..36a9b1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ### Added - `GET /admin/version` returns the running version (e.g. `{"version": "0.7.5"}`), for Zync to check compatibility. It requires an admin token: requests without a valid token get 401 and player tokens 403, so the version is never disclosed to players or unauthenticated clients +### Changed +- The API port no longer serves `/metrics`, which was exempt from authentication and exposed challenge names and team IDs to anyone who could reach the API. Metrics stay on the metrics server (port 5001, basic auth when `metrics.password` is set), which the provided Prometheus configuration already scrapes + ### Fixed - Connection info lists every HTTP endpoint of an instance, one per line, ordered by compose service: each host of each Traefik router rule as `https:///`. Only the first container with a route was reported, so a challenge with several web services showed only one of them, depending on the order Ansible listed the containers. Without any route, the published ports of every container are listed, sorted by container port, instead of only the first container's; with `show_tcp_ports`, they follow the HTTP endpoints as before. Only routers' `.rule` labels are read, so other Traefik labels set by challenge authors (entrypoints, tls, middlewares) no longer make the route random, and containers with `traefik.enable=false` are skipped diff --git a/galvanize-instancer/cmd/metrics_test.go b/galvanize-instancer/cmd/metrics_test.go new file mode 100644 index 0000000..8dc9247 --- /dev/null +++ b/galvanize-instancer/cmd/metrics_test.go @@ -0,0 +1,47 @@ +package cmd + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" +) + +// The API port no longer serves /metrics, which skipped authentication: +// metrics are only on the metrics server (:5001) +func TestAPIPort_NoMetrics(t *testing.T) { + e := newAPI("9.8.7") + assert.Equal(t, http.StatusUnauthorized, get(e, "/metrics", "").Code, "requires a token like any route") + + admin := signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(time.Hour)) + assert.Equal(t, http.StatusNotFound, get(e, "/metrics", admin).Code, "and is not served") +} + +func scrape(h http.Handler, user, pass string) int { + req := httptest.NewRequest(http.MethodGet, "/metrics", nil) + if user != "" || pass != "" { + req.SetBasicAuth(user, pass) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec.Code +} + +// The metrics server's authentication is unchanged: none without a +// password, basic auth with one (username defaults to prometheus) +func TestMetricsHandler(t *testing.T) { + metrics := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }) + + assert.Equal(t, http.StatusOK, scrape(metricsHandler("", "", metrics), "", ""), "open without a password") + + h := metricsHandler("", "s3cret", metrics) + assert.Equal(t, http.StatusUnauthorized, scrape(h, "", "")) + assert.Equal(t, http.StatusUnauthorized, scrape(h, "prometheus", "wrong")) + assert.Equal(t, http.StatusUnauthorized, scrape(h, "admin", "s3cret")) + assert.Equal(t, http.StatusOK, scrape(h, "prometheus", "s3cret")) + + assert.Equal(t, http.StatusOK, scrape(metricsHandler("scraper", "s3cret", metrics), "scraper", "s3cret")) +} diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index c052589..ff50c7f 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -56,9 +56,9 @@ var serveCmd = &cobra.Command{ // 2. Middleware useMiddleware(e) - // 3. Prometheus + // 3. Prometheus: request metrics are gathered here and served by the + // metrics server on :5001 only, never on the API port e.Use(echoprometheus.NewMiddleware("instancer")) // register middleware to gather metrics from requests - e.GET("/metrics", echoprometheus.NewHandler()) // JWT secret from env (for security); jwtSecret := os.Getenv("JWT_SECRET") @@ -273,7 +273,7 @@ func configureQueueless(cfg *config.Config, jobQueue *worker.Queue, expirySched } // jwtMiddleware requires a valid HS256 token signed with secret on every -// route but /health and /metrics; handlers then check the claims' role. +// route but /health; handlers then check the claims' role. func jwtMiddleware(secret string) echo.MiddlewareFunc { return echojwt.WithConfig(echojwt.Config{ NewClaimsFunc: func(c echo.Context) jwt.Claims { @@ -281,7 +281,7 @@ func jwtMiddleware(secret string) echo.MiddlewareFunc { }, SigningKey: []byte(secret), Skipper: func(c echo.Context) bool { - return c.Path() == "/health" || c.Path() == "/metrics" + return c.Path() == "/health" }, }) } From 1d7847f2b943e52a77e73c137128152efbe7bb31 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Wed, 11 Nov 2026 19:44:34 -0500 Subject: [PATCH 11/11] Bump version to 0.7.5 --- CHANGELOG.md | 2 + galvanize-instancer/api/openapi.yaml.in | 2 +- galvanize-instancer/constants.go | 2 +- galvanize-instancer/pkg/api/api.gen.go | 82 ++++++++++++------------- 4 files changed, 45 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36a9b1e..fcea782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## vX.X.X (YYYY-MM-DD) +## v0.7.5 (2026-11-11) + ### Added - `GET /admin/version` returns the running version (e.g. `{"version": "0.7.5"}`), for Zync to check compatibility. It requires an admin token: requests without a valid token get 401 and player tokens 403, so the version is never disclosed to players or unauthenticated clients diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index babe8a6..0d86b6f 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -1,7 +1,7 @@ openapi: 3.0.3 info: title: Galvanize Instancer - version: 0.7.4 + version: 0.7.5 description: API for deploying CTF challenges using Ansible paths: diff --git a/galvanize-instancer/constants.go b/galvanize-instancer/constants.go index cf99851..d81de1c 100644 --- a/galvanize-instancer/constants.go +++ b/galvanize-instancer/constants.go @@ -1,5 +1,5 @@ package main const ( - Version = "0.7.4" + Version = "0.7.5" ) diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index f9162f7..d506002 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -491,47 +491,47 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "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", } // GetSwagger returns the content of the embedded swagger specification file