pyquocca 0.0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.1
2
+ Name: pyquocca
3
+ Version: 0.0.6
4
+ Summary: Challenge utilities for SecEDU CTFs (primarily UNSW's COMP6[48]43).
5
+ Author: HamishWHC
6
+ Author-email: 20359560+HamishWHC@users.noreply.github.com
7
+ Requires-Python: >=3.10,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Requires-Dist: flask (>=3.0.2,<4.0.0)
13
+ Requires-Dist: gunicorn (>=21.2.0,<22.0.0)
14
+ Requires-Dist: python-json-logger (>=2.0.7,<3.0.0)
15
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
16
+ Requires-Dist: typing-extensions (>=4.10.0,<5.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Challenge Standard Library.
20
+ To use this in a challenge, add the following to your challenge's Dockerfile (or similar in your requirements.txt!):
21
+ ```Dockerfile
22
+ RUN pip install --extra-index-url https://6443:whatarejwts@pypi.hamishwhc.com/ pyquocca
23
+ ```
24
+
25
+ If you use this in your requirements.txt file, please delete the file after running `pip install`, so that students aren't able to find the credentials in the container.
@@ -0,0 +1,7 @@
1
+ # Challenge Standard Library.
2
+ To use this in a challenge, add the following to your challenge's Dockerfile (or similar in your requirements.txt!):
3
+ ```Dockerfile
4
+ RUN pip install --extra-index-url https://6443:whatarejwts@pypi.hamishwhc.com/ pyquocca
5
+ ```
6
+
7
+ If you use this in your requirements.txt file, please delete the file after running `pip install`, so that students aren't able to find the credentials in the container.
@@ -0,0 +1,20 @@
1
+ [tool.poetry]
2
+ name = "pyquocca"
3
+ version = "0.0.6"
4
+ description = "Challenge utilities for SecEDU CTFs (primarily UNSW's COMP6[48]43)."
5
+ authors = ["HamishWHC <20359560+HamishWHC@users.noreply.github.com>"]
6
+ readme = "README.md"
7
+
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "^3.10"
11
+ flask = "^3.0.2"
12
+ requests = "^2.31.0"
13
+ gunicorn = "^21.2.0"
14
+ python-json-logger = "^2.0.7"
15
+ typing-extensions = "^4.10.0"
16
+
17
+
18
+ [build-system]
19
+ requires = ["poetry-core"]
20
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,92 @@
1
+ import os
2
+ from typing import Optional
3
+
4
+ import requests
5
+ from flask import request as flask_request
6
+ from flask.wrappers import Request
7
+
8
+ FLAGANIZER_HOST = os.getenv("FLAGANIZER_HOST")
9
+
10
+ USERNAME_HEADER = "X-mTLS-Username"
11
+ STAFF_HEADER = "X-mTLS-Staff"
12
+ FIRST_NAME_HEADER = "X-mTLS-First-Name"
13
+ LAST_NAME_HEADER = "X-mTLS-Last-Name"
14
+ FULL_NAME_HEADER = "X-mTLS-Full-Name"
15
+ IMPERSONATED_BY_HEADER = "X-mTLS-Impersonated-By"
16
+
17
+ XSSBOT_NAME = "XSSBot"
18
+
19
+
20
+ def get_username(request: Optional[Request] = None) -> Optional[str]:
21
+ r = request if request is not None else flask_request
22
+ return r.headers.get(USERNAME_HEADER, None)
23
+
24
+
25
+ def get_impersonator(request: Optional[Request] = None) -> Optional[str]:
26
+ r = request if request is not None else flask_request
27
+ return r.headers.get(IMPERSONATED_BY_HEADER, None)
28
+
29
+
30
+ def is_staff(request: Optional[Request] = None) -> bool:
31
+ r = request if request is not None else flask_request
32
+ return r.headers.get(STAFF_HEADER, "false") == "true"
33
+
34
+
35
+ def is_xssbot(request: Optional[Request] = None) -> bool:
36
+ r = request if request is not None else flask_request
37
+ return (is_staff(r) and get_username(r) == XSSBOT_NAME) or (
38
+ get_impersonator() == XSSBOT_NAME
39
+ )
40
+
41
+
42
+ def get_first_name(request: Optional[Request] = None) -> Optional[str]:
43
+ r = request if request is not None else flask_request
44
+ return r.headers.get(FIRST_NAME_HEADER, get_username(request))
45
+
46
+
47
+ def get_last_name(request: Optional[Request] = None) -> Optional[str]:
48
+ r = request if request is not None else flask_request
49
+ return r.headers.get(LAST_NAME_HEADER, get_username(request))
50
+
51
+
52
+ def get_full_name(request: Optional[Request] = None) -> Optional[str]:
53
+ r = request if request is not None else flask_request
54
+ return r.headers.get(FULL_NAME_HEADER, get_username(request))
55
+
56
+
57
+ class FlaganizerException(Exception):
58
+ pass
59
+
60
+
61
+ class MissingTokenError(FlaganizerException):
62
+ def __init__(self, key: str):
63
+ super().__init__(f"This service does not have access to the token for {key}.")
64
+
65
+
66
+ def get_token(key: str) -> str:
67
+ try:
68
+ with open(f"/run/secrets/flaganizer/{key}/token") as f:
69
+ return f.read()
70
+ except FileNotFoundError as e:
71
+ raise MissingTokenError(key) from e
72
+
73
+
74
+ def get_flag(key: str, username: Optional[str] = None) -> str:
75
+ if username is None:
76
+ username = get_username()
77
+ if username is None:
78
+ raise ValueError("Must be running with a user or request.")
79
+
80
+ assert FLAGANIZER_HOST is not None, "flaganizer host missing"
81
+ r = requests.get(
82
+ f"http://{FLAGANIZER_HOST}/generate",
83
+ params={"username": username},
84
+ headers={
85
+ "Authorization": f"Bearer {get_token(key)}",
86
+ "User-Agent": "pyquocca",
87
+ },
88
+ )
89
+ if r.status_code == 200:
90
+ return r.json().get("flag")
91
+ else:
92
+ raise FlaganizerException(r.json().get("msg"))
@@ -0,0 +1,52 @@
1
+ from pythonjsonlogger.jsonlogger import JsonFormatter, merge_record_extra
2
+
3
+ bind = ["0.0.0.0:8000"]
4
+ forwarded_allow_ips = "*"
5
+ workers = 5
6
+
7
+ # Based on https://stackoverflow.com/a/70511781
8
+ class GunicornJsonFormatter(JsonFormatter):
9
+ def add_fields(self, log_record, record, message_dict):
10
+ """
11
+ This method allows us to inject gunicorn's args as fields for the formatter
12
+ """
13
+ super(GunicornJsonFormatter, self).add_fields(log_record, record, message_dict)
14
+ for field in self._required_fields:
15
+ if field in self.rename_fields:
16
+ log_record[self.rename_fields[field]] = record.args.get(field) # type: ignore
17
+ else:
18
+ log_record[field] = record.args.get(field) # type: ignore
19
+
20
+
21
+ logconfig_dict = {
22
+ "version": 1,
23
+ "formatters": {
24
+ "json": {
25
+ "()": "pyquocca.gunicorn.GunicornJsonFormatter",
26
+ "format": "%(M)s %(t)s %(r)s %(s)s %(p)s %(a)s %({host}i)s %({x-mtls-full-name}i)s %({x-forwarded-for}i)s %({x-mtls-username}i)s %({x-mtls-staff}i)s",
27
+ "datefmt": "%Y-%m-%dT%H:%M:%S%z",
28
+ "rename_fields": {
29
+ "M": "duration",
30
+ "a": "user_agent",
31
+ "t": "time",
32
+ "{host}i": "host",
33
+ "{x-forwarded-for}i": "ip",
34
+ "s": "status",
35
+ "r": "request",
36
+ "p": "process_id",
37
+ "{x-mtls-full-name}i": "full_name",
38
+ "{x-mtls-username}i": "user",
39
+ "{x-mtls-staff}i": "is_staff",
40
+ },
41
+ }
42
+ },
43
+ "handlers": {
44
+ "console": {
45
+ "class": "logging.StreamHandler",
46
+ "level": "INFO",
47
+ "formatter": "json",
48
+ "stream": "ext://sys.stdout",
49
+ }
50
+ },
51
+ "loggers": {"gunicorn.access": {"level": "INFO", "handlers": ["console"]}},
52
+ }
@@ -0,0 +1,70 @@
1
+ import os
2
+ from typing import Any, Literal, Optional
3
+
4
+ import requests
5
+ from typing_extensions import NotRequired, TypedDict
6
+
7
+ from . import get_username, is_staff
8
+
9
+ XSSBOT_HOST = os.getenv("XSSBOT_HOST")
10
+ XSSBOT_URL = f"http://{XSSBOT_HOST}"
11
+
12
+
13
+ class XSSBotException(Exception):
14
+ pass
15
+
16
+
17
+ class InvalidRequestError(XSSBotException):
18
+ def __init__(self, response: Any):
19
+ self.response = response
20
+ super().__init__(f"Invalid request sent to XSSBot.")
21
+
22
+
23
+ class Cookie(TypedDict):
24
+ name: str
25
+ value: str
26
+ domain: str
27
+ path: NotRequired[str]
28
+ sameSite: NotRequired[Literal["Strict", "Lax", "None"]]
29
+ httpOnly: NotRequired[bool]
30
+ secure: NotRequired[bool]
31
+
32
+
33
+ def visit(
34
+ url: str,
35
+ cookies: list[Cookie],
36
+ spoof_mtls=True,
37
+ timeout: Optional[int] = None,
38
+ network_timeout: Optional[int] = None,
39
+ ):
40
+ username = get_username()
41
+ if spoof_mtls and username is not None:
42
+ mtls_user = {"username": username, "isStaff": is_staff()}
43
+ else:
44
+ mtls_user = None
45
+
46
+ data = {"url": url, "cookies": cookies}
47
+
48
+ if timeout:
49
+ data["timeout"] = timeout
50
+
51
+ if network_timeout:
52
+ data["networkTimeout"] = network_timeout
53
+
54
+ if mtls_user:
55
+ data["mtlsUser"] = mtls_user
56
+
57
+ r = requests.post(
58
+ f"{XSSBOT_URL}/visit",
59
+ headers={
60
+ "User-Agent": "pyquocca",
61
+ },
62
+ json=data,
63
+ )
64
+
65
+ if r.status_code == 204:
66
+ return
67
+ elif r.status_code == 400:
68
+ raise InvalidRequestError(r.json())
69
+ else:
70
+ raise XSSBotException(r.content)