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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## vX.X.X (YYYY-MM-DD)

### Fixed
- Same-named challenges in different categories no longer collide. The category is now part of the deploy check against the JWT (a token for `web/login` cannot deploy or terminate `pwn/login`), of the per-instance lock, and of the Docker Compose project name, which also names the instance's subdomain
- Project names end with a real hash of the instance's identity: the previous suffix was always `706f6c`, since `sha1.New().Sum(name)` appended the hash of nothing to the name instead of hashing it. Names are also cut to fit a 63-character DNS label

### Upgrade notes
- Project names, and so the subdomains of new instances, change format (e.g. `polypwn-web-login-team1-<hash>`). Instances already running keep their name; terminating them also removes the project under its previous name, so upgrading does not leave containers behind

## v0.7.1 (2026-06-02)

### Added
Expand Down
2 changes: 1 addition & 1 deletion data/challenges/example/http/challenge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type: zync

# The 'http' playbook deploys a single container behind Traefik.
# Traefik routes traffic based on a generated subdomain:
# <compose_project>.<instancer_host> (e.g. polypwn-example-http-team1-a3f2c1.challs.example.com)
# <compose_project>.<instancer_host> (e.g. polypwn-web-example-http-team1-9448f1e7.challs.example.com)
playbook_name: http

deploy_parameters:
Expand Down
11 changes: 11 additions & 0 deletions data/playbooks/custom_compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,14 @@
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
changed_when: false
failed_when: false
tags:
- delete
11 changes: 11 additions & 0 deletions data/playbooks/http.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,14 @@
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
changed_when: false
failed_when: false
tags:
- delete
11 changes: 11 additions & 0 deletions data/playbooks/tcp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,14 @@
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
changed_when: false
failed_when: false
tags:
- delete
2 changes: 1 addition & 1 deletion galvanize-instancer/internal/ansible/compose_expose.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.Name, teamID)
project := docker.BuildComposeProject(chall.Unique, chall.Category, chall.Name, teamID)
domainRoot := conf.Instancer.InstancerHost
traefikNetwork, _ := conf.Instancer.ExtraDeploymentParameters[traefikNetworkParam].(string)

Expand Down
9 changes: 8 additions & 1 deletion galvanize-instancer/internal/ansible/playbook.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,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.Name, teamID)
composeProject := docker.BuildComposeProject(challenge.Unique, challenge.Category, challenge.Name, teamID)

// Ansible playbook options
playbookOpts := &playbook.AnsiblePlaybookOptions{
Expand All @@ -74,6 +74,13 @@ 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
}

// Merge resource limits (challenge overrides config defaults) and pass to Ansible
merged := config.MergeResourceLimits(conf.Instancer.DefaultResourceLimits, challenge.ResourceLimits)
if resourceOverrides := BuildResourceOverrides(merged); len(resourceOverrides) > 0 {
Expand Down
55 changes: 45 additions & 10 deletions galvanize-instancer/internal/docker/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,52 @@ func SanitizeProjectName(name string) string {
return s
}

func BuildComposeProject(unique bool, challengeName, teamID string) string {
var composeProject string
// projectSuffixLen is the number of hex characters of the identity hash
// appended to project names.
const projectSuffixLen = 8

// maxProjectNameLen keeps a project name usable as a single DNS label: it is
// also the instance's subdomain (<project>.<instancer_host>).
const maxProjectNameLen = 63

// 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
// 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
if unique {
composeProject = "global-" + challengeName
composeProject = SanitizeProjectName(composeProject)
readable = "global-" + category + "-" + challengeName
identity = "unique\x00" + category + "\x00" + challengeName
} else {
composeProject = "polypwn-" + challengeName + "-" + teamID
composeProject = SanitizeProjectName(composeProject)
sum := sha1.New().Sum([]byte(composeProject))
hexSum := hex.EncodeToString(sum)
composeProject = composeProject + "-" + hexSum[:6]
readable = "polypwn-" + category + "-" + challengeName + "-" + teamID
identity = "team\x00" + category + "\x00" + challengeName + "\x00" + teamID
}

sum := sha1.Sum([]byte(identity))
suffix := hex.EncodeToString(sum[:])[:projectSuffixLen]

readable = SanitizeProjectName(readable)
if maxReadable := maxProjectNameLen - 1 - projectSuffixLen; len(readable) > maxReadable {
readable = strings.TrimRight(readable[:maxReadable], "-_")
}
return readable + "-" + suffix
}

// 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,
// so the first 6 hex characters were always those of "pol". It is kept only
// so instances started before an upgrade can still be terminated.
func LegacyComposeProject(unique bool, challengeName, teamID string) string {
if unique {
return SanitizeProjectName("global-" + challengeName)
}
return composeProject
composeProject := SanitizeProjectName("polypwn-" + challengeName + "-" + teamID)
sum := sha1.New().Sum([]byte(composeProject))
return composeProject + "-" + hex.EncodeToString(sum)[:6]
}
89 changes: 89 additions & 0 deletions galvanize-instancer/internal/docker/compose_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package docker

import (
"regexp"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

// A Docker Compose project name that is also a valid DNS label
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")

assert.NotEqual(t, web, pwn)
assert.True(t, strings.HasPrefix(web, "polypwn-web-login-team1-"), web)
assert.True(t, strings.HasPrefix(pwn, "polypwn-pwn-login-team1-"), pwn)

assert.NotEqual(t,
BuildComposeProject(true, "web", "login", ""),
BuildComposeProject(true, "pwn", "login", ""))
}

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"))
}

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"))

// Readable parts equal after sanitization: only the hash keeps them apart
assert.NotEqual(t,
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)
}

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-"))
}

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")

for _, p := range []string{a, b} {
assert.LessOrEqual(t, len(p), 63, p)
assert.Regexp(t, validProject, p)
}
// Truncated to the same readable part, still distinct
assert.NotEqual(t, a, b)
}

func TestBuildComposeProject_ValidForAnyName(t *testing.T) {
for _, p := range []string{
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, "日本", "語", ""))
}

func TestLegacyComposeProject_MatchesV071(t *testing.T) {
// What Galvanize v0.7.1 named these instances
assert.Equal(t, "polypwn-login-team1-706f6c", LegacyComposeProject(false, "login", "team1"))
assert.Equal(t, "polypwn-my-chall-team-2-706f6c", LegacyComposeProject(false, "My Chall", "Team 2"))
assert.Equal(t, "global-login", LegacyComposeProject(true, "login", ""))
}

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", ""))
}
18 changes: 13 additions & 5 deletions galvanize-instancer/pkg/restserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,13 @@ func (s *Server) Wait(ctx context.Context) error {
// log.Printf("Metrics synced. Found %.0f active challenge containers.", count)
//}

// instanceLockKey identifies a challenge instance for the deploy lock.
// Challenge names are only unique within a category, so the category is part
// of it; teamID is empty for unique (shared) instances.
func instanceLockKey(category, challengeName, teamID string) string {
return category + "/" + challengeName + ":" + teamID
}

func (s *Server) GetHealth(ctx echo.Context) error {
return ctx.JSON(200, map[string]string{"status": "ok"})
}
Expand All @@ -141,8 +148,9 @@ func (s *Server) DeployInstance(ctx echo.Context) error {
return ctx.JSON(400, api.Error{Message: utils.Ptr("Invalid request")})
}
zap.S().Infof("Deploy request received for challenge %s for team %s", req.ChallengeName, claims.TeamID)
// Check if challenge is valid for team
if req.ChallengeName != claims.ChallengeName && claims.Role != "admin" {
// Check if challenge is valid for team. Challenge names are only unique
// within a category, so the category must match too.
if (req.ChallengeName != claims.ChallengeName || req.Category != claims.Category) && claims.Role != "admin" {
zap.S().Errorf("Unauthorized attempt to deploy challenge %s for team %s", req.ChallengeName, claims.TeamID)
pkgmetrics.UnauthorizedDeployRequestsTotal.WithLabelValues(claims.TeamID).Inc()
return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")})
Expand All @@ -156,7 +164,7 @@ 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 := chall.Name + claims.TeamID
id := instanceLockKey(chall.Category, chall.Name, claims.TeamID)
s.kmu.LockKey(id)
existingDeployment, err := models.GetDeployment(s.db, chall.Category, chall.Name, claims.TeamID, false)
if err == nil && existingDeployment != nil {
Expand Down Expand Up @@ -345,8 +353,8 @@ func (s *Server) TerminateInstance(ctx echo.Context) error {
if err := ctx.Bind(&req); err != nil {
return ctx.JSON(400, api.Error{Message: utils.Ptr("Invalid request")})
}
// Check if challenge is valid for team
if req.ChallengeName != claims.ChallengeName && claims.Role != "admin" {
// Check if challenge is valid for team (name and category, see DeployInstance)
if (req.ChallengeName != claims.ChallengeName || req.Category != claims.Category) && claims.Role != "admin" {
zap.S().Errorf("Unauthorized attempt to terminate challenge %s for team %s", req.ChallengeName, claims.TeamID)
pkgmetrics.UnauthorizedDeployRequestsTotal.WithLabelValues(claims.TeamID).Inc()
return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")})
Expand Down
2 changes: 1 addition & 1 deletion galvanize-instancer/pkg/restserver_admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (s *Server) DeployAdminInstance(ctx echo.Context) error {
return ctx.JSON(400, api.Error{Message: utils.Ptr("Challenge is not unique")})
}

id := chall.Name + "_unique"
id := instanceLockKey(chall.Category, chall.Name, "")
s.kmu.LockKey(id)
existingDeployment, err := models.GetUniqueDeployment(s.db, chall.Category, chall.Name, false)
if err == nil && existingDeployment != nil {
Expand Down
43 changes: 43 additions & 0 deletions galvanize-instancer/pkg/restserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,36 @@ func TestDeployInstance_Forbidden_WrongChallenge(t *testing.T) {
assert.Equal(t, http.StatusForbidden, rec.Code)
}

func TestDeployInstance_Forbidden_WrongCategory(t *testing.T) {
deployer := &mockDeployer{}
srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge()))

// Same challenge name, but the token is for another category's challenge
claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "pwn", Role: "user"}
body := `{"challenge_name":"http","category":"web"}`
ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/deploy", claims, body)

err := srv.DeployInstance(ctx)
require.NoError(t, err)
assert.Equal(t, http.StatusForbidden, rec.Code)
assert.Empty(t, deployer.deployCalls)
}

func TestDeployInstance_AdminCanDeployOtherCategory(t *testing.T) {
deployer := &mockDeployer{}
srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge()))

claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "pwn", Role: "admin"}
body := `{"challenge_name":"http","category":"web"}`
ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/deploy", claims, body)

err := srv.DeployInstance(ctx)
require.NoError(t, err)
assert.Equal(t, http.StatusAccepted, rec.Code)
waitForBackground(t, srv)
assert.Len(t, deployer.deployCalls, 1)
}

func TestDeployInstance_AdminCanDeployAnychallenge(t *testing.T) {
deployer := &mockDeployer{}
chall := httpChallenge()
Expand Down Expand Up @@ -723,6 +753,19 @@ func TestTerminateInstance_Forbidden_WrongChallenge(t *testing.T) {
assert.Equal(t, http.StatusForbidden, rec.Code)
}

func TestTerminateInstance_Forbidden_WrongCategory(t *testing.T) {
deployer := &mockDeployer{}
srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge()))

claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "pwn", Role: "user"}
body := `{"challenge_name":"http","category":"web"}`
ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/terminate", claims, body)

err := srv.TerminateInstance(ctx)
require.NoError(t, err)
assert.Equal(t, http.StatusForbidden, rec.Code)
}

func TestTerminateInstance_NotFound(t *testing.T) {
deployer := &mockDeployer{}
srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge()))
Expand Down
Loading