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