Skip to content
Merged
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ TODO
docker-compose.local.yml
config.yaml
coverage.out
openapi.yaml
openapi.yaml
monitoring/worker/cf.env
1 change: 1 addition & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion data/challenges/example/http/challenge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ 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-web-example-http-team1-9448f1e7.challs.example.com)
# <compose_project>.<instancer_host> (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:
Expand Down
12 changes: 6 additions & 6 deletions data/playbooks/custom_compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
19 changes: 10 additions & 9 deletions data/playbooks/http.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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}} }}"
Expand All @@ -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:
Expand Down
23 changes: 14 additions & 9 deletions data/playbooks/tcp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

- name: Build compose definition
ansible.builtin.set_fact:
compose_definition:
_compose_def:
services:
tcp: "{{ _tcp_service }}"
tags:
Expand All @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion galvanize-instancer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ RUN useradd -ms /bin/bash galvanize
RUN apt-get update && apt-get install -y curl pipx ssh-client tini \
&& rm -rf /var/lib/apt/lists/* \
&& pipx ensurepath --global \
&& pipx install --include-deps --global ansible
&& pipx install --include-deps --global ansible \
&& ansible-galaxy collection install community.docker -p /usr/share/ansible/collections
WORKDIR /app
RUN mkdir "data"
COPY ./data/playbooks ./data/playbooks
Expand Down
14 changes: 10 additions & 4 deletions 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.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)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion galvanize-instancer/internal/ansible/compose_expose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
91 changes: 74 additions & 17 deletions galvanize-instancer/internal/ansible/connection_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ package ansible

import (
"fmt"
"sort"
"strings"
)

func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string) (string, error) {
// GetConnectionInfo returns the first Traefik HTTP URL found, or else the
// published ports. When showTCPPorts is set, the published ports of every
// container are listed after the HTTP URL instead of being hidden by it.
func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string, showTCPPorts bool) (string, error) {
if showTCPPorts {
return getAllConnectionInfo(containerInfos, host, protocolHints)
}
traefikLabel := ""
for _, ci := range containerInfos {
for labelKey, labelValue := range ci.Labels {
Expand All @@ -23,25 +30,75 @@ func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHint
}
}
// Check if we have published ports
var ports []string
for _, pub := range ci.Publishers {
if pub.PublishedPort != 0 {
// If IP is IPv6, continue
if strings.Contains(pub.URL, ":") {
continue
}
scheme := pub.Protocol
if protocolHints != nil {
if hintedScheme, ok := protocolHints[pub.TargetPort]; ok {
scheme = hintedScheme
}
}
ports = append(ports, fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort))
}
}
ports := publishedPortURLs(ci.Publishers, host, protocolHints)
if len(ports) > 0 {
return strings.Join(ports, "\n"), nil
}
}
return "", fmt.Errorf("no connection info found")
}

func getAllConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string) (string, error) {
var lines []string
for _, ci := range containerInfos {
if url := traefikURL(ci.Labels); url != "" {
lines = append(lines, url)
break
}
}
var publishers []PublisherInfo
for _, ci := range containerInfos {
publishers = append(publishers, ci.Publishers...)
}
// Docker does not guarantee publisher order; sort so the output is stable.
sort.SliceStable(publishers, func(i, j int) bool {
if publishers[i].TargetPort != publishers[j].TargetPort {
return publishers[i].TargetPort < publishers[j].TargetPort
}
return publishers[i].PublishedPort < publishers[j].PublishedPort
})
seen := map[string]bool{}
for _, port := range publishedPortURLs(publishers, host, protocolHints) {
if !seen[port] {
seen[port] = true
lines = append(lines, port)
}
}
if len(lines) == 0 {
return "", fmt.Errorf("no connection info found")
}
return strings.Join(lines, "\n"), nil
}

func traefikURL(labels map[string]string) string {
for labelKey, labelValue := range labels {
if !strings.HasPrefix(labelKey, "traefik.http.routers.") {
continue
}
labelParts := strings.Split(labelValue, "`")
if len(labelParts) >= 2 {
return "https://" + labelParts[1] + "/"
}
}
return ""
}

func publishedPortURLs(publishers []PublisherInfo, host string, protocolHints map[int]string) []string {
var ports []string
for _, pub := range publishers {
if pub.PublishedPort != 0 {
// If IP is IPv6, continue
if strings.Contains(pub.URL, ":") {
continue
}
scheme := pub.Protocol
if protocolHints != nil {
if hintedScheme, ok := protocolHints[pub.TargetPort]; ok {
scheme = hintedScheme
}
}
ports = append(ports, fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort))
}
}
return ports
}
46 changes: 44 additions & 2 deletions galvanize-instancer/internal/ansible/connection_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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{}{
Expand Down
4 changes: 2 additions & 2 deletions galvanize-instancer/internal/ansible/deployer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading