LOADING

加载过慢请开启缓存 浏览器默认开启

ZiAzusa#2024W7 运维:搭建CTFd平台的踩坑过程

2024/12/17 周报 运维 Docker
字数统计: 5.8k字 阅读时长: 约30分 本文阅读量:

#0 安装docker和docker-compose

Debian 12和Ubuntu 24.04可以直接使用以下命令:

sudo apt install docker.io
sudo apt install docker-compose

实际上搭建CTFd本身是“非常简单”的,只需要 git clone,然后docker-compose up -d

然后就会卡在第一步的docker pull。

#1 Docker换源

因为一些众所周知的原因,在国内访问DockerHub远比GitHub困难得多,而且绝大多数云服务商的Docker镜像源现在都只能在他们的内网使用了…

最后考虑使用赛博大善人Cloudflare的Workers搭建反向代理服务。

直接使用 这个项目 的workers.js模板即可:

// _worker.js

// Docker镜像仓库主机地址
let hub_host = 'registry-1.docker.io';
// Docker认证服务器地址
const auth_url = 'https://auth.docker.io';
// 自定义的工作服务器地址
let workers_url = 'https://xxx/';

let 屏蔽爬虫UA = ['netcraft'];

// 根据主机名选择对应的上游地址
function routeByHosts(host) {
    // 定义路由表
    const routes = {
        // 生产环境
        "quay": "quay.io",
        "gcr": "gcr.io",
        "k8s-gcr": "k8s.gcr.io",
        "k8s": "registry.k8s.io",
        "ghcr": "ghcr.io",
        "cloudsmith": "docker.cloudsmith.io",
        "nvcr": "nvcr.io",
        
        // 测试环境
        "test": "registry-1.docker.io",
    };

    if (host in routes) return [ routes[host], false ];
    else return [ hub_host, true ];
}

/** @type {RequestInit} */
const PREFLIGHT_INIT = {
    // 预检请求配置
    headers: new Headers({
        'access-control-allow-origin': '*', // 允许所有来源
        'access-control-allow-methods': 'GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS', // 允许的HTTP方法
        'access-control-max-age': '1728000', // 预检请求的缓存时间
    }),
}

/**
 * 构造响应
 * @param {any} body 响应体
 * @param {number} status 响应状态码
 * @param {Object<string, string>} headers 响应头
 */
function makeRes(body, status = 200, headers = {}) {
    headers['access-control-allow-origin'] = '*' // 允许所有来源
    return new Response(body, { status, headers }) // 返回新构造的响应
}

/**
 * 构造新的URL对象
 * @param {string} urlStr URL字符串
 */
function newUrl(urlStr) {
    try {
        return new URL(urlStr) // 尝试构造新的URL对象
    } catch (err) {
        return null // 构造失败返回null
    }
}

function isUUID(uuid) {
    // 定义一个正则表达式来匹配 UUID 格式
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
    
    // 使用正则表达式测试 UUID 字符串
    return uuidRegex.test(uuid);
}

async function nginx() {
    const text = `<!DOCTYPE html><html><head><title>Welcome to nginx!</title><style>body{width:35em;margin:0 auto;font-family:Tahoma,Verdana,Arial,sans-serif}</style></head><body><h1>Welcome to nginx!</h1><p>If you see this page,the nginx web server is successfully installed and working.Further configuration is required.</p><p>For online documentation and support please refer to<a href="http://nginx.org/">nginx.org</a>.<br/>Commercial support is available at<a href="http://nginx.com/">nginx.com</a>.</p><p><em>Thank you for using nginx.</em></p></body></html>`
    return text;
}

async function searchInterface() {
    const text = `<!DOCTYPE html><html><head><title>Docker Hub Search</title><style>body{font-family:Arial,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0;background:linear-gradient(to right,rgb(28,143,237),rgb(29,99,237))}.logo{margin-bottom:20px}.search-container{display:flex;align-items:center}#search-input{padding:10px;font-size:16px;border:1px solid#ddd;border-radius:4px;width:300px;margin-right:10px}#search-button{padding:10px;background-color:rgba(255,255,255,0.2);border:none;border-radius:4px;cursor:pointer;width:44px;height:44px;display:flex;align-items:center;justify-content:center}#search-button svg{width:24px;height:24px}</style></head><body><div class="logo"><svg xmlns="http://www.w3.org/2000/svg"viewBox="0 0 24 18"fill="#ffffff"width="100"height="75"><path d="M23.763 6.886c-.065-.053-.673-.512-1.954-.512-.32 0-.659.03-1.01.087-.248-1.703-1.651-2.533-1.716-2.57l-.345-.2-.227.328a4.596 4.596 0 0 0-.611 1.433c-.23.972-.09 1.884.403 2.666-.596.331-1.546.418-1.744.42H.752a.753.753 0 0 0-.75.749c-.007 1.456.233 2.864.692 4.07.545 1.43 1.355 2.483 2.409 3.13 1.181.725 3.104 1.14 5.276 1.14 1.016 0 2.03-.092 2.93-.266 1.417-.273 2.705-.742 3.826-1.391a10.497 10.497 0 0 0 2.61-2.14c1.252-1.42 1.998-3.005 2.553-4.408.075.003.148.005.221.005 1.371 0 2.215-.55 2.68-1.01.505-.5.685-.998.704-1.053L24 7.076l-.237-.19Z"></path><path d="M2.216 8.075h2.119a.186.186 0 0 0 .185-.186V6a.186.186 0 0 0-.185-.186H2.216A.186.186 0 0 0 2.031 6v1.89c0 .103.083.186.185.186Zm2.92 0h2.118a.185.185 0 0 0 .185-.186V6a.185.185 0 0 0-.185-.186H5.136A.185.185 0 0 0 4.95 6v1.89c0 .103.083.186.186.186Zm2.964 0h2.118a.186.186 0 0 0 .185-.186V6a.186.186 0 0 0-.185-.186H8.1A.185.185 0 0 0 7.914 6v1.89c0 .103.083.186.186.186Zm2.928 0h2.119a.185.185 0 0 0 .185-.186V6a.185.185 0 0 0-.185-.186h-2.119a.186.186 0 0 0-.185.186v1.89c0 .103.083.186.185.186Zm-5.892-2.72h2.118a.185.185 0 0 0 .185-.186V3.28a.186.186 0 0 0-.185-.186H5.136a.186.186 0 0 0-.186.186v1.89c0 .103.083.186.186.186Zm2.964 0h2.118a.186.186 0 0 0 .185-.186V3.28a.186.186 0 0 0-.185-.186H8.1a.186.186 0 0 0-.186.186v1.89c0 .103.083.186.186.186Zm2.928 0h2.119a.185.185 0 0 0 .185-.186V3.28a.186.186 0 0 0-.185-.186h-2.119a.186.186 0 0 0-.185.186v1.89c0 .103.083.186.185.186Zm0-2.72h2.119a.186.186 0 0 0 .185-.186V.56a.185.185 0 0 0-.185-.186h-2.119a.186.186 0 0 0-.185.186v1.89c0 .103.083.186.185.186Zm2.955 5.44h2.118a.185.185 0 0 0 .186-.186V6a.185.185 0 0 0-.186-.186h-2.118a.185.185 0 0 0-.185.186v1.89c0 .103.083.186.185.186Z"></path></svg></div><div class="search-container"><input type="text"id="search-input"placeholder="Search Docker Hub"><button id="search-button"><svg focusable="false"aria-hidden="true"viewBox="0 0 24 24"fill="none"xmlns="http://www.w3.org/2000/svg"><path d="M21 21L16.65 16.65M19 11C19 15.4183 15.4183 19 11 19C6.58172 19 3 15.4183 3 11C3 6.58172 6.58172 3 11 3C15.4183 3 19 6.58172 19 11Z"stroke="white"fill="none"stroke-width="2"stroke-linecap="round"stroke-linejoin="round"></path></svg></button></div><script>function performSearch(){const query=document.getElementById('search-input').value;if(query){window.location.href='/search?q='+encodeURIComponent(query)}}document.getElementById('search-button').addEventListener('click',performSearch);document.getElementById('search-input').addEventListener('keypress',function(event){if(event.key==='Enter'){performSearch()}});</script></body></html>`;
    return text;
}

export default {
    async fetch(request, env, ctx) {
        const getReqHeader = (key) => request.headers.get(key); // 获取请求头

        let url = new URL(request.url); // 解析请求URL
        const userAgentHeader = request.headers.get('User-Agent');
        const userAgent = userAgentHeader ? userAgentHeader.toLowerCase() : "null";
        if (env.UA) 屏蔽爬虫UA = 屏蔽爬虫UA.concat(await ADD(env.UA));
        workers_url = `https://${url.hostname}`;
        const pathname = url.pathname;

        // 获取请求参数中的 ns
        const ns = url.searchParams.get('ns'); 
        const hostname = url.searchParams.get('hubhost') || url.hostname;
        const hostTop = hostname.split('.')[0]; // 获取主机名的第一部分

        let checkHost; // 在这里定义 checkHost 变量
        // 如果存在 ns 参数,优先使用它来确定 hub_host
        if (ns) {
            if (ns === 'docker.io') {
                hub_host = 'registry-1.docker.io'; // 设置上游地址为 registry-1.docker.io
            } else {
                hub_host = ns; // 直接使用 ns 作为 hub_host
            }
        } else {
            checkHost = routeByHosts(hostTop);
            hub_host = checkHost[0]; // 获取上游地址
        }

        const fakePage = checkHost ? checkHost[1] : false; // 确保 fakePage 不为 undefined
        console.log(`域名头部: ${hostTop}\n反代地址: ${hub_host}\n伪装首页: ${fakePage}`);
        const isUuid = isUUID(pathname.split('/')[1].split('/')[0]);

        if (屏蔽爬虫UA.some(fxxk => userAgent.includes(fxxk)) && 屏蔽爬虫UA.length > 0) {
            // 首页改成一个nginx伪装页
            return new Response(await nginx(), {
                headers: {
                    'Content-Type': 'text/html; charset=UTF-8',
                },
            });
        }

        const conditions = [
            isUuid,
            pathname.includes('/_'),
            pathname.includes('/r/'),
            pathname.includes('/v2/repositories'),
            pathname.includes('/v2/user'),
            pathname.includes('/v2/orgs'),
            pathname.includes('/v2/_catalog'),
            pathname.includes('/v2/categories'),
            pathname.includes('/v2/feature-flags'),
            pathname.includes('search'),
            pathname.includes('source'),
            pathname == '/',
            pathname == '/favicon.ico',
            pathname == '/auth/profile',
        ];

        if (conditions.some(condition => condition) && (fakePage === true || hostTop == 'docker')) {
            if (env.URL302) {
                return Response.redirect(env.URL302, 302);
            } else if (env.URL) {
                if (env.URL.toLowerCase() == 'nginx') {
                    //首页改成一个nginx伪装页
                    return new Response(await nginx(), {
                        headers: {
                            'Content-Type': 'text/html; charset=UTF-8',
                        },
                    });
                } else return fetch(new Request(env.URL, request));
            } else if (url.pathname == '/'){
                return new Response(await searchInterface(), {
                    headers: {
                      'Content-Type': 'text/html; charset=UTF-8',
                    },
                });
            }
            
            const newUrl = new URL("https://registry.hub.docker.com" + pathname + url.search);

            // 复制原始请求的标头
            const headers = new Headers(request.headers);

            // 确保 Host 头部被替换为 hub.docker.com
            headers.set('Host', 'registry.hub.docker.com');

            const newRequest = new Request(newUrl, {
                    method: request.method,
                    headers: headers,
                    body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.blob() : null,
                    redirect: 'follow'
            });

            return fetch(newRequest);
        }

        // 修改包含 %2F 和 %3A 的请求
        if (!/%2F/.test(url.search) && /%3A/.test(url.toString())) {
            let modifiedUrl = url.toString().replace(/%3A(?=.*?&)/, '%3Alibrary%2F');
            url = new URL(modifiedUrl);
            console.log(`handle_url: ${url}`);
        }

        // 处理token请求
        if (url.pathname.includes('/token')) {
            let token_parameter = {
                headers: {
                    'Host': 'auth.docker.io',
                    'User-Agent': getReqHeader("User-Agent"),
                    'Accept': getReqHeader("Accept"),
                    'Accept-Language': getReqHeader("Accept-Language"),
                    'Accept-Encoding': getReqHeader("Accept-Encoding"),
                    'Connection': 'keep-alive',
                    'Cache-Control': 'max-age=0'
                }
            };
            let token_url = auth_url + url.pathname + url.search;
            return fetch(new Request(token_url, request), token_parameter);
        }

        // 修改 /v2/ 请求路径
        if ( hub_host == 'registry-1.docker.io' && /^\/v2\/[^/]+\/[^/]+\/[^/]+$/.test(url.pathname) && !/^\/v2\/library/.test(url.pathname)) {
            //url.pathname = url.pathname.replace(/\/v2\//, '/v2/library/');
            url.pathname = '/v2/library/' + url.pathname.split('/v2/')[1];
            console.log(`modified_url: ${url.pathname}`);
        }

        // 更改请求的主机名
        url.hostname = hub_host;

        // 构造请求参数
        let parameter = {
            headers: {
                'Host': hub_host,
                'User-Agent': getReqHeader("User-Agent"),
                'Accept': getReqHeader("Accept"),
                'Accept-Language': getReqHeader("Accept-Language"),
                'Accept-Encoding': getReqHeader("Accept-Encoding"),
                'Connection': 'keep-alive',
                'Cache-Control': 'max-age=0'
            },
            cacheTtl: 3600 // 缓存时间
        };

        // 添加Authorization头
        if (request.headers.has("Authorization")) {
            parameter.headers.Authorization = getReqHeader("Authorization");
        }

        // 发起请求并处理响应
        let original_response = await fetch(new Request(url, request), parameter);
        let original_response_clone = original_response.clone();
        let original_text = original_response_clone.body;
        let response_headers = original_response.headers;
        let new_response_headers = new Headers(response_headers);
        let status = original_response.status;

        // 修改 Www-Authenticate 头
        if (new_response_headers.get("Www-Authenticate")) {
            let auth = new_response_headers.get("Www-Authenticate");
            let re = new RegExp(auth_url, 'g');
            new_response_headers.set("Www-Authenticate", response_headers.get("Www-Authenticate").replace(re, workers_url));
        }

        // 处理重定向
        if (new_response_headers.get("Location")) {
            return httpHandler(request, new_response_headers.get("Location"));
        }

        // 返回修改后的响应
        let response = new Response(original_text, {
            status,
            headers: new_response_headers
        });
        return response;
    }
};

/**
 * 处理HTTP请求
 * @param {Request} req 请求对象
 * @param {string} pathname 请求路径
 */
function httpHandler(req, pathname) {
    const reqHdrRaw = req.headers;

    // 处理预检请求
    if (req.method === 'OPTIONS' &&
        reqHdrRaw.has('access-control-request-headers')
    ) {
        return new Response(null, PREFLIGHT_INIT);
    }

    let rawLen = '';

    const reqHdrNew = new Headers(reqHdrRaw);

    const refer = reqHdrNew.get('referer');

    let urlStr = pathname;

    const urlObj = newUrl(urlStr);

    /** @type {RequestInit} */
    const reqInit = {
        method: req.method,
        headers: reqHdrNew,
        redirect: 'follow',
        body: req.body
    };
    return proxy(urlObj, reqInit, rawLen);
}

/**
 * 代理请求
 * @param {URL} urlObj URL对象
 * @param {RequestInit} reqInit 请求初始化对象
 * @param {string} rawLen 原始长度
 */
async function proxy(urlObj, reqInit, rawLen) {
    const res = await fetch(urlObj.href, reqInit);
    const resHdrOld = res.headers;
    const resHdrNew = new Headers(resHdrOld);

    // 验证长度
    if (rawLen) {
        const newLen = resHdrOld.get('content-length') || '';
        const badLen = (rawLen !== newLen);

        if (badLen) {
            return makeRes(res.body, 400, {
                '--error': `bad len: ${newLen}, except: ${rawLen}`,
                'access-control-expose-headers': '--error',
            });
        }
    }
    const status = res.status;
    resHdrNew.set('access-control-expose-headers', '*');
    resHdrNew.set('access-control-allow-origin', '*');
    resHdrNew.set('Cache-Control', 'max-age=1500');

    // 删除不必要的头
    resHdrNew.delete('content-security-policy');
    resHdrNew.delete('content-security-policy-report-only');
    resHdrNew.delete('clear-site-data');

    return new Response(res.body, {
        status,
        headers: resHdrNew
    });
}

async function ADD(envadd) {
    var addtext = envadd.replace(/[	 |"'\r\n]+/g, ',').replace(/,+/g, ',');	// 将空格、双引号、单引号和换行符替换为逗号
    if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
    if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1);
    const add = addtext.split(',');
    return add;
}

接下来修改 /etc/docker/daemon.json(docker.domain是自建的反代服务地址):

{
  "registry-mirrors": [
    "https://docker.domain"
  ]
}

接下来重载配置并重启docker:

sudo systemctl daemon-reload
sudo systemctl restart docker
sudo systemctl restart docker.socket

这样第一步Docker源无法访问的问题就解决了。

当我们满心欢喜看着这个docker pull飞速的完成了,我们就迎来了第二个问题…

在镜像内还需要使用apt安装很多软件包,但显然debian的apt源和pip源也不是那么可靠…

#2 更换镜像内的apt源和pip源

首先准备好清华源的debian.sources,将其放置于CTFd的运行目录:

Types: deb
URIs: https://mirrors.tuna.tsinghua.edu.cn/debian
Suites: bookworm bookworm-updates bookworm-backports
Components: main contrib non-free non-free-firmware
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

# 默认注释了源码镜像以提高 apt update 速度,如有需要可自行取消注释
# Types: deb-src
# URIs: https://mirrors.tuna.tsinghua.edu.cn/debian
# Suites: bookworm bookworm-updates bookworm-backports
# Components: main contrib non-free non-free-firmware
# Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

# 以下安全更新软件源包含了官方源与镜像站配置,如有需要可自行修改注释切换
Types: deb
URIs: https://security.debian.org/debian-security
Suites: bookworm-security
Components: main contrib non-free non-free-firmware
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

# Types: deb-src
# URIs: https://security.debian.org/debian-security
# Suites: bookworm-security
# Components: main contrib non-free non-free-firmware
# Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

然后直接修改官方的Dockerfile为以下内容:

FROM python:3.11-slim-bookworm AS build

WORKDIR /opt/CTFd

# hadolint ignore=DL3008
COPY . /opt/CTFd

RUN rm -rf /etc/apt/sources.list.d/* \
    && mv /opt/CTFd/debian.sources /etc/apt/sources.list.d/debian.sources \
    && apt-get update \
    && apt-get install -y --no-install-recommends \
        build-essential \
        libffi-dev \
        libssl-dev \
        git \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* \
    && python -m venv /opt/venv

ENV PATH="/opt/venv/bin:$PATH"

RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt \
    && for d in CTFd/plugins/*; do \
        if [ -f "$d/requirements.txt" ]; then \
            pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple -r "$d/requirements.txt"; \
        fi; \
    done; 

FROM python:3.11-slim-bookworm AS release
WORKDIR /opt/CTFd

# hadolint ignore=DL3008
COPY --chown=1001:1001 . /opt/CTFd

RUN rm -rf /etc/apt/sources.list.d/* \
    && mv /opt/CTFd/debian.sources /etc/apt/sources.list.d/debian.sources \
    && apt-get update \
    && apt-get install -y --no-install-recommends \
        libffi8 \
        libssl3 \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

RUN useradd \
    --no-log-init \
    --shell /bin/bash \
    -u 1001 \
    ctfd \
    && mkdir -p /var/log/CTFd /var/uploads \
    && chown -R 1001:1001 /var/log/CTFd /var/uploads /opt/CTFd \
    && chmod +x /opt/CTFd/docker-entrypoint.sh

COPY --chown=1001:1001 --from=build /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

USER 1001
EXPOSE 8000
ENTRYPOINT ["/opt/CTFd/docker-entrypoint.sh"]

这里rm掉了镜像内原有的apt源,然后直接将新的debian.sources替换进去。

pip就不使用永久换源了,直接 -i 镜像源地址 即可。

终于,可以使用 docker-compose up -d 启动服务了…

但此时的CTFd并不能开启动态靶机,我们还需要安装 ctfd-whale 这个插件。

#3 配置FRP网络

在ctfd-whale的install.md里面给出了一个“非常简单”的安装脚本:

curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh --mirror Aliyun
docker swarm init # 初始化Docker集群
docker node update --label-add='name=linux-xxx' $(docker node ls -q) # 为宿主机分配节点名称,xxx为int

git clone https://github.com/CTFd/CTFd --depth=1
git clone https://github.com/frankli0324/ctfd-whale CTFd/CTFd/plugins/ctfd-whale --depth=1
curl -fsSL https://cdn.jsdelivr.net/gh/frankli0324/ctfd-whale/docker-compose.example.yml -o CTFd/docker-compose.yml

# make sure you have pip3 installed on your rig
pip3 install docker-compose
docker-compose -f CTFd/docker-compose.yml up -d
docker-compose -f CTFd/docker-compose.yml exec ctfd python manage.py

但你要是信了他的鬼话,说什么运行完你就装好了,那怕是要哭断肠去了…

他给出的docker-compose.example.yml没有对frp使用的网络进行任何配置,同时token和host也必须重新配置。

修改后的docker-compose.yml如下:

version: '3.7'

services:
  ctfd:
    build: .
    user: root
    restart: always
    ports:
      - "8000:8000" # 映射CTFd端口
    environment:
      - UPLOAD_FOLDER=/var/uploads
      - DATABASE_URL=mysql+pymysql://用户名:密码@db/数据库名
      - REDIS_URL=redis://cache:6379
      - WORKERS=1
      - LOG_FOLDER=/var/log/CTFd
      - ACCESS_LOG=-
      - ERROR_LOG=-
      - REVERSE_PROXY=true
    volumes:
      - .data/CTFd/logs:/var/log/CTFd
      - .data/CTFd/uploads:/var/uploads
      - .:/opt/CTFd:ro
    # 由于unix socket在后续发现并不能用,在这里就禁用掉映射
    #  - /var/run/docker.sock:/var/run/docker.sock
    depends_on:
      - db
      - frpc
    networks:
        default:
        internal:
        frp_connect:

  # 禁用nginx反代,由于80端口本就不可用
  #nginx:
  #  image: nginx:1.17
  #  restart: always
  #  volumes:
  #    - ./conf/nginx/http.conf:/etc/nginx/nginx.conf
  #  ports:
  #    - 80:80
  #  depends_on:
  #    - ctfd

  db:
    image: mariadb:10.4.12
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD= # 数据库容器的root密码
      - MYSQL_USER= # MariaDB用户名
      - MYSQL_PASSWORD= # MariaDB密码
      - MYSQL_DATABASE= # MariaDB数据库名
    volumes:
      - .data/mysql:/var/lib/mysql
    networks:
        internal:
    # This command is required to set important mariadb defaults
    command: [mysqld, --character-set-server=utf8mb4, --collation-server=utf8mb4_unicode_ci, --wait_timeout=28800, --log-warnings=0]

  cache:
    image: redis:4
    restart: always
    volumes:
    - .data/redis:/data
    networks:
        internal:

  frpc:
    image: frankli0324/frp:frpc
    restart: always
    command: [
      "--server_addr=frps",
      "--server_port=", # FRPS的端口
      "--token=", # 使用生成器生成的随机Token
      "--admin_addr=0.0.0.0",
      "--admin_port=", # API端口,用于后续的ctfd-whale配置项
      "--admin_user=", # FRPC用户名,用于后续的ctfd-whale配置项
      "--admin_pwd=", # 使用生成器生成的随机FRPC Passwd,用于后续的ctfd-whale配置项
    ]
    depends_on:
      - frps
    networks:
      frp_connect:
        ipv4_address: # 一定要在这里固定IP地址,确保后续的ctf-whale配置,注意要与下文frp_connect设置的网段一致
      internal:
      frp_container:

  frps:
    image: frankli0324/frp:frps
    restart: always
    command: [
      "--bind_addr=0.0.0.0",
      "--bind_port=", # FRPS的端口,用于FRPC连接
      "--token=", # 使用生成器生成的随机Token,与上文一致
      "--subdomain_host=", # http类型题目的主域名
      "--vhost_http_port=", # http类型题目的端口
    ]
    ports:
      - 1xxxx-1xxxx:1xxxx-1xxxx  # 映射direct类型题目的端口
      - xxxx:xxxx # 映射http类型题目的端口
    networks:
      frp_connect:
      default:
      internal:

networks:
    default:
    internal:
      internal: true
    frp_connect: # 用于FRPC与FRPS的连接,和ctfd-whale和FRPC的连接
      driver: overlay
      internal: true
      ipam:
        config:
          - subnet: 172.114.0.0/16 # 固定网段
    frp_container: # 用于创建容器
      internal: false
      driver: overlay
      attachable: true
      ipam:
        config:
          - subnet: 172.514.0.0/16 # 固定网段

而后配置好便可正常启动了。

已经将修改后的Dockerfile和docker-compose.yml备份

#4 配置ctfd-whale:

由于测试发现默认的unix socket,即 unix:///var/run/docker.sock 并不能正常地连接到宿主机的Docker,这里转为使用tcp socket。

修改/lib/systemd/system/docker.service的启动命令部分:

ExecStart=/usr/sbin/dockerd -H fd:// -H tcp://172.17.0.1:xxxxx --containerd=/run/containerd/containerd.sock $DOCKER_OPTS
# 注意这里一定要使用172.17.0.1,172.17.0.0/16是docker的默认网段
# 切忌将docker.socket API暴露到公网...

修改后依然需要重载配置并重启Docker。

而后ctfd-whale配置如下(网上的全是旧版本的ctf-whale教程,这里需要重新摸索):

Docker选项卡:

Common:
  API URL: tcp://172.17.0.1:xxxxx
  Credentials: # 置空,或填入DockerHub的账号密码(但是也连不上~)
  Swarm Nodes: linux-xxx # 在第一步初始化docker集群时为宿主机分配的节点名称
    Use SSL: false

Standalone Containers:
  Auto Connect Network: ctfd_frp_connect # 关注docker-compose up -d的logs,找到最开始设置的frp_connect网络在Docker里面的实际名称
  Dns Setting: 223.5.5.5 # 随意配置一个可用的DNS即可,这里使用阿里云的。

Grouped Containers:
  Auto Connect Containers: ctfd_frpc_1 # 关注docker-compose up -d的logs,找到最开始设置的frpc容器在Docker里面的实际名称
  Multi-Container Network Subnet: 174.1.0.0/16
  Multi-Container Network Subnet New Prefix: 24

Router选项卡:

Router type: frp
API URL: http://设置的FRPC用户名:设置的FRPC密码@frpc:设置的FRPC端口
# 注意务必按照以上格式填写,否则会报认证错误
Http Domain Suffix: 在docker-compose.yml设置的HTTP题目的主域名
External Http Port: 在docker-compose.yml设置的HTTP题目的端口
Direct IP Address: 服务器公网IP(或内网IP),用于Direct类题目
Direct Minimum Port: 与上文设置的Direct类题目端口最小值一致
Direct Maximum Port: 与上文设置的Direct类题目端口最大值一致
Frpc config template: # 置空,保存后自动生成
Frps config template [generated]: # 置空,保存后自动生成

其余选项无特殊需求用默认即可。

如无问题,现在已经可以正常创建dynamic_docker类型的题目了。

#5 有关../和DELETE请求的问题

学校防火墙ban掉了URL包含../的请求和所有80端口上DELETE类型的请求…

所以CTFd只能跑在非80端口,否则无法正常地关闭靶机和删除题目(这些操作需要使用DELETE请求)。

#6 迁移…

简单地研究就能发现CTFd是自带了Export和Import功能的,可以利用这个功能“方便”地实现迁移。

在旧平台导出,然后在新平台导入…

然后不出意外地问题就出现了,由于ctfd-whale在版本更新的过程中修改过全部的配置文件结构,所以引入会直接报500错误。

最后的解决方式是,首先在新平台导出,然后用新平台的db/config.json文件替换旧平台的db/config.json文件,然后再导入新平台。

但是即使ctfd-whale正常工作了,旧平台创建的dynamic_docker类型的题目依然无法启动,查看 docker logs,依然是配置文件结构问题,经过测试新平台创建的dynamic_docker并无问题,而查看数据库导出文件也没有区别,遂放弃。

之后考虑直接重新创建旧平台的dynamic_docker题目,反正也不多(´ー∀ー`)

#7 迁移之后…

本来运行的还挺好的,但是在执行 docker-compose down 后重新启动CTFd,发现就启动不了了。

查看 docker logs 发现问题出在数据库版本错误…

依然使用新平台的db/alembic_version.json文件替换旧平台的db/alembic_version.json文件,然后再导入新平台即可。

#8 有关动态flag的题目创建

首先在创建题目时将flag置空,而后需要配置题目的Dockerfile和start.sh,以glzjin/hctf_2018_warmup为例:

Dockerfile:

FROM php:5.6.36-apache

LABEL Author="CoColi <CoColizdf@163.com>"

ADD src /var/www/html

RUN mv /var/www/html/ffffllllaaaagggg / \
    && docker-php-source extract\
    && cp /usr/src/php/php.ini-production /usr/local/etc/php/php.ini \
    && sed -i -e 's/display_errors.*/display_errors = Off/' /usr/local/etc/php/php.ini \
    && mkdir /init-scripts/ \
    && mv /var/www/html/start.sh /init-scripts/ \
    && chmod +x /init-scripts/start.sh
EXPOSE 80

ENTRYPOINT ["/init-scripts/start.sh"] # 重点关注这里,即需要使用start.sh配置flag

start.sh:

#!/usr/bin/env bash

echo $FLAG > /ffffllllaaaagggg # CTFd会将生成的动态flag写入靶机的环境变量,所以可以直接将该环境变量写入flag文件

export FLAG=not_flag # 清空环境变量,否则解题人就能读取/proc/1/environ拿flag了...
FLAG=not_flag

apache2-foreground

经过测试,靶机运行正常,提交动态flag会判定为正确。

#INFINITY 后续

之后还需研究限制用户开启的靶机数目,对题目进行分类,以及避免插件冲突等问题。

路漫漫其修远兮,吾将上下而求索。