├── .env.example ├── .github ├── CONTRIBUTING.md ├── route_docs.png └── workflows │ ├── ghcr.yml │ └── tox.yml ├── .gitignore ├── .python-version ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── OVERVIEW.md ├── README.md ├── conftest.py ├── docker-compose.yaml ├── poetry.lock ├── poetry.toml ├── pyproject.toml ├── src └── pwncore │ ├── __init__.py │ ├── __main__.py │ ├── config.py │ ├── containerASD.py │ ├── docs.py │ ├── models │ ├── __init__.py │ ├── container.py │ ├── ctf.py │ ├── pre_event.py │ └── user.py │ ├── py.typed │ ├── routes │ ├── __init__.py │ ├── admin.py │ ├── auth.py │ ├── ctf │ │ ├── __init__.py │ │ ├── pre_event.py │ │ └── start.py │ ├── leaderboard.py │ └── team.py │ └── types.py ├── tests ├── __init__.py └── test_login.py └── tox.ini /.env.example: -------------------------------------------------------------------------------- 1 | # Database configuration 2 | POSTGRES_USER=postgres_user 3 | POSTGRES_PASSWORD=postgres_password 4 | POSTGRES_DB=postgres_db 5 | 6 | # Application configuration 7 | PORT=8000 8 | WORKERS=4 9 | 10 | # Docker configuration 11 | UID=1000 12 | GID=1000 13 | DATA_PATH=./db_data/ 14 | CONFIG_FILE=./src/pwncore/config.py 15 | 16 | # Admin service configuration 17 | PORT_ADMIN=8001 -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # What you need. 4 | 5 | Install tox as mentioned [here](https://tox.wiki/en/latest/installation.html) 6 | 7 | Then install poetry as detailed [here](https://python-poetry.org/docs/#installation) 8 | 9 | 10 | 11 | ## Adding a dependency 12 | Warning, never use pip to add a dependency. Nasty things are gonna 13 | happen if you ignore that advice. 14 | 15 | ``` 16 | $ poetry add yourdep yourdep2 ... 17 | ``` 18 | 19 | The command may take time due to dependency resolution sometimes, but 20 | if it exceeds 5 minutes it is abnormal. Usually it should be done before you notice. 21 | 22 | ## Spawning a shell in the environment 23 | 24 | ``` 25 | $ poetry shell 26 | ``` 27 | 28 | You can learn more at https://python-poetry.org/docs/cli/ 29 | 30 | ## Running tests 31 | 32 | ``` 33 | $ tox r 34 | ``` -------------------------------------------------------------------------------- /.github/route_docs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lugvitc/pwncore/8060e4b0a0e4953ef2e14b201af6726e2b8720b2/.github/route_docs.png -------------------------------------------------------------------------------- /.github/workflows/ghcr.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Build and Push Docker Image to ghcr.io 3 | 4 | on: 5 | release: 6 | types: 7 | - created 8 | 9 | env: 10 | REGISTRY: ghcr.io 11 | IMAGE_NAME: ${{ github.repository }} 12 | 13 | jobs: 14 | build-and-push-image: 15 | runs-on: ubuntu-latest 16 | if: startsWith(github.ref, 'refs/tags/v') 17 | permissions: 18 | contents: read 19 | packages: write 20 | attestations: write 21 | id-token: write 22 | # 23 | steps: 24 | - name: Checkout repository 25 | uses: actions/checkout@v4 26 | 27 | # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here. 28 | - name: Log in to the Container registry 29 | uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1 30 | with: 31 | registry: ${{ env.REGISTRY }} 32 | username: ${{ github.actor }} 33 | password: ${{ secrets.GHCR_TOKEN }} 34 | 35 | # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels. 36 | - name: Extract metadata (tags, labels) for Docker 37 | id: meta 38 | uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 39 | with: 40 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 41 | 42 | # This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages. 43 | - name: Build and push Docker image 44 | id: push 45 | uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4 46 | with: 47 | context: . 48 | push: true 49 | tags: ${{ steps.meta.outputs.tags }} 50 | labels: ${{ steps.meta.outputs.labels }} 51 | 52 | # This step generates an artifact attestation for the image, which is an unforgeable statement about where and how it was built. It increases supply chain security for people who consume the image. For more information, see [Using artifact attestations to establish provenance for builds](/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds). 53 | - name: Generate artifact attestation 54 | uses: actions/attest-build-provenance@v2 55 | with: 56 | subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}} 57 | subject-digest: ${{ steps.push.outputs.digest }} 58 | push-to-registry: true 59 | -------------------------------------------------------------------------------- /.github/workflows/tox.yml: -------------------------------------------------------------------------------- 1 | name: Tox 2 | 3 | on: 4 | push: 5 | branches: [ "*" ] 6 | pull_request: 7 | branches: [ "*" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | python-version: [ 16 | "3.11", 17 | "3.12" 18 | ] 19 | 20 | steps: 21 | # TODO: Add caching 22 | - uses: actions/checkout@v4 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v4 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Install Tox in Python ${{ matrix.python-version }} 28 | run: | 29 | python -m pip install tox-gh 30 | - name: Run the tox environment (Python ${{ matrix.python-version }}) 31 | run: | 32 | tox 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | src/pwncore/utils.py 163 | db_data/ -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.11.11 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Git Commit Message Guide 2 | 3 | ## Commit Message Structure 4 | 5 | Each commit message should generally follow this format: 6 | 7 | ``` 8 | : 9 | 10 | [optional body] 11 | 12 | [optional footer(s)] 13 | ``` 14 | 15 | ### 1. Adding a New File 16 | 17 | ``` 18 | feat: Add user authentication module 19 | ``` 20 | 21 | ### 2. Adding New Functionality 22 | 23 | ``` 24 | feat: Implement password reset functionality 25 | ``` 26 | 27 | ### 3. Updating Functionality 28 | 29 | ``` 30 | refactor: Improve search algorithm efficiency 31 | ``` 32 | 33 | ### 4. Fixing Bugs 34 | 35 | ``` 36 | fix: Resolve login error for special characters 37 | ``` 38 | 39 | ### 5. Removing Unused Code 40 | 41 | ``` 42 | chore: Remove deprecated user profile functions 43 | ``` 44 | 45 | ### 6. Updating Documentation 46 | 47 | ``` 48 | docs: Update README with new API endpoints 49 | ``` 50 | 51 | ### 7. Refactoring Code (without changing functionality) 52 | 53 | ``` 54 | refactor: Simplify error handling in payment module 55 | ``` 56 | 57 | ### 8. Updating Dependencies 58 | 59 | ``` 60 | chore: Update dependencies to latest versions 61 | ``` 62 | 63 | ### 9. Making Performance Improvements 64 | 65 | ``` 66 | perf: Optimize image loading on homepage 67 | ``` 68 | 69 | ## Pull Requests 70 | 71 | ``` 72 | feat: Add user registration API endpoint 73 | 74 | - Implement POST /api/users/register 75 | - Add input validation and error handling 76 | - Create unit tests for the new endpoint 77 | 78 | Closes #123 79 | ``` 80 | 81 | ``` 82 | fix: Prevent race condition in concurrent file access 83 | 84 | - Implement file locking mechanism 85 | - Add timeout to prevent deadlocks 86 | - Update relevant documentation 87 | 88 | Bug: #456 89 | ``` 90 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.12-slim 2 | 3 | WORKDIR /app 4 | 5 | RUN pip install poetry 6 | 7 | RUN poetry config virtualenvs.create false 8 | 9 | COPY pyproject.toml poetry.lock README.md /app/ 10 | # RUN poetry install 11 | 12 | # Copy everything from src into /app/src 13 | COPY src /app/src 14 | RUN poetry install 15 | 16 | WORKDIR /app/src 17 | 18 | EXPOSE 8000 19 | 20 | # Run FastAPI with Gunicorn 21 | CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "pwncore:app", "--bind", "0.0.0.0:8000", "--log-level", "debug"] 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /OVERVIEW.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | Rough functionality: 4 | - User 5 | - (id) -> profile 6 | - signup 7 | - Create a team 8 | - Or join a team 9 | - login 10 | - logout 11 | - Team 12 | - (id) -> profile 13 | - clear (NEW) 14 | - Stops all running containers associated with the team 15 | - CTF 16 | - (id) -> Get CTF info 17 | - start 18 | - Check if team has already completed it 19 | - Only if no container is assigned to the team before 20 | - If container exists, return its CTF ID 21 | - Else 22 | - Start the container 23 | - Save container and CTF ID to team profile 24 | - stop 25 | - Stop container and delete record from DB 26 | - hints/(1,2,3,...) 27 | - As hints are used, save their usage to their team profile 28 | - flag 29 | - If flag invalid, return flag invalid 30 | - If valid, check for hints used and assign necessary points. 31 | - add (TBD) 32 | - Make a dynamic way to add CTFs 33 | - Admin 34 | - TBD 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pwncore 2 | 3 | A CTF platform backend written in [FastAPI](https://github.com/fastapi/fastapi) using [Tortoise-ORM](https://github.com/tortoise/tortoise-orm), [Tox](https://github.com/tox-dev/tox) and [Pydantic](https://github.com/pydantic/pydantic) 4 | 5 | ## Table of Contents 6 | 7 | 1. [TODO](#todo) 8 | 2. [Prerequisites](#prerequisites) 9 | 3. [Installation](#installation) 10 | 4. [Usage](#usage) 11 | 5. [Project Structure](#project-structure) 12 | 6. [Documenting](#documenting) 13 | 7. [Contributing](#contributing) 14 | 8. [License](#license) 15 | 16 | ## TODO 17 | 18 | - [ ] Remove `round2` logic and paths 19 | - [ ] feat: Power ups 20 | - [ ] fix: Leaderboard caching error 21 | - [ ] Issue identification and Bug fixes 22 | - [ ] Setup tests using `tox` 23 | - [ ] feat: Leaderboard graph 24 | 25 | ## Prerequisites 26 | 27 | Before you begin, ensure you have met the following requirements: 28 | 29 | - Python 3.7+ (< Python 3.13) 30 | - Docker (optional, for container functionality) 31 | 32 | ## Installation 33 | 34 | 1. Clone the repository (or a fork of the repository): 35 | 36 | ```bash 37 | git clone https://github.com/lugvitc/pwncore.git 38 | cd pwncore 39 | ``` 40 | 41 | 2. Set up a virtual environment: 42 | 43 | ```bash 44 | python3.12 -m venv .venv 45 | source .venv/bin/activate 46 | ``` 47 | 48 | 3. Install Poetry and project dependencies: 49 | 50 | ```bash 51 | pip install poetry 52 | poetry install 53 | ``` 54 | 55 | 4. Configure the project: 56 | - Open `src/pwncore/config.py` 57 | - Set `db_url` to a path for persistent storage or continue with in-memory database 58 | - Configure `docker_url` as needed (see [Usage](#usage) for details) 59 | 60 | ## Usage 61 | 62 | 1. Start: 63 | 64 | ```bash 65 | uvicorn pwncore:app --reload 66 | 67 | # OR 68 | 69 | poetry run dev 70 | ``` 71 | 72 | 2. Access the auto-generated documentation at [http://localhost:8080/docs](http://localhost:8080/docs) 73 | 74 | 3. Docker configuration: 75 | - Enable and start the Docker service on your system, or 76 | - Modify `src/pwncore/config.py:62`: 77 | 78 | ```python 79 | docker_url="http://google.com", # For testing without Docker 80 | ``` 81 | 82 | ## Project Structure 83 | 84 | ``` 85 | . 86 | ├── Dockerfile 87 | ├── LICENSE 88 | ├── OVERVIEW.md 89 | ├── poetry.lock 90 | ├── poetry.toml 91 | ├── pyproject.toml 92 | ├── README.md 93 | ├── src 94 | │   └── pwncore 95 | │   ├── config.py 96 | │   ├── container.py 97 | │   ├── docs.py 98 | │   ├── __init__.py 99 | │   ├── __main__.py 100 | │   ├── models 101 | │   │   ├── container.py 102 | │   │   ├── ctf.py 103 | │   │   ├── __init__.py 104 | │   │   ├── pre_event.py 105 | │   │   ├── round2.py 106 | │   │   └── user.py 107 | │   ├── py.typed 108 | │   ├── routes 109 | │   │   ├── admin.py 110 | │   │   ├── auth.py 111 | │   │   ├── ctf 112 | │   │   │   ├── __init__.py 113 | │   │   │   ├── pre_event.py 114 | │   │   │   └── start.py 115 | │   │   ├── __init__.py 116 | │   │   ├── leaderboard.py 117 | │   │   ├── round2.py 118 | │   │   └── team.py 119 | │   └── types.py 120 | ├── tests 121 | │   ├── __init__.py 122 | │   └── test_login.py 123 | └── tox.ini 124 | 125 | 7 directories, 32 files 126 | ``` 127 | 128 | ## Documenting: 129 | 130 | FastAPI generates documentation for the routes using OpenAPI. The documentation is available by default at `/docs` (Swagger UI) and `/redoc` (ReDoc). 131 | 132 | There are 2 ways to add documentation for a route: 133 | 134 | 1. Explicitly mention the summary and description: 135 | 136 | ```py 137 | @router.get("/start/{ctf_id}", 138 | description="This description supports **Markdown**.", 139 | summary="Start the docker container" 140 | ) 141 | ``` 142 | 143 | 2. Let it infer summary from function name and description from comments: 144 | 145 | ```py 146 | @router.get("/start/{ctf_id}") 147 | async def start_the_docker_container(ctf_id: int): # The function name is inferred for the summary 148 | # This is a regular single-line comment. 149 | # Will not be displayed in the documentation. 150 | ''' 151 | This is a multi-line comment, and will be displayed 152 | in the documentation when the route is expanded. 153 | 154 | The cool thing is that Markdown works here! 155 | # See, Markdown works! 156 | _Pretty_ **cool** right? 157 | ''' 158 | return {"status": "CTF started"} 159 | ``` 160 | 161 | Result: 162 | 163 | ![Result](.github/route_docs.png) 164 | 165 | ## Contributing 166 | 167 | Follow the following steps while working on the platform 168 | 169 | 1. Fork the repository 170 | 2. Create your feature branch (`git checkout -b feature/functionality`) 171 | 3. Commit your changes (`git commit -m 'Add some functionality'`). Go through [CONTRIBUTING](/CONTRIBUTING.md) for preferred commit messages 172 | 4. Push to the branch (`git push origin feature/functionality`) 173 | 5. Open a Pull Request 174 | 175 | ## License 176 | 177 | This project is licensed under the [GNU GENERAL PUBLIC LICENSE] - see the [LICENSE](./LICENSE) file for details. 178 | -------------------------------------------------------------------------------- /conftest.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def pytest_configure(config): 4 | sys._is_a_test = True -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | web: 3 | build: 4 | context: . 5 | dockerfile: Dockerfile 6 | ports: 7 | - ${PORT}:8000 8 | environment: 9 | - DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB} 10 | - WORKERS=${WORKERS} 11 | volumes: 12 | - /var/run/docker.sock:/var/run/docker.sock 13 | - ${CONFIG_FILE}:/app/src/pwncore/config.py 14 | depends_on: 15 | - db 16 | 17 | db: 18 | image: postgres:14 19 | user: ${UID}:${GID} 20 | environment: 21 | - POSTGRES_USER=${POSTGRES_USER} 22 | - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} 23 | - POSTGRES_DB=${POSTGRES_DB} 24 | - PGDATA=/var/lib/postgresql/data/pgdata 25 | healthcheck: 26 | interval: 10s 27 | retries: 10 28 | test: "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\"" 29 | timeout: 2s 30 | volumes: 31 | - ${DATA_PATH}:/var/lib/postgresql/data 32 | ports: 33 | - 5432:5432 34 | 35 | # admin_db: 36 | # image: nocodb/nocodb:latest 37 | # environment: 38 | # NC_DB: pg://db:5432?u=${POSTGRES_USER}&p=${POSTGRES_PASSWORD}&d=${POSTGRES_DB} 39 | # volumes: 40 | # - nc_data:/usr/app/data 41 | # ports: 42 | # - ${PORT_ADMIN}:8080 43 | # depends_on: 44 | # - db 45 | 46 | # volumes: 47 | # nc_data: {} 48 | -------------------------------------------------------------------------------- /poetry.toml: -------------------------------------------------------------------------------- 1 | [virtualenvs] 2 | in-project = true 3 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "pwncore" 3 | version = "0.1.0" 4 | description = "The backend for an advanced CTF platform" 5 | authors = ["LUGVITC"] 6 | license = "GNU GENERAL PUBLIC LICENSE" 7 | readme = "README.md" 8 | 9 | [[tool.poetry.packages]] 10 | include = "pwncore" 11 | from = "src" 12 | 13 | # Format to add new packages to the wheel 14 | # [[tool.poetry.packages]] 15 | # include = "new_package_or_maybe_script?" 16 | # from = "src" 17 | 18 | [tool.poetry.dependencies] 19 | python = "^3.11" 20 | fastapi = "^0.104.1" 21 | uvicorn = "^0.24.0" 22 | tortoise-orm = {version = "^0.20.0", extras = ["asyncpg", "accel"]} 23 | aiodocker = "^0.21.0" 24 | passlib = "^1.7.4" 25 | pyjwt = "^2.8.0" 26 | types-passlib = "^1.7.7.13" 27 | multidict = "^6.0.5" 28 | gunicorn = "^23.0.0" 29 | 30 | [tool.poetry.group.dev.dependencies] 31 | mypy = "^1.6.1" 32 | httpx = "^0.25.1" 33 | pytest = "^7.4.3" 34 | flake8 = "^6.1.0" 35 | black = "^23.10.1" 36 | flake8-bugbear = "^23.9.16" 37 | 38 | [tool.mypy] 39 | python_version = 3.11 40 | warn_return_any = true 41 | warn_unreachable = true 42 | warn_redundant_casts = true 43 | warn_unused_ignores = true 44 | warn_unused_configs = true 45 | check_untyped_defs = true 46 | show_column_numbers = true 47 | show_error_codes = true 48 | 49 | enable_error_code = [ 50 | "ignore-without-code", 51 | "truthy-bool", 52 | "truthy-iterable", 53 | "redundant-expr", 54 | "no-any-unimported", 55 | "redundant-self", 56 | "type-arg" 57 | ] 58 | 59 | pretty = true 60 | 61 | # For per file / package config 62 | # [[tool.mypy.overrides]] 63 | 64 | [build-system] 65 | requires = ["poetry-core"] 66 | build-backend = "poetry.core.masonry.api" 67 | 68 | 69 | [tool.poetry.scripts] 70 | dev = "pwncore.__main__:run_dev" 71 | -------------------------------------------------------------------------------- /src/pwncore/__init__.py: -------------------------------------------------------------------------------- 1 | from contextlib import asynccontextmanager 2 | 3 | import shutil 4 | import aiodocker 5 | from logging import getLogger 6 | from fastapi import FastAPI 7 | from fastapi.middleware.cors import CORSMiddleware 8 | from tortoise import Tortoise 9 | 10 | import pwncore.containerASD as containerASD 11 | import pwncore.docs as docs 12 | import pwncore.routes as routes 13 | from pwncore.config import config 14 | from pwncore.models import Container 15 | 16 | logger = getLogger(__name__) 17 | 18 | @asynccontextmanager 19 | async def app_lifespan(app: FastAPI): 20 | # Startup 21 | await Tortoise.init(db_url=config.db_url, modules={"models": ["pwncore.models"]}) 22 | await Tortoise.generate_schemas() 23 | 24 | containerASD.docker_client = aiodocker.Docker(url=config.docker_url) 25 | 26 | yield 27 | # Shutdown 28 | # Stop and remove all running containers 29 | containers = await Container.all().values() 30 | await Container.all().delete() 31 | for db_container in containers: 32 | try: 33 | container = await containerASD.docker_client.containers.get( 34 | db_container["docker_id"] 35 | ) 36 | await container.kill() 37 | await container.delete() 38 | except ( 39 | Exception 40 | ): # Raises DockerError if container does not exist, just pass for now. 41 | pass 42 | try: 43 | shutil.rmtree(config.staticfs_data_dir) 44 | except Exception as err: 45 | logger.exception("Failed to delete static files", exc_info=err) 46 | 47 | # close_connections is deprecated, not sure how to use connections.close_all() 48 | await Tortoise.close_connections() 49 | await containerASD.docker_client.close() 50 | 51 | 52 | app = FastAPI( 53 | title="Pwncore", 54 | openapi_tags=docs.tags_metadata, 55 | description=docs.description, 56 | lifespan=app_lifespan, 57 | ) 58 | app.include_router(routes.router) 59 | 60 | origins = [ 61 | "http://c0d.lugvitc.net", 62 | "https://c0d.lugvitc.net", 63 | ] 64 | 65 | if config.development: 66 | origins.append("*") 67 | 68 | app.add_middleware( 69 | CORSMiddleware, 70 | allow_origins=origins, 71 | allow_credentials=True, 72 | allow_methods=["*"], 73 | allow_headers=["*"], 74 | ) 75 | -------------------------------------------------------------------------------- /src/pwncore/__main__.py: -------------------------------------------------------------------------------- 1 | import uvicorn 2 | 3 | 4 | def run_dev(): 5 | uvicorn.run("pwncore:app", host="127.0.0.1", port=8080, reload=True) 6 | 7 | 8 | if __name__ == "__main__": 9 | run_dev() 10 | -------------------------------------------------------------------------------- /src/pwncore/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import bcrypt 3 | from dataclasses import dataclass 4 | import warnings 5 | from passlib.hash import bcrypt_sha256 6 | 7 | """ 8 | Sample messages: 9 | "db_error": "An error occurred, please try again.", 10 | "port_limit_reached": "Server ran out of ports 💀", 11 | "ctf_not_found": "CTF does not exist.", 12 | "container_start": "Container started.", 13 | "container_stop": "Container stopped.", 14 | "containers_team_stop": "All team containers stopped.", 15 | "container_not_found": "You have no running containers for this CTF.", 16 | "container_already_running": "Your team already has a running container for this CTF.", 17 | "container_limit_reached": "Your team already has reached the maximum number" 18 | " of containers limit, please stop other unused containers." 19 | """ 20 | 21 | msg_codes = { 22 | "db_error": 0, 23 | "port_limit_reached": 1, 24 | "ctf_not_found": 2, 25 | "container_start": 3, 26 | "container_stop": 4, 27 | "containers_team_stop": 5, 28 | "container_not_found": 6, 29 | "container_already_running": 7, 30 | "container_limit_reached": 8, 31 | "hint_limit_reached": 9, 32 | "team_not_found": 10, 33 | "user_not_found": 11, 34 | "ctf_solved": 12, 35 | "signup_success": 13, 36 | "wrong_password": 14, 37 | "login_success": 15, 38 | "team_exists": 17, 39 | "user_added": 18, 40 | "user_removed": 19, 41 | "user_already_in_team": 20, 42 | "user_not_in_team": 21, 43 | "insufficient_coins": 22, 44 | "user_or_email_exists": 23, 45 | "users_not_found": 24, 46 | } 47 | 48 | admin_hash_value = os.environ.get("PWNCORE_ADMIN_HASH", bcrypt_sha256.hash('pwncore')) 49 | using_default_admin = os.environ.get("PWNCORE_ADMIN_HASH") is None 50 | 51 | @dataclass 52 | class Config: 53 | development: bool 54 | msg_codes: dict 55 | db_url: str 56 | docker_url: str | None 57 | flag: str 58 | max_containers_per_team: int 59 | jwt_secret: str 60 | jwt_valid_duration: int 61 | hint_penalty: int 62 | max_members_per_team: int 63 | staticfs_url: str 64 | staticfs_data_dir: str 65 | staticfs_jwt_secret: str 66 | admin_hash: str 67 | 68 | config = Config( 69 | development=False, 70 | # db_url="sqlite://:memory:", 71 | db_url=os.environ.get("DATABASE_URL", "sqlite://:memory:"), 72 | # docker_url=None, # None for default system docker 73 | # Or set it to an arbitrary URL for testing without Docker 74 | docker_url="http://google.com", 75 | flag="C0D", 76 | max_containers_per_team=3, 77 | jwt_secret="mysecret", 78 | jwt_valid_duration=12, # In hours 79 | msg_codes=msg_codes, 80 | hint_penalty=50, 81 | max_members_per_team=3, 82 | staticfs_url="http://localhost:8080", 83 | staticfs_data_dir=os.environ.get("STATIC_DATA_DIR", "/data"), 84 | staticfs_jwt_secret="PyMioVKFXHymQd+n7q5geOsT6fSYh3gDVw3GqilW+5U=" 85 | admin_hash=admin_hash_value, 86 | ) 87 | 88 | # Warn in production if env not loaded 89 | if not config.development and using_default_admin: 90 | warnings.warn("Default admin hash being used in production!", RuntimeWarning) -------------------------------------------------------------------------------- /src/pwncore/containerASD.py: -------------------------------------------------------------------------------- 1 | # import asyncio 2 | 3 | import aiodocker 4 | 5 | # from pwncore.config import config 6 | 7 | docker_client: aiodocker.Docker = None # type: ignore[assignment] 8 | 9 | 10 | # if not hasattr(sys, "_is_a_test"): 11 | # docker_client = aiodocker.Docker(url=config.docker_url) 12 | # 13 | # async def create_docker_client(): 14 | # return aiodocker.Docker(url=config.docker_url) 15 | 16 | 17 | # docker_client = asyncio.run(create_docker_client()) 18 | -------------------------------------------------------------------------------- /src/pwncore/docs.py: -------------------------------------------------------------------------------- 1 | from pwncore.routes import ctf, team 2 | 3 | tags_metadata = [ctf.metadata, team.metadata] 4 | 5 | description = "Example description to be edited from /docs.py" 6 | -------------------------------------------------------------------------------- /src/pwncore/models/__init__.py: -------------------------------------------------------------------------------- 1 | """pwncore.models 2 | 3 | Contains all Pydantic and Tortoise ORM models 4 | """ 5 | 6 | import typing 7 | 8 | import tortoise 9 | 10 | from pwncore.models.container import Container, Ports 11 | from pwncore.models.ctf import ( 12 | Problem, 13 | SolvedProblem, 14 | Hint, 15 | ViewedHint, 16 | Hint_Pydantic, 17 | BaseProblem_Pydantic, 18 | Problem_Pydantic, 19 | BaseProblem, 20 | ) 21 | from pwncore.models.user import ( 22 | User, 23 | Team, 24 | Team_Pydantic, 25 | User_Pydantic, 26 | ) 27 | from pwncore.models.pre_event import ( 28 | PreEventProblem, 29 | PreEventSolvedProblem, 30 | PreEventUser, 31 | PreEventProblem_Pydantic, 32 | ) 33 | 34 | 35 | __all__ = ( 36 | "Problem", 37 | "BaseProblem_Pydantic", 38 | "Hint", 39 | "Hint_Pydantic", 40 | "SolvedProblem", 41 | "ViewedHint", 42 | "Container", 43 | "Ports", 44 | "User", 45 | "PreEventSolvedProblem", 46 | "PreEventProblem", 47 | "PreEventUser", 48 | "User_Pydantic", 49 | "Team", 50 | "Team_Pydantic", 51 | "PreEventProblem_Pydantic", 52 | "Problem_Pydantic", 53 | "BaseProblem", 54 | ) 55 | 56 | 57 | def get_annotations(cls, method=None): 58 | return typing.get_type_hints(method or cls) 59 | 60 | 61 | tortoise.contrib.pydantic.utils.get_annotations = get_annotations # type: ignore[unused-ignore] 62 | tortoise.contrib.pydantic.creator.get_annotations = get_annotations # type: ignore[unused-ignore] 63 | -------------------------------------------------------------------------------- /src/pwncore/models/container.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import typing as t 4 | 5 | from tortoise.models import Model 6 | from tortoise import fields 7 | 8 | if t.TYPE_CHECKING: 9 | from pwncore.models.ctf import Problem 10 | from pwncore.models.user import Team 11 | 12 | __all__ = ("Container", "Ports") 13 | 14 | 15 | # Note: These are all type annotated, dont worry 16 | class Container(Model): 17 | docker_id = fields.CharField(128, unique=True) 18 | problem: fields.ForeignKeyRelation[Problem] = fields.ForeignKeyField( 19 | "models.Problem", on_delete=fields.OnDelete.NO_ACTION 20 | ) 21 | team: fields.ForeignKeyRelation[Team] = fields.ForeignKeyField("models.Team") 22 | flag = fields.TextField() 23 | 24 | token = fields.TextField() 25 | ports: fields.ReverseRelation[Ports] 26 | 27 | 28 | class Ports(Model): 29 | # FUTURE PROOFING: ADD domain 30 | container: fields.ForeignKeyRelation[Container] = fields.ForeignKeyField( 31 | "models.Container", related_name="ports", on_delete=fields.OnDelete.CASCADE 32 | ) 33 | port = fields.IntField(pk=True) 34 | -------------------------------------------------------------------------------- /src/pwncore/models/ctf.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from math import tanh 4 | 5 | from tortoise.models import Model 6 | from tortoise import fields 7 | from tortoise.contrib.pydantic import pydantic_model_creator 8 | 9 | from pwncore.models.user import Team 10 | 11 | __all__ = ( 12 | "Problem", 13 | "Hint", 14 | "SolvedProblem", 15 | "ViewedHint", 16 | "BaseProblem_Pydantic", 17 | "Hint_Pydantic", 18 | "Problem_Pydantic", 19 | "BaseProblem", 20 | ) 21 | 22 | 23 | class BaseProblem(Model): 24 | name = fields.TextField() 25 | description = fields.TextField() 26 | # both tables inherit points, for pre-event points means coins 27 | points = fields.IntField() 28 | author = fields.TextField() 29 | 30 | 31 | class Problem(BaseProblem): 32 | image_name = fields.TextField() 33 | 34 | # commenting it for now, may be used later 35 | # image_config: fields.Field[dict[str, Any]] = fields.JSONField( 36 | # null=True 37 | # ) # type: ignore[assignment] 38 | static = fields.BooleanField(default=False) 39 | 40 | mi = fields.IntField(default=50) 41 | ma = fields.IntField(default=500) 42 | visible = fields.BooleanField(default=True) 43 | tags = fields.SmallIntField(default=1) # by default misc, 16 tag limit 44 | 45 | hints: fields.ReverseRelation[Hint] 46 | 47 | class PydanticMeta: 48 | exclude = ["image_name", "static", "mi", "ma", "visible"] 49 | 50 | async def _solves(self) -> int: 51 | return await SolvedProblem.filter(problem=self).count() 52 | 53 | async def update_points(self) -> None: 54 | self.points = round( 55 | self.mi + (self.ma - self.mi) * (1 - tanh((await self._solves()) / 25)) 56 | ) 57 | await self.save() 58 | 59 | 60 | class Hint(Model): 61 | id = fields.IntField(pk=True) 62 | order = fields.SmallIntField() # 0, 1, 2 63 | problem: fields.ForeignKeyRelation[Problem] = fields.ForeignKeyField( 64 | "models.Problem", related_name="hints" 65 | ) 66 | text = fields.TextField() 67 | 68 | class Meta: 69 | ordering = ("order",) 70 | 71 | 72 | class SolvedProblem(Model): 73 | team: fields.ForeignKeyRelation[Team] = fields.ForeignKeyField( 74 | "models.Team", related_name="solved_problem" 75 | ) 76 | problem: fields.ForeignKeyRelation[Problem] = fields.ForeignKeyField( 77 | "models.Problem" 78 | ) 79 | solved_at = fields.DatetimeField(auto_now_add=True) 80 | 81 | penalty = fields.FloatField(default=1.0) 82 | 83 | class Meta: 84 | unique_together = (("team", "problem"),) 85 | 86 | 87 | class ViewedHint(Model): 88 | team: fields.ForeignKeyRelation[Team] = fields.ForeignKeyField( 89 | "models.Team", related_name="viewedhints" 90 | ) 91 | hint: fields.ForeignKeyRelation[Hint] = fields.ForeignKeyField( 92 | "models.Hint", 93 | ) 94 | 95 | with_points = fields.BooleanField(default=False) 96 | 97 | class Meta: 98 | unique_together = (("team", "hint"),) 99 | 100 | 101 | BaseProblem_Pydantic = pydantic_model_creator(BaseProblem) 102 | Problem_Pydantic = pydantic_model_creator(Problem) 103 | Hint_Pydantic = pydantic_model_creator(Hint) 104 | -------------------------------------------------------------------------------- /src/pwncore/models/pre_event.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from tortoise.models import Model 4 | from tortoise import fields 5 | from tortoise.contrib.pydantic import pydantic_model_creator 6 | 7 | from pwncore.models.ctf import BaseProblem 8 | 9 | __all__ = ( 10 | "PreEventSolvedProblem", 11 | "PreEventProblem", 12 | "PreEventProblem_Pydantic", 13 | "PreEventUser", 14 | ) 15 | 16 | 17 | class PreEventProblem(BaseProblem): 18 | flag = fields.TextField() 19 | url = fields.TextField() # Link to CTF file/repo/website 20 | 21 | date = fields.DateField() 22 | 23 | class PydanticMeta: 24 | exclude = ("flag",) 25 | 26 | 27 | class PreEventSolvedProblem(Model): 28 | user: fields.ForeignKeyRelation[PreEventUser] = fields.ForeignKeyField( 29 | "models.PreEventUser", related_name="solvedproblems" 30 | ) 31 | problem: fields.ForeignKeyRelation[PreEventProblem] = fields.ForeignKeyField( 32 | "models.PreEventProblem" 33 | ) 34 | solved_at = fields.DatetimeField(auto_now_add=True) 35 | 36 | class Meta: 37 | unique_together = (("user", "problem"),) 38 | 39 | 40 | class PreEventUser(Model): 41 | tag = fields.CharField(128, pk=True) 42 | email = fields.CharField(256, unique=True) 43 | 44 | solvedproblems: fields.ReverseRelation[PreEventSolvedProblem] 45 | 46 | 47 | PreEventProblem_Pydantic = pydantic_model_creator(PreEventProblem) 48 | -------------------------------------------------------------------------------- /src/pwncore/models/user.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from tortoise import fields 4 | from tortoise.exceptions import IntegrityError 5 | from tortoise.models import Model 6 | from tortoise.expressions import Q 7 | from tortoise.contrib.pydantic import pydantic_model_creator 8 | 9 | from pwncore.models.container import Container 10 | from pwncore.config import config 11 | 12 | __all__ = ( 13 | "User", 14 | "Team", 15 | "User_Pydantic", 16 | "Team_Pydantic", 17 | ) 18 | 19 | 20 | class User(Model): 21 | # Registration numbers and other identity tags 22 | # abstractly just represents one person, expand this 23 | # field for Identity providers 24 | tag = fields.CharField(128, unique=True) 25 | name = fields.TextField() 26 | email = fields.TextField() 27 | phone_num = fields.CharField(15) 28 | 29 | team: fields.ForeignKeyNullableRelation[Team] = fields.ForeignKeyField( 30 | "models.Team", "members", null=True, on_delete=fields.OnDelete.SET_NULL 31 | ) 32 | 33 | async def save(self, *args, **kwargs): 34 | # TODO: Insert/Update in one query 35 | # Reason why we dont use pre_save: overhead, ugly 36 | if self.team is not None and hasattr(self.team, "members"): 37 | count = await self.team.members.filter(~Q(id=self.pk)).count() 38 | if count >= config.max_members_per_team: 39 | raise IntegrityError( 40 | f"{config.max_members_per_team}" 41 | " or more users already exist for the team" 42 | ) 43 | return await super().save(*args, **kwargs) 44 | 45 | 46 | class Team(Model): 47 | id = fields.IntField( 48 | pk=True 49 | ) # team.id raises Team does not have id, so explicitly adding it 50 | name = fields.CharField(255, unique=True) 51 | secret_hash = fields.TextField() 52 | coins = fields.IntField(default=0) 53 | points = fields.IntField(default=0) 54 | 55 | members: fields.ReverseRelation[User] 56 | containers: fields.ReverseRelation[Container] 57 | 58 | class PydanticMeta: 59 | exclude = ["secret_hash"] 60 | 61 | 62 | Team_Pydantic = pydantic_model_creator(Team) 63 | User_Pydantic = pydantic_model_creator(User) 64 | -------------------------------------------------------------------------------- /src/pwncore/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lugvitc/pwncore/8060e4b0a0e4953ef2e14b201af6726e2b8720b2/src/pwncore/py.typed -------------------------------------------------------------------------------- /src/pwncore/routes/__init__.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter 2 | 3 | from pwncore.routes import ctf, team, auth, admin, leaderboard 4 | 5 | # from pwncore.config import config 6 | 7 | # Main router (all routes go under /api) 8 | router = APIRouter(prefix="/api") 9 | 10 | # Include all the subroutes 11 | router.include_router(auth.router) 12 | router.include_router(ctf.router) 13 | router.include_router(team.router) 14 | router.include_router(leaderboard.router) 15 | router.include_router(admin.router) 16 | # if config.development: 17 | # router.include_router(admin.router) 18 | -------------------------------------------------------------------------------- /src/pwncore/routes/admin.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from datetime import date 3 | 4 | from fastapi import APIRouter, Request, Response 5 | from passlib.hash import bcrypt, bcrypt_sha256 6 | from tortoise.transactions import atomic, in_transaction 7 | 8 | import pwncore.containerASD as containerASD 9 | from pwncore.config import config 10 | from pwncore.models import ( 11 | Hint, 12 | PreEventProblem, 13 | PreEventSolvedProblem, 14 | Problem, 15 | Team, 16 | User, 17 | ) 18 | from pwncore.models.ctf import SolvedProblem 19 | from pwncore.models.pre_event import PreEventUser 20 | 21 | metadata = { 22 | "name": "admin", 23 | "description": "Admin routes (currently only running when development on)", 24 | } 25 | 26 | # TODO: Make this protected 27 | router = APIRouter(prefix="/admin", tags=["admin"]) 28 | 29 | if config.development: 30 | logging.basicConfig(level=logging.INFO) 31 | 32 | NAMES = [ 33 | "Mimas", 34 | "Enceladus", 35 | "Tethys", 36 | "Dione", 37 | "Rhea", 38 | "Titan", 39 | "Hyperion", 40 | "Iapetus", 41 | "Phoebe", 42 | "Janus", 43 | "Epimetheus", 44 | "Pan", 45 | ] 46 | 47 | 48 | async def _del_cont(id: str): 49 | container = await containerASD.docker_client.containers.get(id) 50 | await container.kill() 51 | await container.delete() 52 | 53 | 54 | @atomic() 55 | @router.get("/union") 56 | async def calculate_team_coins( 57 | response: Response, req: Request 58 | ): # Inefficient, anyways will be used only once 59 | if not bcrypt_sha256.verify((await req.body()).strip(), config.admin_hash): # Use config.admin_hash 60 | response.status_code = 401 61 | return 62 | async with in_transaction(): 63 | logging.info("Calculating team points form pre-event CTFs:") 64 | team_ids = await Team.filter().values_list("id", flat=True) 65 | for team_id in team_ids: 66 | member_tags = await User.filter(team_id=team_id).values_list( 67 | "tag", flat=True 68 | ) 69 | 70 | if not member_tags: 71 | return 0 72 | 73 | problems_solved = set( 74 | await PreEventSolvedProblem.filter(user_id__in=member_tags).values_list( 75 | "problem_id", flat=True 76 | ) 77 | ) 78 | 79 | team = await Team.get(id=team_id) 80 | for ctf_id in problems_solved: 81 | team.coins += (await PreEventProblem.get(id=ctf_id)).points 82 | logging.info(f"{team.id}) {team.name}: {team.coins}") 83 | await team.save() 84 | 85 | 86 | @router.get("/create") 87 | async def init_db( 88 | response: Response, req: Request 89 | ): # Inefficient, anyways will be used only once 90 | if not bcrypt_sha256.verify((await req.body()).strip(), config.admin_hash): 91 | response.status_code = 401 92 | return 93 | await Problem.create( 94 | name="Invisible-Incursion", 95 | description="Chod de tujhe se na ho paye", 96 | author="Meetesh Saini", 97 | points=300, 98 | image_name="key:latest", 99 | # image_config={"PortBindings": {"22/tcp": [{}]}}, 100 | mi=200, 101 | ma=400, 102 | ) 103 | await PreEventProblem.create( 104 | name="Static_test", 105 | description="Chod de tujhe se na ho paye", 106 | author="Meetesh Saini", 107 | points=20, 108 | flag="asd", 109 | url="lugvitc.org", 110 | date=date.today(), 111 | ) 112 | await PreEventProblem.create( 113 | name="New Static Test", 114 | description="AJJSBFISHDBFHSD", 115 | author="Meetesh Saini", 116 | points=21, 117 | flag="asdf", 118 | url="lugvitc.org", 119 | date=date.today(), 120 | ) 121 | await PreEventProblem.create( 122 | name="Static_test2", 123 | description="Chod de tujhe se na ho payga", 124 | author="Meetesh_Saini", 125 | points=23, 126 | flag="asd", 127 | url="http://lugvitc.org", 128 | date=date.today(), 129 | ) 130 | await Problem.create( 131 | name="In-Plain-Sight", 132 | description="A curious image with hidden secrets?", 133 | author="KreativeThinker", 134 | points=300, 135 | image_name="key:latest", 136 | # image_config={"PortBindings": {"22/tcp": [{}]}}, 137 | mi=200, 138 | ma=400, 139 | ) 140 | await Problem.create( 141 | name="GitGood", 142 | description="How to master the art of solving CTFs? Git good nub.", 143 | author="Aadivishnu and Shoubhit", 144 | points=300, 145 | image_name="reg.lugvitc.net/key:latest", 146 | # image_config={"PortBindings": {"22/tcp": [{}]}}, 147 | ) 148 | await Team.create(name="CID Squad", secret_hash=bcrypt.hash("veryverysecret")) 149 | await Team.create( 150 | name="Triple A battery", secret_hash=bcrypt.hash("chotiwali"), coins=20 151 | ) 152 | await PreEventUser.create(tag="23BCE1000", email="dd@ff.in") 153 | await PreEventUser.create(tag="23BRS1000", email="d2d@ff.in") 154 | await PreEventSolvedProblem.create(user_id="23BCE1000", problem_id="1") 155 | await PreEventSolvedProblem.create(user_id="23BRS1000", problem_id="1") 156 | # await PreEventSolvedProblem.create( 157 | # tag="23BAI1000", 158 | # problem_id="2" 159 | # ) 160 | await User.create( 161 | tag="23BRS1000", 162 | name="abc", 163 | team_id=2, 164 | phone_num=1111111111, 165 | email="email1@xyz.org", 166 | ) 167 | await User.create( 168 | tag="23BCE1000", 169 | name="def", 170 | team_id=2, 171 | phone_num=2222222222, 172 | email="email1@xyz.org", 173 | ) 174 | await User.create( 175 | tag="23BAI1000", 176 | name="ghi", 177 | team_id=2, 178 | phone_num=3333333333, 179 | email="email1@xyz.org", 180 | ) 181 | await User.create( 182 | tag="23BRS2000", 183 | name="ABC", 184 | team_id=1, 185 | phone_num=4444444444, 186 | email="email1@xyz.org", 187 | ) 188 | await User.create( 189 | tag="23BCE2000", 190 | name="DEF", 191 | team_id=1, 192 | phone_num=5555555555, 193 | email="email1@xyz.org", 194 | ) 195 | await User.create( 196 | tag="23BAI2000", 197 | name="GHI", 198 | team_id=1, 199 | phone_num=6666666666, 200 | email="email1@xyz.org", 201 | ) 202 | await Hint.create(order=0, problem_id=1, text="This is the first hint") 203 | await Hint.create(order=1, problem_id=1, text="This is the second hint") 204 | await Hint.create(order=2, problem_id=1, text="This is the third hint") 205 | await Hint.create(order=0, problem_id=2, text="This is the first hint") 206 | await Hint.create(order=1, problem_id=2, text="This is the second hint") 207 | await SolvedProblem.create(team_id=2, problem_id=1) 208 | await SolvedProblem.create(team_id=2, problem_id=2) 209 | await SolvedProblem.create(team_id=1, problem_id=2) 210 | -------------------------------------------------------------------------------- /src/pwncore/routes/auth.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import datetime 4 | import typing as t 5 | from logging import getLogger 6 | 7 | import jwt 8 | from fastapi import APIRouter, Depends, Header, HTTPException, Response 9 | from passlib.hash import bcrypt 10 | from pydantic import BaseModel 11 | from tortoise.transactions import atomic 12 | 13 | from pwncore.config import config 14 | from pwncore.models import Team, User 15 | 16 | # Metadata at the top for instant accessibility 17 | metadata = { 18 | "name": "auth", 19 | "description": "Authentication using a JWT using a single access token.", 20 | } 21 | 22 | router = APIRouter(prefix="/auth", tags=["auth"]) 23 | logger = getLogger(__name__) 24 | 25 | 26 | class AuthBody(BaseModel): 27 | name: str 28 | password: str 29 | 30 | 31 | class SignupBody(BaseModel): 32 | name: str 33 | password: str 34 | tags: set[str] 35 | 36 | 37 | def normalise_tag(tag: str): 38 | return tag.strip().casefold() 39 | 40 | 41 | @atomic() 42 | @router.post("/signup") 43 | async def signup_team(team: SignupBody, response: Response): 44 | team.name = team.name.strip() 45 | members = set(map(normalise_tag, team.tags)) 46 | 47 | try: 48 | if await Team.exists(name=team.name): 49 | response.status_code = 406 50 | return {"msg_code": config.msg_codes["team_exists"]} 51 | 52 | q = await User.filter(tag__in=members) 53 | # print(q, members) 54 | if len(q) != len(members): 55 | response.status_code = 404 56 | return { 57 | "msg_code": config.msg_codes["users_not_found"], 58 | "tags": list(members - set(map(lambda h: h.tag, q))), 59 | } 60 | in_teams = list(filter(lambda h: h.team, q)) 61 | if in_teams: 62 | response.status_code = 401 63 | return { 64 | "msg_code": config.msg_codes["user_already_in_team"], 65 | "tags": list(in_teams), 66 | } 67 | 68 | newteam = await Team.create( 69 | name=team.name, secret_hash=bcrypt.hash(team.password) 70 | ) 71 | 72 | for user in q: 73 | # Mypy kinda not working 74 | user.team_id = newteam.id # type: ignore[attr-defined] 75 | if q: 76 | b = User.bulk_update(q, fields=["team_id"]) 77 | # print(b.sql()) 78 | await b 79 | except Exception: 80 | logger.exception("error in signup!") 81 | response.status_code = 500 82 | return {"msg_code": config.msg_codes["db_error"]} 83 | return {"msg_code": config.msg_codes["signup_success"]} 84 | 85 | 86 | @router.post("/login") 87 | async def team_login(team_data: AuthBody, response: Response): 88 | # TODO: Simplified logic since we're not doing refresh tokens. 89 | 90 | team = await Team.get_or_none(name=team_data.name) 91 | if team is None: 92 | response.status_code = 404 93 | return {"msg_code": config.msg_codes["team_not_found"]} 94 | if not bcrypt.verify(team_data.password, team.secret_hash): 95 | response.status_code = 401 96 | return {"msg_code": config.msg_codes["wrong_password"]} 97 | 98 | current_time = datetime.datetime.utcnow() 99 | expiration_time = current_time + datetime.timedelta(hours=config.jwt_valid_duration) 100 | token_payload = {"team_id": team.id, "exp": expiration_time} 101 | token = jwt.encode(token_payload, config.jwt_secret, algorithm="HS256") 102 | 103 | # Returning token to be sent as an authorization header "Bearer " 104 | return { 105 | "msg_code": config.msg_codes["login_success"], 106 | "access_token": token, 107 | "token_type": "bearer", 108 | } 109 | 110 | 111 | # Custom JWT processing (since FastAPI's implentation deals with refresh tokens) 112 | # Supressing B008 in order to be able to use Header() in arguments 113 | def get_jwt(*, authorization: t.Annotated[str, Header()]) -> JwtInfo: 114 | try: 115 | token = authorization.split(" ")[1] # Remove Bearer 116 | # print(token, authorization) 117 | decoded_token: JwtInfo = jwt.decode( 118 | token, config.jwt_secret, algorithms=["HS256"] 119 | ) 120 | except jwt.exceptions.InvalidTokenError as err: 121 | logger.warning("Invalid token", exc_info=err) 122 | raise HTTPException(status_code=401) 123 | return decoded_token 124 | 125 | 126 | # Using a pre-assigned variable everywhere else to follow flake8's B008 127 | JwtInfo = t.TypedDict("JwtInfo", {"team_id": int, "exp": int}) 128 | RequireJwt = t.Annotated[JwtInfo, Depends(get_jwt)] 129 | -------------------------------------------------------------------------------- /src/pwncore/routes/ctf/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from asyncio import create_task 4 | from collections import defaultdict 5 | from logging import getLogger 6 | import shutil 7 | 8 | from fastapi import APIRouter, Request, Response 9 | from pydantic import BaseModel 10 | from tortoise.transactions import atomic 11 | 12 | import pwncore.containerASD as containerASD 13 | from pwncore.config import config 14 | from pwncore.models import ( 15 | Container, 16 | Hint, 17 | Hint_Pydantic, 18 | Problem, 19 | SolvedProblem, 20 | Team, 21 | ViewedHint, 22 | ) 23 | from pwncore.models.ctf import Problem_Pydantic 24 | from pwncore.routes.auth import RequireJwt 25 | from pwncore.routes.ctf.pre_event import router as pre_event_router 26 | from pwncore.routes.ctf.start import router as start_router 27 | 28 | # Metadata at the top for instant accessibility 29 | metadata = { 30 | "name": "ctf", 31 | "description": "Operations related to CTF, except" 32 | "create and delete (those are under admin)", 33 | } 34 | 35 | router = APIRouter(prefix="/ctf", tags=["ctf"]) 36 | router.include_router(start_router) 37 | router.include_router(pre_event_router) 38 | 39 | logger = getLogger("routes.ctf") 40 | 41 | 42 | def _invalid_order(): 43 | logger.warn("= Invalid penalty lookup by order occured =") 44 | return 0 45 | 46 | 47 | # 0 - 10 - 10 48 | # 1 - 5 - 15 49 | # 2 - 10 - 25 50 | HINTPENALTY = defaultdict(_invalid_order, {0: 10, 1: 5, 2: 10}) 51 | 52 | 53 | class Flag(BaseModel): 54 | flag: str 55 | 56 | 57 | @router.get("/completed") 58 | async def completed_problem_get(jwt: RequireJwt): 59 | team_id = jwt["team_id"] 60 | ViewedHint.filter(team_id=team_id).annotate() 61 | problems = await Problem_Pydantic.from_queryset( 62 | Problem.filter(solvedproblems__team_id=team_id, visible=True) 63 | ) 64 | return problems 65 | 66 | 67 | @router.get("/list") 68 | async def ctf_list(jwt: RequireJwt): 69 | team_id = jwt["team_id"] 70 | problems = await Problem_Pydantic.from_queryset(Problem.filter(visible=True)) 71 | acc: dict[int, float] = defaultdict(lambda: 1.0) 72 | for k, v in map( 73 | lambda x: (x.hint.problem_id, HINTPENALTY[x.hint.order]), # type: ignore[attr-defined] 74 | await ViewedHint.filter(team_id=team_id, with_points=True).prefetch_related( 75 | "hint" 76 | ), 77 | ): 78 | acc[k] -= v / 100 79 | for i in problems: 80 | i.points = int(acc[i.id] * i.points) # type: ignore[attr-defined] 81 | return problems 82 | 83 | 84 | async def update_points(req: Request, ctf_id: int): 85 | try: 86 | p = await Problem.get(id=ctf_id) 87 | await p.update_points() 88 | req.app.state.force_expire = True 89 | except Exception: 90 | logger.exception("An error occured while updating points") 91 | 92 | 93 | @atomic() 94 | @router.post("/{ctf_id}/flag") 95 | async def flag_post( 96 | req: Request, ctf_id: int, flag: Flag, response: Response, jwt: RequireJwt 97 | ): 98 | team_id = jwt["team_id"] 99 | problem = await Problem.get_or_none(id=ctf_id, visible=True) 100 | if not problem: 101 | response.status_code = 404 102 | return {"msg_code": config.msg_codes["ctf_not_found"]} 103 | 104 | status = await SolvedProblem.exists(team_id=team_id, problem_id=ctf_id) 105 | if status: 106 | response.status_code = 401 107 | return {"msg_code": config.msg_codes["ctf_solved"]} 108 | 109 | team_container = await Container.get_or_none(team_id=team_id, problem_id=ctf_id) 110 | if not team_container: 111 | return {"msg_code": config.msg_codes["container_not_found"]} 112 | 113 | if team_container.flag == flag.flag.strip(): 114 | hints = await Hint.filter( 115 | problem_id=ctf_id, 116 | viewedhints__team_id=team_id, 117 | viewedhints__with_points=True, 118 | ) 119 | pnlt = (100 - sum(map(lambda h: HINTPENALTY[h.order], hints))) / 100 120 | 121 | # Stop container after submitting 122 | try: 123 | await Container.filter(team_id=team_id, problem_id=ctf_id).delete() 124 | except Exception: 125 | response.status_code = 500 126 | return {"msg_code": config.msg_codes["db_error"]} 127 | 128 | if problem.static: 129 | shutil.rmtree( 130 | f"{config.staticfs_data_dir}/{team_id}/{team_container.docker_id}" 131 | ) 132 | else: 133 | container = await containerASD.docker_client.containers.get( 134 | team_container.docker_id 135 | ) 136 | await container.kill() 137 | await container.delete() 138 | 139 | await SolvedProblem.create(team_id=team_id, problem_id=ctf_id, penalty=pnlt) 140 | create_task(update_points(req, ctf_id)) 141 | return {"status": True} 142 | 143 | return {"status": False} 144 | 145 | 146 | @atomic() 147 | @router.get("/{ctf_id}/hint") 148 | async def hint_get(ctf_id: int, response: Response, jwt: RequireJwt): 149 | team_id = jwt["team_id"] 150 | problem = await Problem.exists(id=ctf_id, visible=True) 151 | if not problem: 152 | response.status_code = 404 153 | return {"msg_code": config.msg_codes["ctf_not_found"]} 154 | 155 | team = await Team.get(id=team_id) 156 | # if team.coins < config.hint_penalty: 157 | # return {"msg_code": config.msg_codes["insufficient_coins"]} 158 | 159 | viewed_hints = ( 160 | await Hint.filter(problem_id=ctf_id, viewedhints__team_id=team_id) 161 | .order_by("-order") 162 | .first() 163 | ) 164 | if viewed_hints: 165 | if not await Hint.exists(problem_id=ctf_id, order=viewed_hints.order + 1): 166 | response.status_code = 403 167 | return {"msg_code": config.msg_codes["hint_limit_reached"]} 168 | 169 | hint = await Hint.get(problem_id=ctf_id, order=viewed_hints.order + 1) 170 | 171 | else: 172 | hint = await Hint.get(problem_id=ctf_id, order=0) 173 | 174 | with_points = team.coins < config.hint_penalty 175 | if not with_points: 176 | team.coins -= config.hint_penalty 177 | await team.save() 178 | 179 | await ViewedHint.create(hint_id=hint.id, team_id=team_id, with_points=with_points) 180 | return { 181 | "text": hint.text, 182 | "order": hint.order, 183 | } 184 | 185 | 186 | @router.get("/{ctf_id}/viewed_hints") 187 | async def viewed_problem_hints_get(ctf_id: int, jwt: RequireJwt): 188 | team_id = jwt["team_id"] 189 | viewed_hints = await Hint_Pydantic.from_queryset( 190 | Hint.filter(problem_id=ctf_id, viewedhints__team_id=team_id) 191 | ) 192 | return viewed_hints 193 | 194 | 195 | @router.get("/{ctf_id}") 196 | async def ctf_get(ctf_id: int, response: Response): 197 | problem = await Problem_Pydantic.from_queryset( 198 | Problem.filter(id=ctf_id, visible=True) 199 | ) 200 | if not problem: 201 | response.status_code = 404 202 | return {"msg_code": config.msg_codes["ctf_not_found"]} 203 | return problem 204 | -------------------------------------------------------------------------------- /src/pwncore/routes/ctf/pre_event.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from datetime import datetime, timezone, timedelta 4 | 5 | from fastapi import APIRouter, Response 6 | from pydantic import BaseModel 7 | from tortoise.transactions import atomic 8 | from tortoise.functions import Sum 9 | from tortoise.exceptions import DoesNotExist, IntegrityError 10 | 11 | from pwncore.models import ( 12 | PreEventProblem, 13 | PreEventSolvedProblem, 14 | PreEventUser, 15 | PreEventProblem_Pydantic, 16 | ) 17 | from pwncore.config import config 18 | 19 | router = APIRouter(prefix="/pre", tags=["ctf"]) 20 | _IST = timezone(timedelta(hours=5, minutes=30)) 21 | 22 | 23 | class PreEventFlag(BaseModel): 24 | tag: str 25 | flag: str 26 | email: str 27 | 28 | 29 | class CoinsQuery(BaseModel): 30 | tag: str 31 | 32 | 33 | @router.get("/list") 34 | async def ctf_list(): 35 | problems = await PreEventProblem_Pydantic.from_queryset(PreEventProblem.all()) 36 | return problems 37 | 38 | 39 | @router.get("/today") 40 | async def ctf_today(): 41 | return await PreEventProblem_Pydantic.from_queryset( 42 | PreEventProblem().filter(date=datetime.now(_IST).date()) 43 | ) 44 | 45 | 46 | @router.get("/coins/{tag}") 47 | async def coins_get(tag: str): 48 | try: 49 | return { 50 | "coins": await PreEventUser.get(tag=tag.strip().casefold()) 51 | .annotate(coins=Sum("solvedproblems__problem__points")) 52 | .values_list("coins", flat=True) 53 | } 54 | except DoesNotExist: 55 | return 0 56 | 57 | 58 | @atomic() 59 | @router.post("/{ctf_id}/flag") 60 | async def pre_event_flag_post(ctf_id: int, post_body: PreEventFlag, response: Response): 61 | problem = await PreEventProblem.get_or_none(id=ctf_id) 62 | 63 | if not problem or (problem.date != datetime.now(_IST).date()): 64 | response.status_code = 404 65 | return {"msg_code": config.msg_codes["ctf_not_found"]} 66 | 67 | user_tag = post_body.tag.strip().casefold() 68 | 69 | if await PreEventSolvedProblem.exists(user_id=user_tag, problem_id=ctf_id): 70 | response.status_code = 401 71 | return {"msg_code": config.msg_codes["ctf_solved"]} 72 | 73 | try: 74 | pu = await PreEventUser.get_or_none(tag=user_tag) 75 | print(pu, user_tag, post_body.email) 76 | if pu is None: 77 | print(1) 78 | pu = await PreEventUser.create(tag=user_tag, email=post_body.email) 79 | elif pu.email != post_body.email: 80 | print(2) 81 | pu.email = post_body.email 82 | await pu.save() 83 | except IntegrityError: 84 | response.status_code = 401 85 | return {"msg_code": config.msg_codes["user_or_email_exists"]} 86 | 87 | if status := problem.flag == post_body.flag: 88 | await PreEventSolvedProblem.create(user=pu, problem_id=ctf_id) 89 | 90 | coins = ( 91 | await PreEventUser.get(tag=user_tag) 92 | .annotate(coins=Sum("solvedproblems__problem__points")) 93 | .values_list("coins", flat=True) 94 | ) 95 | 96 | return {"status": status, "coins": coins} 97 | 98 | 99 | @router.get("/{ctf_id}") 100 | async def ctf_get(ctf_id: int, response: Response): 101 | problem = await PreEventProblem_Pydantic.from_queryset( 102 | PreEventProblem.filter(id=ctf_id) 103 | ) 104 | if not problem: 105 | response.status_code = 404 106 | return {"msg_code": config.msg_codes["ctf_not_found"]} 107 | return problem 108 | -------------------------------------------------------------------------------- /src/pwncore/routes/ctf/start.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import uuid 5 | import shutil 6 | from logging import getLogger 7 | import jwt as jwtlib 8 | from fastapi import APIRouter, Response 9 | from tortoise.transactions import in_transaction 10 | 11 | import pwncore.containerASD as containerASD 12 | from pwncore.config import config 13 | from pwncore.models import Container, Ports, Problem 14 | from pwncore.routes.auth import RequireJwt 15 | 16 | router = APIRouter(tags=["ctf"]) 17 | logger = getLogger(__name__) 18 | 19 | 20 | @router.post("/{ctf_id}/start") 21 | async def start_docker_container(ctf_id: int, response: Response, jwt: RequireJwt): 22 | """ 23 | image_config contains the raw POST data that gets sent to the Docker Remote API. 24 | For now it just contains the guest ports that need to be opened on the host. 25 | image_config: 26 | { 27 | "PortBindings": { 28 | "22/tcp": [{}] # Let docker randomly assign ports 29 | } 30 | } 31 | 32 | Notes: 33 | - image_config has been commented out in the Problem model for now. 34 | - It's not necessary to pass the ports to expose in image_config, 35 | Docker will automatically map a random port to the container's exposed port. 36 | """ 37 | async with in_transaction(): 38 | ctf = await Problem.get_or_none(id=ctf_id, visible=True) 39 | if not ctf: 40 | response.status_code = 404 41 | return {"msg_code": config.msg_codes["ctf_not_found"]} 42 | 43 | team_id = jwt["team_id"] # From JWT 44 | team_container = await Container.filter(team=team_id, problem=ctf_id) 45 | if team_container: 46 | a, b = team_container[0], team_container[1:] 47 | db_ports = await a.ports.all().values("port") # Get ports from DB 48 | ports = [db_port["port"] for db_port in db_ports] # Create a list out of it 49 | static_url = f"{config.staticfs_url}/{a.token}" if ctf.static else None 50 | for db_container in b: 51 | try: 52 | await db_container.delete() 53 | except Exception: 54 | pass 55 | # containers won't exist for static ctfs 56 | if ctf.static: 57 | staticLocation = f"{config.staticfs_data_dir}/{team_id}/{db_container.docker_id}" 58 | if os.path.exists(staticLocation): 59 | shutil.rmtree(staticLocation) 60 | else: 61 | container = await containerASD.docker_client.containers.get( 62 | db_container.docker_id 63 | ) 64 | await container.kill() 65 | await container.delete() 66 | 67 | return { 68 | "msg_code": config.msg_codes["container_already_running"], 69 | "ports": ports, 70 | "static_url": static_url, 71 | "ctf_id": ctf_id, 72 | } 73 | 74 | if ( 75 | await Container.filter( 76 | team_id=team_id 77 | ).count() >= config.max_containers_per_team 78 | ): # fmt: skip 79 | return {"msg_code": config.msg_codes["container_limit_reached"]} 80 | 81 | # Start a new container 82 | container_name = f"{team_id}_{ctf_id}_{uuid.uuid4().hex}" 83 | container_flag = f"{config.flag}{{{uuid.uuid4().hex}}}" 84 | 85 | if ctf.static: 86 | container_id = uuid.uuid4().hex 87 | payload = { 88 | "id": str(team_id), 89 | "containerId": container_id, 90 | } 91 | token = jwtlib.encode(payload, config.staticfs_jwt_secret, algorithm="HS256") 92 | container = await containerASD.docker_client.containers.run( 93 | name=container_name, 94 | config={ 95 | "Image": ctf.image_name, 96 | "AttachStdin": False, 97 | "AttachStdout": False, 98 | "AttachStderr": False, 99 | "Tty": False, 100 | "OpenStdin": False, 101 | "HostConfig": { 102 | "AutoRemove": True, 103 | "Binds": [f"{config.staticfs_data_dir}/{team_id}/{container_id}:/dist"], 104 | }, 105 | "Cmd": ["/root/gen_flag", container_flag], 106 | }, 107 | ) 108 | try: 109 | async with in_transaction(): 110 | db_container = await Container.create( 111 | docker_id=container_id, 112 | team_id=team_id, 113 | problem_id=ctf_id, 114 | flag=container_flag, 115 | token=token, 116 | ) 117 | except Exception as err: 118 | # Stop the container if failed to make a DB record 119 | await container.kill() 120 | await container.delete() 121 | logger.exception("Error while starting", exc_info=err) 122 | 123 | response.status_code = 500 124 | return {"msg_code": config.msg_codes["db_error"]} 125 | return { 126 | "msg_code": config.msg_codes["container_start"], 127 | "ports": [], 128 | "static_url": f"{config.staticfs_url}/{token}", 129 | "ctf_id": ctf_id, 130 | } 131 | 132 | # Run 133 | container = await containerASD.docker_client.containers.run( 134 | name=container_name, 135 | config={ 136 | "Image": ctf.image_name, 137 | # Detach stuff 138 | "AttachStdin": False, 139 | "AttachStdout": False, 140 | "AttachStderr": False, 141 | "Tty": False, 142 | "OpenStdin": False, 143 | "HostConfig": {"PublishAllPorts": True}, 144 | # **ctf.image_config, 145 | }, 146 | ) 147 | 148 | await (await container.exec(["/root/gen_flag", container_flag])).start( 149 | detach=True 150 | ) 151 | 152 | try: 153 | async with in_transaction(): 154 | db_container = await Container.create( 155 | docker_id=container.id, 156 | team_id=team_id, 157 | problem_id=ctf_id, 158 | flag=container_flag, 159 | ) 160 | 161 | # Get ports and save them 162 | guest_ports = (await container.show())["NetworkSettings"]["Ports"] 163 | ports = [] # List to return back to frontend 164 | for guest_port in guest_ports: 165 | # Docker assigns the port to the IPv4 and IPv6 addresses 166 | # Since we only require IPv4, we select the zeroth item 167 | # from the returned list. 168 | port = int(guest_ports[guest_port][0]["HostPort"]) 169 | ports.append(port) 170 | await Ports.create(port=port, container=db_container) 171 | except Exception as err: 172 | # Stop the container if failed to make a DB record 173 | await container.kill() 174 | await container.delete() 175 | logger.exception("Error while starting", exc_info=err) 176 | 177 | response.status_code = 500 178 | return {"msg_code": config.msg_codes["db_error"]} 179 | 180 | return { 181 | "msg_code": config.msg_codes["container_start"], 182 | "ports": ports, 183 | "static_url": None, 184 | "ctf_id": ctf_id, 185 | } 186 | 187 | 188 | @router.post("/stopall") 189 | async def stopall_docker_container(response: Response, jwt: RequireJwt): 190 | async with in_transaction(): 191 | team_id = jwt["team_id"] # From JWT 192 | 193 | containers = await Container.filter(team_id=team_id).values() 194 | 195 | # We first try to delete the record from the DB 196 | # Then we stop the container 197 | try: 198 | await Container.filter(team_id=team_id).delete() 199 | except Exception: 200 | response.status_code = 500 201 | return {"msg_code": config.msg_codes["db_error"]} 202 | 203 | team_path = f"{config.staticfs_data_dir}/{team_id}" 204 | if os.path.exists(team_path): 205 | shutil.rmtree(team_path) 206 | 207 | for db_container in containers: 208 | container = await containerASD.docker_client.containers.get( 209 | db_container["docker_id"] 210 | ) 211 | await container.kill() 212 | await container.delete() 213 | 214 | return {"msg_code": config.msg_codes["containers_team_stop"]} 215 | 216 | 217 | @router.post("/{ctf_id}/stop") 218 | async def stop_docker_container(ctf_id: int, response: Response, jwt: RequireJwt): 219 | async with in_transaction(): 220 | # Let this work on invisible problems incase 221 | # we mess up the database while making problems visible 222 | ctf = await Problem.get_or_none(id=ctf_id) 223 | if not ctf: 224 | response.status_code = 404 225 | return {"msg_code": config.msg_codes["ctf_not_found"]} 226 | 227 | team_id = jwt["team_id"] 228 | team_container = await Container.get_or_none(team_id=team_id, problem_id=ctf_id) 229 | if not team_container: 230 | return {"msg_code": config.msg_codes["container_not_found"]} 231 | 232 | # We first try to delete the record from the DB 233 | # Then we stop the container 234 | try: 235 | await Container.filter(team_id=team_id, problem_id=ctf_id).delete() 236 | except Exception: 237 | response.status_code = 500 238 | return {"msg_code": config.msg_codes["db_error"]} 239 | 240 | if ctf.static: 241 | shutil.rmtree( 242 | f"{config.staticfs_data_dir}/{team_id}/{team_container.docker_id}" 243 | ) 244 | return {"msg_code": config.msg_codes["container_stop"]} 245 | 246 | container = await containerASD.docker_client.containers.get( 247 | team_container.docker_id 248 | ) 249 | await container.kill() 250 | await container.delete() 251 | 252 | return {"msg_code": config.msg_codes["container_stop"]} 253 | -------------------------------------------------------------------------------- /src/pwncore/routes/leaderboard.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from json import dumps 4 | from time import monotonic 5 | 6 | from fastapi import APIRouter, Request, Response 7 | 8 | from tortoise.expressions import RawSQL, Q 9 | 10 | from pwncore.models import Team 11 | 12 | # Metadata at the top for instant accessibility 13 | metadata = {"name": "leaderboard", "description": "Operations on the leaderboard"} 14 | 15 | router = APIRouter(prefix="/leaderboard", tags=["leaderboard"]) 16 | 17 | 18 | class ExpiringLBCache: 19 | period: float 20 | last_update: float 21 | data: bytes 22 | 23 | def __init__(self, period: float) -> None: 24 | self.period = period 25 | self.last_update = 0 26 | self.data = b"[]" 27 | 28 | async def _do_update(self): 29 | self.data = dumps( 30 | ( 31 | await Team.all() 32 | .filter(Q(solved_problem__problem__visible=True) | Q(points__gte=0)) 33 | .annotate( 34 | tpoints=RawSQL( 35 | 'COALESCE((SUM("solvedproblem"."penalty" * ' 36 | '"solvedproblem__problem"."points")' 37 | ' + "team"."points"), 0)' 38 | ) 39 | ) 40 | .group_by("id") 41 | .order_by("-tpoints") 42 | .values("name", "tpoints") 43 | ), 44 | separators=(",", ":"), 45 | ).encode("utf-8") 46 | self.last_update = monotonic() 47 | 48 | async def get_lb(self, req: Request): 49 | if ( 50 | getattr(req.app.state, "force_expire", False) 51 | or (monotonic() - self.last_update) > self.period # noqa: W503 52 | ): 53 | await self._do_update() 54 | req.app.state.force_expire = False 55 | return self.data 56 | 57 | 58 | gcache = ExpiringLBCache(30.0) 59 | 60 | 61 | @router.get("") 62 | async def fetch_leaderboard(req: Request): 63 | return Response(content=await gcache.get_lb(req), media_type="application/json") 64 | -------------------------------------------------------------------------------- /src/pwncore/routes/team.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from fastapi import APIRouter, Response 4 | from pydantic import BaseModel 5 | from tortoise.transactions import atomic 6 | 7 | from pwncore.config import config 8 | from pwncore.models import Team, User, Team_Pydantic, User_Pydantic, Container 9 | from pwncore.routes.auth import RequireJwt 10 | 11 | # from pwncore.routes.leaderboard import gcache 12 | 13 | # Metadata at the top for instant accessibility 14 | metadata = {"name": "team", "description": "Operations with teams"} 15 | 16 | router = APIRouter(prefix="/team", tags=["team"]) 17 | 18 | 19 | class UserAddBody(BaseModel): 20 | tag: str 21 | name: str 22 | email: str 23 | phone_num: str 24 | 25 | 26 | class UserRemoveBody(BaseModel): 27 | tag: str 28 | 29 | 30 | @router.get("/list") 31 | async def team_list(): 32 | teams = await Team_Pydantic.from_queryset(Team.all()) 33 | return teams 34 | 35 | 36 | # Unable to test as adding users returns an error 37 | @router.get("/members") 38 | async def team_members(jwt: RequireJwt): 39 | team_id = jwt["team_id"] 40 | members = await User_Pydantic.from_queryset(User.filter(team_id=team_id)) 41 | # Incase of no members, it just returns an empty list. 42 | return members 43 | 44 | 45 | @router.get("/me") 46 | async def get_self_team(jwt: RequireJwt): 47 | team_id = jwt["team_id"] 48 | 49 | team_model = await Team.get(id=team_id) 50 | 51 | team = dict(await Team_Pydantic.from_tortoise_orm(team_model)) 52 | # Get points from leaderboard 53 | # would be better is cache stores the values in a dict indexed by team id 54 | # for leaderboard_team in gcache.data: 55 | # if leaderboard_team["name"] == team["name"]: 56 | # team["tpoints"] = leaderboard_team["tpoints"] 57 | # break 58 | 59 | return team 60 | 61 | 62 | @atomic() 63 | @router.post("/add") 64 | async def add_member(user: UserAddBody, response: Response, jwt: RequireJwt): 65 | team_id = jwt["team_id"] 66 | 67 | if await User.get_or_none(tag=user.tag): 68 | response.status_code = 403 69 | return {"msg_code": config.msg_codes["user_already_in_team"]} 70 | 71 | try: 72 | await User.create( 73 | # Validation for user tag (reg. no. in our case) 74 | # needs to be done on frontend to not make the server event specific 75 | tag=user.tag.strip().casefold(), 76 | name=user.name, 77 | email=user.email, 78 | phone_num=user.phone_num, 79 | team_id=team_id, 80 | ) 81 | except Exception: 82 | response.status_code = 500 83 | return {"msg_code": config.msg_codes["db_error"]} 84 | return {"msg_code": config.msg_codes["user_added"]} 85 | 86 | 87 | @atomic() 88 | @router.post("/remove") 89 | async def remove_member(user_info: UserRemoveBody, response: Response, jwt: RequireJwt): 90 | team_id = jwt["team_id"] 91 | 92 | user = await User.get_or_none(team_id=team_id, tag=user_info.tag) 93 | if not user: 94 | response.status_code = 403 95 | return {"msg_code": config.msg_codes["user_not_in_team"]} 96 | 97 | try: 98 | await user.delete() 99 | except Exception: 100 | response.status_code = 500 101 | return {"msg_code": config.msg_codes["db_error"]} 102 | return {"msg_code": config.msg_codes["user_removed"]} 103 | 104 | 105 | @router.get("/containers") 106 | async def get_team_containers(response: Response, jwt: RequireJwt): 107 | containers = await Container.filter(team_id=jwt["team_id"]).prefetch_related( 108 | "ports", "problem" 109 | ) 110 | 111 | result = {} 112 | for container in containers: 113 | # mypy complains id doesnt exist in Problem 114 | result[container.problem.id] = await container.ports.all().values_list( # type: ignore[attr-defined] 115 | "port", flat=True 116 | ) 117 | 118 | return result 119 | -------------------------------------------------------------------------------- /src/pwncore/types.py: -------------------------------------------------------------------------------- 1 | """Only for type aliases and nothing else. 2 | """ 3 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lugvitc/pwncore/8060e4b0a0e4953ef2e14b201af6726e2b8720b2/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_login.py: -------------------------------------------------------------------------------- 1 | from fastapi.testclient import TestClient 2 | 3 | from pwncore import app 4 | 5 | client = TestClient(app) 6 | 7 | 8 | # Example test 9 | def test_login(): 10 | # Send a GET response to the specified endpoint 11 | response = client.get("/api/team/login") 12 | 13 | # Evaluate the response against expected values 14 | assert response.status_code == 404 15 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 80 3 | select = C,E,F,W,B,B950 4 | extend-ignore = E203, E501, E704 5 | 6 | [tox] 7 | envlist = 8 | py31{1,2} 9 | type 10 | lint 11 | 12 | [gh] 13 | python = 14 | 3.12 = py312 15 | 3.11 = py311, type, lint 16 | 17 | [testenv] 18 | description = run api tests 19 | deps = 20 | fastapi==0.104.1 21 | httpx==0.25.2 22 | pytest==7.4.4 23 | passlib==1.7.4 24 | commands = pytest 25 | 26 | [testenv:type] 27 | base_python = py311 28 | description = run type checking 29 | deps = 30 | mypy 31 | commands = mypy tests/ src/ {posargs} 32 | 33 | [testenv:black] 34 | decription = Use black to format the code 35 | skip_install = true 36 | deps = 37 | black 38 | commands = black src/ tests/ 39 | 40 | [testenv:lint] 41 | decription = Lint with flake8 42 | skip_install = true 43 | deps = 44 | flake8 45 | flake8-bugbear 46 | commands = flake8 src/ tests/ 47 | 48 | [testenv:debug] 49 | description = check if the package runs after any configuration changes, not for debugging dev changes 50 | commands = uvicorn pwncore:app 51 | 52 | # TODO: Add linting 53 | --------------------------------------------------------------------------------