Initial release of ctfcli

ctfcli-challenge-finalize-command
Kevin Chung 2020-04-02 12:33:16 -04:00
commit 354ebfe9e9
59 changed files with 1660 additions and 0 deletions

135
.gitignore vendored Normal file
View File

@ -0,0 +1,135 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
dist/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# Miscellaneous
.DS_Store
.vscode/
.ctf/

11
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,11 @@
image: python:3.7
before_script:
- python -V
- mkdir -p .pip
- pip install --upgrade pip
- pip install --cache-dir='.pip' -r development.txt
test:
script:
- make lint

42
CHANGELOG Normal file
View File

@ -0,0 +1,42 @@
# Changelog
0.0.2 / 2020-04-02
==================
### Added
- Initial release of ctfcli
- `ctf init` commands
- `ctf challenge` commands
- `ctf config` commands
- `ctf plugins` commands
- README and basic example on plugins
### Changed
- Nothing
### Removed
- Removed initial stub release from source control
0.0.1 / 2020-01-01
==================
### Added
- Stub release
### Changed
- Nothing
### Removed
- Nothing
0.0.1 / 2020-01-01
==================
### Added
- Initial stub release of ctfcli
### Changed
- Nothing
### Removed
- Nothing

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 CTFd LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

5
MANIFEST.in Normal file
View File

@ -0,0 +1,5 @@
include LICENSE
include README.md
recursive-include ctfcli/templates *
recursive-include ctfcli/utils *
recursive-include ctfcli/spec *

29
Makefile Normal file
View File

@ -0,0 +1,29 @@
lint:
flake8 --ignore=E402,E501,E712,W503,E203,I002 --exclude=ctfcli/templates **/*.py
black --check --exclude=ctfcli/templates .
format:
black --exclude=ctfcli/templates .
install:
python3 setup.py install
build:
python3 setup.py sdist bdist_wheel
clean:
rm -rf build/
rm -rf dist/
rm -rf ctfcli.egg-info/
publish-test:
@echo "Publishing to TestPyPI"
@echo "Are you sure? [y/N] " && read ans && [ $${ans:-N} == y ]
python3 setup.py sdist bdist_wheel
twine upload --repository test dist/*
publish-pypi:
@echo "Publishing to PyPI"
@echo "ARE YOU ABSOLUTELY SURE? [y/N] " && read ans && [ $${ans:-N} == y ]
python3 setup.py sdist bdist_wheel
twine upload --repository pypi dist/*

125
README.md Normal file
View File

@ -0,0 +1,125 @@
# ctfcli
*ctfcli is a tool to manage Capture The Flag events and challenges.*
`ctfcli` provides challenge specifications and templates to make it easier to generate challenges of different categories. It also provides an integration with the [CTFd](https://github.com/CTFd/CTFd/) REST API to allow for command line uploading of challenges and integration with CI/CD build systems.
`ctfcli` features tab completion, a REPL interface (thanks to [Python-Fire](https://github.com/google/python-fire)) and plugin support for custom commands.
*WIP: ctfcli is an alpha project and changes will happen. Be sure to pin versions and read the CHANGELOG when updating.*
# Installation and Usage
ctfcli can be installed with `pip install ctfcli`
## 1. Create an Event
ctfcli turns the current folder into a CTF event git repo. It asks for the base url of the CTFd instance you're working with ahd an access token.
```
ctf init
Please enter CTFd instance URL: https://demo.ctfd.io
Please enter CTFd Admin Access Token: d41d8cd98f00b204e9800998ecf8427e
Do you want to continue with https://demo.ctfd.io and d41d8cd98f00b204e9800998ecf8427e [y/N]: y
Initialized empty Git repository in /Users/user/Downloads/event/.git/
```
This will create the `.ctf` folder with the `config` file that will specify the URL, access token, and keep a record of all the challenges dedicated for this event.
## 2. Add challenges
Events are made up of challenges. Challenges can be made from a subdirectory or pulled from another repository. Remote challenges are pulled into the event repo and a reference is kept in the `.ctf/config` file.
```
ctf challenge add [REPO | FOLDER]
```
```
ctf challenge add crypto/stuff
```
```
ctf challenge add https://github.com/challenge.git
challenge
Cloning into 'challenge'...
remote: Enumerating objects: 624, done.
remote: Counting objects: 100% (624/624), done.
remote: Compressing objects: 100% (540/540), done.
remote: Total 624 (delta 109), reused 335 (delta 45), pack-reused 0
Receiving objects: 100% (624/624), 6.49 MiB | 21.31 MiB/s, done.
Resolving deltas: 100% (109/109), done.
```
## 3. Install challenges
Installing a challenge will automatically create the challenge in your CTFd instance using the API.
```
ctf challenge install [challenge.yml | DIRECTORY]
```
```
ctf challenge install buffer_overflow
Found buffer_overflow/challenge.yml
Loaded buffer_overflow
Installing buffer_overflow
Success!
```
## 4. Update challenges
Syncing a challenge will automatically update the challenge in your CTFd instance using the API. Any changes made in the `challenge.yml` file will be reflected in your instance.
```
ctf challenge sync [challenge.yml | DIRECTORY]
```
```
ctf challenge sync buffer_overflow
Found buffer_overflow/challenge.yml
Loaded buffer_overflow
Syncing buffer_overflow
Success!
```
# Challenge Templates
`ctfcli` contains pre-made challenge templates to make it faster to create CTF challenges with safe defaults.
```
ctf challenge new
├── binary
├── crypto
├── programming
└── web
```
```
ctf challenge new binary
/Users/user/.virtualenvs/ctfcli/lib/python3.7/site-packages/ctfcli-0.0.1-py3.7.egg/ctfcli/templates/binary/default
name [Hello]: buffer_overflow
ls -1 buffer_overflow
Makefile
README.md
WRITEUP.md
challenge.yml
dist/
src/
```
**Contributions welcome on improving the challenge templates to make CTF challenges better for everyone!**
# Challenge Specification
`ctfcli` provides a [challenge specification](ctfcli/spec/challenge-example.yml) (`challenge.yml`) that outlines the major details of a challenge.
Every challenge generated by or processed by `ctfcli` should have a `challenge.yml` file.
The specification format has already been tested and used with CTFd in production events but comments, suggestions, and PRs are welcome on the format of `challenge.yml`.
# Plugins
`ctfcli` plugins are essentially additions to to the command line interface via dynamic class modifications. See the [plugin documentation page](docs/plugins.md) for a simple example.
*`ctfcli` is an alpha project! The plugin interface is likely to change!*

2
ctfcli/__init__.py Normal file
View File

@ -0,0 +1,2 @@
__version__ = "0.0.2"
__name__ = "ctfcli"

78
ctfcli/__main__.py Normal file
View File

@ -0,0 +1,78 @@
import configparser
import importlib
import os
import subprocess
import sys
from pathlib import Path
import click
from ctfcli.cli.challenges import Challenge
from ctfcli.cli.config import Config
from ctfcli.cli.plugins import Plugins
from ctfcli.utils.plugins import get_plugin_dir
import fire
class CTFCLI(object):
def init(self):
ctf_url = click.prompt("Please enter CTFd instance URL")
ctf_token = click.prompt("Please enter CTFd Admin Access Token")
if (
click.confirm(f"Do you want to continue with {ctf_url} and {ctf_token}")
is False
):
click.echo("Aborted!")
return
if Path(".ctf").exists():
click.secho(".ctf/ folder already exists. Aborting!", fg="red")
return
os.mkdir(".ctf")
config = configparser.ConfigParser()
config["config"] = {"url": ctf_url, "access_token": ctf_url}
config["challenges"] = {}
with open(".ctf/config", "a+") as f:
config.write(f)
subprocess.call(["git", "init"])
def config(self):
return COMMANDS.get("config")
def challenge(self):
return COMMANDS.get("challenge")
def plugins(self):
return COMMANDS.get("plugins")
COMMANDS = {
"challenge": Challenge(),
"config": Config(),
"plugins": Plugins(),
"cli": CTFCLI(),
}
def main():
# Load plugins
plugin_dir = get_plugin_dir()
sys.path.insert(0, plugin_dir)
for plugin in sorted(os.listdir(plugin_dir)):
plugin_path = os.path.join(plugin_dir, plugin, "__init__.py")
print("Loading", plugin_path, "as", plugin)
loaded = importlib.import_module(plugin)
loaded.load(COMMANDS)
sys.path.remove(plugin_dir)
# Load CLI
fire.Fire(CTFCLI)
if __name__ == "__main__":
main()

0
ctfcli/cli/__init__.py Normal file
View File

141
ctfcli/cli/challenges.py Normal file
View File

@ -0,0 +1,141 @@
import os
import shutil
import subprocess
from cookiecutter.main import cookiecutter
from pathlib import Path
import click
from ctfcli.utils.challenge import (
create_challenge,
lint_challenge,
load_challenge,
load_installed_challenges,
sync_challenge,
)
from ctfcli.utils.config import (
get_base_path,
get_config_path,
get_project_path,
load_config,
)
class Challenge(object):
def new(self, type):
path = Path(get_base_path())
if os.sep not in type:
type += os.sep + "default"
path = path / "templates" / type
cookiecutter(str(path))
def add(self, repo):
config = load_config()
if repo.endswith(".git"):
# Get relative path from project root to current directory
challenge_path = Path(os.path.relpath(os.getcwd(), get_project_path()))
# Get new directory that will exist after clone
base_repo_path = Path(os.path.basename(repo).rsplit(".", maxsplit=1)[0])
# Join targets
challenge_path = challenge_path / base_repo_path
print(challenge_path)
config["challenges"][str(challenge_path)] = repo
with open(get_config_path(), "w+") as f:
config.write(f)
subprocess.call(["git", "clone", "--depth", "1", repo])
shutil.rmtree(str(base_repo_path / ".git"))
elif Path(repo).exists():
config["challenges"][repo] = repo
with open(get_config_path(), "w+") as f:
config.write(f)
else:
click.secho(
"Couldn't process that challenge path. Please check it for errors.",
fg="red",
)
def restore(self):
config = load_config()
challenges = dict(config["challenges"])
for folder, url in challenges.items():
if url.endswith(".git"):
click.echo(f"Cloning {url} to {folder}")
subprocess.call(["git", "clone", "--depth", "1", url, folder])
shutil.rmtree(str(Path(folder) / ".git"))
else:
click.echo(f"Skipping {url} - {folder}")
def install(self, challenge=None, force=False):
if challenge is None:
challenge = os.getcwd()
path = Path(challenge)
if path.name.endswith(".yml") is False:
path = path / "challenge.yml"
click.secho(f"Found {path}")
challenge = load_challenge(path)
click.secho(f'Loaded {challenge["name"]}', fg="yellow")
installed_challenges = load_installed_challenges()
for c in installed_challenges:
if c["name"] == challenge["name"]:
click.secho(
"Already found existing challenge with same name. Perhaps you meant sync instead of install?",
fg="red",
)
if force is True:
click.secho(
"Ignoring existing challenge because of --force", fg="yellow"
)
else:
return
click.secho(f'Installing {challenge["name"]}', fg="yellow")
create_challenge(challenge=challenge)
click.secho(f"Success!", fg="green")
def sync(self, challenge=None):
if challenge is None:
challenge = os.getcwd()
path = Path(challenge)
if path.name.endswith(".yml") is False:
path = path / "challenge.yml"
click.secho(f"Found {path}")
challenge = load_challenge(path)
click.secho(f'Loaded {challenge["name"]}', fg="yellow")
installed_challenges = load_installed_challenges()
for c in installed_challenges:
if c["name"] == challenge["name"]:
break
else:
click.secho(
"Couldn't find existing challenge. Perhaps you meant install instead of sync?",
fg="red",
)
click.secho(f'Syncing {challenge["name"]}', fg="yellow")
sync_challenge(challenge=challenge)
click.secho(f"Success!", fg="green")
def lint(self, challenge=None):
if challenge is None:
challenge = os.getcwd()
path = Path(challenge)
if path.name.endswith(".yml") is False:
path = path / "challenge.yml"
lint_challenge(path)

33
ctfcli/cli/config.py Normal file
View File

@ -0,0 +1,33 @@
import os
import subprocess
import click
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import IniLexer, JsonLexer
from ctfcli.utils.config import get_config_path, preview_config
class Config(object):
def edit(self):
editor = os.getenv("EDITOR", "vi")
command = editor, get_config_path()
subprocess.call(command)
def path(self):
click.echo(get_config_path())
def view(self, color=True, json=False):
config = get_config_path()
with open(config) as f:
if json is True:
config = preview_config(as_string=True)
if color:
config = highlight(config, JsonLexer(), TerminalFormatter())
else:
config = f.read()
if color:
config = highlight(config, IniLexer(), TerminalFormatter())
print(config)

27
ctfcli/cli/plugins.py Normal file
View File

@ -0,0 +1,27 @@
import os
import shutil
import subprocess
from ctfcli.utils.plugins import get_plugin_dir
class Plugins(object):
def install(self, url):
local_dir = os.path.join(
get_plugin_dir(), os.path.basename(url).rsplit(".", maxsplit=1)[0]
)
subprocess.call(["git", "clone", url, local_dir])
subprocess.call(
["pip", "install", "-r", os.path.join(local_dir, "requirements.txt")]
)
def uninstall(self, plugin_name):
plugin_dir = os.path.join(get_plugin_dir(), plugin_name)
shutil.rmtree(plugin_dir)
def list(self):
for plugin in sorted(os.listdir(get_plugin_dir())):
print(plugin)
def dir(self):
print(get_plugin_dir())

View File

@ -0,0 +1,71 @@
# This file represents the base specification of your challenge. It is used by
# other tools to install and deploy your challenge.
# Required sections
name: "{{cookiecutter.name}}"
author: "author"
category: Cateogory
description: This is a sample description
value: 100
# Specifies what version of the challenge specification was used.
# Subject to change until ctfcli v1.0.0
version: "0.1"
# Settings used for Dockerfile deployment
# If not used, remove or set to null
# If you have a Dockerfile set to .
# If you have an imaged hosted on Docker set to the image url (e.g. python/3.8:latest, registry.gitlab.com/python/3.8:latest)
# Follow Docker best practices and assign a tag
image: null
# Optional settings
# Can be removed if unused
type: standard
attempts: 5
# Flags specify answers that your challenge use. You should generally provide
# at least one.
# Can be removed if unused
# Accepts strings or dictionaries
flags:
- flag{3xampl3}
- {
type: "static",
content: "flag{wat}",
data: "asdfasdfsdf",
}
# Tags are used to classify your challenge with topics. You should provide at
# least one.
# Can be removed if unused
# Accepts strings
tags:
- web
- sandbox
- js
# Provide paths to files from the same directory that this file is in
# Accepts strings
files:
- dist/source.py
# Hints are used to give players a way to buy or have suggestions. They are not
# required but can be nice.
# Can be removed if unused
# Accepts dictionaries or strings
hints:
- {
content: "This hint costs points",
cost: 10
}
- This hint is free
# Requirements are used to make a challenge require another challenge to be
# solved before being available.
# Can be removed if unused
# Accepts challenge names as strings or challenge IDs as integers
requirements:
- "Warmup"
- "Are you alive"
- 1

View File

@ -0,0 +1,3 @@
{
"name": "Hello"
}

View File

@ -0,0 +1,13 @@
# Challenge specific files
README.md
WRITEUP.md
challenge.yml
# Docker files
Dockerfile
docker-compose.yml
.dockerignore
# Build files
Makefile
.gitignore

View File

@ -0,0 +1,10 @@
.DEFAULT_GOAL := 64
32:
gcc -g -Wall -m32 -o dist/{{cookiecutter.name}} src/{{cookiecutter.name}}.c
64:
gcc -g -Wall -m64 -o dist/{{cookiecutter.name}} src/{{cookiecutter.name}}.c
clean:
$(RM) dist/*

View File

@ -0,0 +1,5 @@
# {{cookiecutter.name}}
## Description
## Topics

View File

@ -0,0 +1 @@
../../../../spec/challenge-example.yml

View File

@ -0,0 +1,8 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
printf("Hello World!\n");
return 0;
}

View File

@ -0,0 +1,3 @@
{
"name": "Hello"
}

View File

@ -0,0 +1,5 @@
default:
python src/encrypt.py > dist/flag.txt
clean:
$(RM) dist/*

View File

@ -0,0 +1,5 @@
# {{cookiecutter.name}}
## Description
## Topics

View File

@ -0,0 +1 @@
../../../../spec/challenge-example.yml

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import codecs
def encrypt(string):
enc = codecs.getencoder("rot-13")
return enc(string)[0]
def main():
with open("src/flag.txt") as f:
print(encrypt(f.read()))
if __name__ == "__main__":
main()

View File

@ -0,0 +1 @@
temp flag

View File

@ -0,0 +1,5 @@
{
"name": "Hello",
"port": "12345",
"timeout": "60"
}

View File

@ -0,0 +1,13 @@
# Challenge specific files
README.md
WRITEUP.md
challenge.yml
# Docker files
Dockerfile
docker-compose.yml
.dockerignore
# Build files
Makefile
.gitignore

View File

@ -0,0 +1,12 @@
FROM python:3.7-alpine
RUN apk update && \
apk add \
socat
RUN mkdir "/opt/{{cookiecutter.name}}"
COPY ./src/* "/opt/{{cookiecutter.name}}/"
RUN pip install -r "/opt/{{cookiecutter.name}}/requirements.txt"
EXPOSE {{cookiecutter.port}}
WORKDIR "/opt/{{cookiecutter.name}}/"
CMD ./serve.sh

View File

@ -0,0 +1,5 @@
# {{cookiecutter.name}}
## Description
## Topics

View File

@ -0,0 +1 @@
../../../../spec/challenge-example.yml

View File

@ -0,0 +1,6 @@
version: "3"
services:
app:
build: .
ports:
- '8000:8000'

View File

@ -0,0 +1,5 @@
#!/bin/sh
socat \
-T{{cookiecutter.timeout}} \
TCP-LISTEN:{{cookiecutter.port}},reuseaddr,fork \
EXEC:"timeout {{cookiecutter.timeout}} ./server.py"

View File

@ -0,0 +1,20 @@
#!/usr/bin/env python
import random
from six.moves import input
def server():
print("Hello World")
secret = random.randint(1, 100)
while True:
guess = input("What's the random number?")
if int(guess) == secret:
print("You got it!")
exit()
else:
print("No.")
if __name__ == "__main__":
server()

View File

@ -0,0 +1,3 @@
{
"name": "Hello"
}

View File

@ -0,0 +1,13 @@
# Challenge specific files
README.md
WRITEUP.md
challenge.yml
# Docker files
Dockerfile
docker-compose.yml
.dockerignore
# Build files
Makefile
.gitignore

View File

@ -0,0 +1,26 @@
FROM python:3.7-alpine
RUN apk update && \
apk add \
python \
python-dev \
linux-headers \
libffi-dev \
gcc \
make \
musl-dev \
py-pip \
mysql-client \
git \
openssl-dev
RUN adduser -D -u 1001 -s /bin/bash app
WORKDIR /opt/app
RUN mkdir -p /opt/app
COPY src/ /opt/app/
RUN pip install -r requirements.txt
USER 1001
EXPOSE 8000
ENTRYPOINT ["/opt/app/serve.sh"]

View File

@ -0,0 +1,5 @@
# {{cookiecutter.name}}
## Description
## Topics

View File

@ -0,0 +1 @@
../../../../spec/challenge-example.yml

View File

@ -0,0 +1,6 @@
version: "3"
services:
app:
build: .
ports:
- '8000:8000'

View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.config["BOOTSTRAP_SERVE_LOCAL"] = True
bootstrap = Bootstrap(app)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True, threaded=True)

View File

@ -0,0 +1,3 @@
gunicorn==19.10.0
Flask==1.1.1
Bootstrap-Flask==1.2.0

View File

@ -0,0 +1,6 @@
#!/bin/sh
gunicorn 'app:app' \
--bind '0.0.0.0:8000' \
--workers 4 \
--access-logfile "-" \
--error-logfile "-"

View File

@ -0,0 +1,55 @@
<!doctype html>
<html lang="en">
{% raw %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% block bootstrap_css %}
{{ bootstrap.load_css() }}
{% endblock %}
{% block styles %}
{% endblock %}
</head>
{% endraw %}
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">{{cookiecutter.name}}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
{% raw %}
<main role="main" class="container">
{% block content %}{% endblock %}
</main>
{% endraw %}
{% raw %}
{% block bootstrap_js %}
{{ bootstrap.load_js() }}
{% endblock %}
{% block scripts %}
{% endblock %}
{% endraw %}
</body>
</html>

View File

@ -0,0 +1,8 @@
{% raw %}
{% extends "base.html" %}
{% block content %}
Index page
{% endblock %}
{% endraw %}

0
ctfcli/utils/__init__.py Normal file
View File

13
ctfcli/utils/api.py Normal file
View File

@ -0,0 +1,13 @@
from urllib.parse import urljoin
from requests import Session
class APISession(Session):
def __init__(self, prefix_url=None, *args, **kwargs):
super(APISession, self).__init__(*args, **kwargs)
self.prefix_url = prefix_url
def request(self, method, url, *args, **kwargs):
url = urljoin(self.prefix_url, url)
return super(APISession, self).request(method, url, *args, **kwargs)

242
ctfcli/utils/challenge.py Normal file
View File

@ -0,0 +1,242 @@
import yaml
import click
from .config import generate_session
def load_challenge(path):
try:
with open(path) as f:
return yaml.safe_load(f.read())
except FileNotFoundError:
click.secho(f"No challenge.yml was found in {path}", fg="red")
return
def load_installed_challenges():
s = generate_session()
return s.get("/api/v1/challenges", json=True).json()["data"]
def sync_challenge(challenge):
data = {
"name": challenge["name"],
"category": challenge["category"],
"description": challenge["description"],
"type": challenge.get("type", "standard"),
"value": int(challenge["value"]),
}
if challenge.get("attempts"):
data["max_attempts"] = challenge.get("attempts")
data["state"] = "hidden"
installed_challenges = load_installed_challenges()
for c in installed_challenges:
if c["name"] == challenge["name"]:
challenge_id = c["id"]
break
else:
return
s = generate_session()
original_challenge = s.get(f"/api/v1/challenges/{challenge_id}", json=data).json()[
"data"
]
r = s.patch(f"/api/v1/challenges/{challenge_id}", json=data)
r.raise_for_status()
# Delete existing flags
current_flags = s.get(f"/api/v1/flags", json=data).json()["data"]
for flag in current_flags:
if flag["challenge_id"] == challenge_id:
flag_id = flag["id"]
r = s.delete(f"/api/v1/flags/{flag_id}", json=True)
r.raise_for_status()
# Create new flags
if challenge.get("flags"):
for flag in challenge["flags"]:
if type(flag) == str:
data = {"content": flag, "type": "static", "challenge": challenge_id}
r = s.post(f"/api/v1/flags", json=data)
r.raise_for_status()
# Delete existing tags
current_tags = s.get(f"/api/v1/tags", json=data).json()["data"]
for tag in current_tags:
if tag["challenge_id"] == challenge_id:
tag_id = tag["id"]
r = s.delete(f"/api/v1/tags/{tag_id}", json=True)
r.raise_for_status()
# Update tags
if challenge.get("tags"):
for tag in challenge["tags"]:
r = s.post(f"/api/v1/tags", json={"challenge": challenge_id, "value": tag})
r.raise_for_status()
# Delete existing files
all_current_files = s.get(f"/api/v1/files?type=challenge", json=data).json()["data"]
for f in all_current_files:
for used_file in original_challenge["files"]:
if f["location"] in used_file:
file_id = f["id"]
r = s.delete(f"/api/v1/files/{file_id}", json=True)
r.raise_for_status()
# Upload files
if challenge.get("files"):
files = []
for f in challenge["files"]:
files.append(("file", open(f, "rb")))
data = {"challenge": challenge_id, "type": "challenge"}
# Specifically use data= here instead of json= to send multipart/form-data
r = s.post(f"/api/v1/files", files=files, data=data)
r.raise_for_status()
# Delete existing hints
current_hints = s.get(f"/api/v1/hints", json=data).json()["data"]
for hint in current_hints:
if hint["challenge_id"] == challenge_id:
hint_id = hint["id"]
r = s.delete(f"/api/v1/hints/{hint_id}", json=True)
r.raise_for_status()
# Create hints
if challenge.get("hints"):
for hint in challenge["hints"]:
if type(hint) == str:
data = {"content": hint, "cost": 0, "challenge": challenge_id}
else:
data = {
"content": hint["content"],
"cost": hint["cost"],
"challenge": challenge_id,
}
r = s.post(f"/api/v1/hints", json=data)
r.raise_for_status()
# Update requirements
if challenge.get("requirements"):
installed_challenges = load_installed_challenges()
required_challenges = []
for r in challenge["requirements"]:
if type(r) == str:
for c in installed_challenges:
if c["name"] == r:
required_challenges.append(c["id"])
elif type(r) == int:
required_challenges.append(r)
required_challenges = list(set(required_challenges))
data = {"requirements": {"prerequisites": required_challenges}}
r = s.patch(f"/api/v1/challenges/{challenge_id}", json=data)
r.raise_for_status()
# Unhide challenge
data = {"state": "visible"}
r = s.patch(f"/api/v1/challenges/{challenge_id}", json=data)
r.raise_for_status()
def create_challenge(challenge):
data = {
"name": challenge["name"],
"category": challenge["category"],
"description": challenge["description"],
"type": challenge.get("type", "standard"),
"value": int(challenge["value"]),
}
if challenge.get("attempts"):
data["max_attempts"] = challenge.get("attempts")
s = generate_session()
r = s.post("/api/v1/challenges", json=data)
r.raise_for_status()
challenge_data = r.json()
challenge_id = challenge_data["data"]["id"]
# Create flags
if challenge.get("flags"):
for flag in challenge["flags"]:
if type(flag) == str:
data = {"content": flag, "type": "static", "challenge": challenge_id}
r = s.post(f"/api/v1/flags", json=data)
r.raise_for_status()
# Create tags
if challenge.get("tags"):
for tag in challenge["tags"]:
r = s.post(f"/api/v1/tags", json={"challenge": challenge_id, "value": tag})
r.raise_for_status()
# Upload files
if challenge.get("files"):
files = []
for f in challenge["files"]:
files.append(("file", open(f, "rb")))
data = {"challenge": challenge_id, "type": "challenge"}
# Specifically use data= here instead of json= to send multipart/form-data
r = s.post(f"/api/v1/files", files=files, data=data)
r.raise_for_status()
# Add hints
if challenge.get("hints"):
for hint in challenge["hints"]:
if type(hint) == str:
data = {"content": hint, "cost": 0, "challenge": challenge_id}
else:
data = {
"content": hint["content"],
"cost": hint["cost"],
"challenge": challenge_id,
}
r = s.post(f"/api/v1/hints", json=data)
r.raise_for_status()
# Add requirements
if challenge.get("requirements"):
installed_challenges = load_installed_challenges()
required_challenges = []
for r in challenge["requirements"]:
if type(r) == str:
for c in installed_challenges:
if c["name"] == r:
required_challenges.append(c["id"])
elif type(r) == int:
required_challenges.append(r)
required_challenges = list(set(required_challenges))
data = {"requirements": {"prerequisites": required_challenges}}
r = s.patch(f"/api/v1/challenges/{challenge_id}", json=data)
r.raise_for_status()
def lint_challenge(path):
try:
challenge = load_challenge(path)
except yaml.YAMLError as e:
click.secho(f"Error parsing challenge.yml: {e}", fg="red")
exit(1)
required_fields = ["name", "author", "category", "description", "value"]
errors = []
for field in required_fields:
if challenge.get(field) is None:
errors.append(field)
if len(errors) > 0:
print("Missing fields: ", ", ".join(errors))
exit(1)
exit(0)

71
ctfcli/utils/config.py Normal file
View File

@ -0,0 +1,71 @@
import configparser
import json
import os
from .api import APISession
from ctfcli import __file__ as base_path
def get_base_path():
return os.path.dirname(base_path)
def get_config_path():
pwd = os.getcwd()
while pwd:
config = os.path.join(pwd, ".ctf/config")
if os.path.isfile(config):
return config
new_pwd = os.path.dirname(pwd)
pwd = None if new_pwd == pwd else new_pwd
return None
def get_project_path():
pwd = os.getcwd()
while pwd:
config = os.path.join(pwd, ".ctf/config")
if os.path.isfile(config):
return pwd
new_pwd = os.path.dirname(pwd)
pwd = None if new_pwd == pwd else new_pwd
return None
def load_config():
path = get_config_path()
parser = configparser.ConfigParser()
# Preserve case in configparser
parser.optionxform = str
parser.read(path)
return parser
def preview_config(as_string=False):
config = load_config()
d = {}
for section in config.sections():
d[section] = {}
for k, v in config.items(section):
d[section][k] = v
preview = json.dumps(d, sort_keys=True, indent=4)
if as_string is True:
return preview
else:
print(preview)
def generate_session():
config = load_config()
url = config["config"]["url"]
url = url.strip("/")
access_token = config["config"]["access_token"]
s = APISession(url)
s.headers.update({"Authorization": f"Token {access_token}"})
return s

15
ctfcli/utils/plugins.py Normal file
View File

@ -0,0 +1,15 @@
import appdirs
import os
from ctfcli import __name__ as pkg_name
def get_plugin_dir():
plugins_path = os.path.join(get_data_dir(), "plugins")
if not os.path.exists(plugins_path):
os.makedirs(plugins_path)
return os.path.join(plugins_path)
def get_data_dir():
return appdirs.user_data_dir(appname=pkg_name)

9
development.txt Normal file
View File

@ -0,0 +1,9 @@
-r requirements.txt
twine==3.1.1
setuptools==46.1.3
wheel==0.34.2
black==19.10b0
flake8==3.7.9
flake8-bugbear==20.1.2
flake8-comprehensions==3.1.4
flake8-isort==2.8.0

75
docs/plugins.md Normal file
View File

@ -0,0 +1,75 @@
# Plugins
`ctfcli` plugins are essentially additions to to the command line interface via dynamic class modifications.
*`ctfcli` is an alpha project! The plugin interface is likely to change!*
## Installing a plugin
`ctfcli` expects plugins to be shared via git repositories. The `ctf plugins install` command will clone a given plugin repository to the plugin directory.
```
ctf plugins install URL
```
## Writing a new plugin
### 1. Locate your plugin directory
```
ctf plugins dir
/Users/user/Library/Application Support/ctfcli/plugins
```
### 2. Create a new module
Create a new Python module with an `__init__.py` file inside of it. Inside of the `__init__.py` file you should specify a load function that takes a single argument (the pre-defined command classes)
```
.
└── plugin
└── __init__.py
```
```
cat plugin/__init__.py
from types import MethodType
def load(commands):
pass
```
### 3. Define your plugin
```python
from types import MethodType
def cow(self):
a_cow = """
^__^
(oo)\_______
(__)\ )\\/\\
||----w |
|| ||
"""
print(a_cow)
def load(commands):
plugins = commands["plugins"]
plugins.cow = MethodType(cow, plugins)
```
### 4. Run your new command
```
ctf plugins cow
Loading /Users/user/Library/Application Support/ctfcli/plugins/plugin/__init__.py as plugin
^__^
(oo)\_______
(__)\ )\/\
||----w |
|| ||
```

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
cookiecutter==1.6.0
click==7.0
fire==0.2.1
pyyaml==5.2
Pygments==2.5.2
requests==2.22.0
colorama==0.4.3
appdirs==1.4.3

45
setup.py Normal file
View File

@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
import os
from ctfcli import __version__
def read(fname):
try:
with open(os.path.join(os.path.dirname(__file__), fname), "r") as fp:
return fp.read().strip()
except IOError:
return ""
setup(
name="ctfcli",
version=__version__,
author="Kevin Chung",
author_email="kchung@ctfd.io",
license="Apache 2.0",
description="Tool for creating and running Capture The Flag competitions",
long_description=read("README.md"),
long_description_content_type="text/markdown",
keywords=["ctf"],
classifiers=[],
install_requires=[
"cookiecutter==1.6.0",
"click==7.0",
"fire==0.2.1",
"pyyaml==5.2",
"Pygments==2.5.2",
"requests==2.22.0",
"colorama==0.4.3",
"appdirs==1.4.3",
],
packages=find_packages(),
include_package_data=True,
entry_points={"console_scripts": ["ctf = ctfcli.__main__:main"]},
)