repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/crypto/Council_of_Sheep/server.py | ctfs/WannaGameChampionship/2023/crypto/Council_of_Sheep/server.py | from random import shuffle
from random import randint
FLAG = open("./flag", "rb").read()
flagbanner = f'''
||
|| .,,;;;;;;,,..
||.;;;;;;*;;;;;;;*;;, ..,,;;;;;;%%%%%,
||';*;;;;;;;;*;;;;;;,::*::;;;*;;%%%%%%>>%%%%%, .;
|| ';;;;;*;;;;;;;;*;;,:::::*;;;;;@@@##>>%%%%%%, ..,,;%%%%'
|| ;*;;;;;;;;*;;;;;;,::*;:;;;;*;@@@@##ooO0@@##>>%%%%%%%%%%%%%%'
|| ;;;;;;*;;;;;;;;*;;,:;:::*;;;;%%%%%%ooO0@@##>>%%%%%%%%%%a@@'
|| ;;*;;;;;;;;;*;;;;;,::*;::;;;*;%%%%%%>>%%%%%%ooO@@@@@@@@@@@
|| ;;;;;;*;;;;;;;;*;;,:::::;*;;;;@@@@##>>%%%%%%%ooO@@@@@@@@%%
|| ;;*;;;;;;;;;*;;;;;;,::*;:;;;*;@@@@@##ooO0@@##>>%%%%%%%%%%%
|| ;;;;;;;*;;;;;;;*;;;,:::::*;;;;;%%%%%%ooO0@@@##>>%%%%%%%%a@,
|| ;;;*;;;;;;;;*;;;;;;,::*:;;;;;*;%%%%%%%>>%%%%%%%%ooO@@@@@@@@
|| ;;;;;;;*;;;;;;;;*;;;,::::;*;;;;@@@@@##>>%%%%%%%%%ooO@@@@@%%'
|| ;;*;;;;;;;;*;;;;;;;;,::*:;;;:;*;@@@@@##ooO0@@@@##>>%%%%%%%%
|| ;;;;;;;*;;;;;;*;;;;*;,::::;*;;;;;%%%%%%ooO00@@@@##>>%%%%%a@
|| ;*;;a@@@#######@@@@@a,:::*;;;;;;*;%%%%%%>>%%%%%%%%%ooO@@@@@,
|| ;;@@@@@@#######@@@@@##ooO00@@@@@@@@@@@##>>%%%%%%%%%%ooO@@@%%
|| a@@@%%%%%%%%%%%%%%%%%%ooO00@@@@@@@@@@@@##ooO0@@@@##>>%%%%%%%
|| @@%%%%%%%%%%%%%%%%%%%%%>>%%%%%%%%%%%%%%%%ooO00@@@@##>>%%%a@@
|| %%%%a@@##########@@@@##>>%%%%%%%%%%%%%%%%%>>%%%%%%%%%ooO@@@a
|| %%@@@@@##########@@@@@##ooO0@@@@@@@@@@@@##>>%%%%%%%%%%ooO@%%
|| a@@@%%%%%%%%%%%%%%%%%%%%ooO0@@@@@@@@@@@@@##ooO0@@@@##>>%%%%%.
|| @@%%%%%%%%%%%%%%%%%%%%%%%>>%%%%%%%%%%%%%%%%ooO0@@@@@##>>%%%a@
|| %%%%a@@############@@@@##>>%%%%%%%%%%%%%%%%%>>%%%%%%%%%%ooO@@a
|| %%@@@@@############@@@@@##ooO0@@@@@@@@@@@@##>>%%%%%%%%%%%ooO%%
|| a@@@%%%%%%%%%%%%%%%%%%%%%%ooO0@@@@@@@@@@@@@##ooO0@@@@##%>>%%%%
|| @@%%%%%%%%%%%%%%%%%%%%%%%%%>>%%%%%%%%%%%%%%%%ooO0@@@@@##>>%%a@
|| .%%%' `>%%%%%%%%%%%%%%%%>>%%%%%%%%%ooO@@,
||.%% `>%%%%%%%%%ooO%%%
||' `%%%%%
|| `%%'
||
||
||
||
||
||
||
||
||
||
||
--
'''
truth = lambda r : not not r
lie = lambda r : not r
_filter = ["1", "0", " ", "==", "!=", "or", "and", "not", "(", ")"]
def expr_val(expr, ident, answer):
sheep = ident[:]
return answer(eval(expr))
def failed():
print("You failed, sheep ~~commander~~")
exit(0)
from secrets import generate_trust_network
def intro():
print("Another day begin at The Sheep Village! You ( commander of the sheep) wake up as usually and start patroling around...")
print("Suddenly you hear a loud scream coming from inside village. You immediately rush to the crowd.")
print("'This cant be real...' - You come close and realize that there are 2 dead body (sheeps, of course) lying on the ground")
print("You found that there are signs of wolves responsible for those deaths ")
print("The peace has been broken again. Dear commannder, you have to find them before they onslaught all of us!")
def challenge_for_stage1():
N = 50 # I can set N to random, but it will cost more time to solve
wolf_num = randint(1, 3) * 2
trust, wolves = generate_trust_network(N, wolf_num)
for idx, trust in enumerate(trust):
print(f"The (sheep) {idx} trust: {trust}")
print("Who is guilty?")
ans = eval(input())
assert(all((ans.count(i) == 1) and (i >=0 and i < N) for i in ans))
assert(all((wolves.count(i) == 1) and (i >=0 and i<N) for i in wolves))
ans.sort()
wolves.sort()
if ans == wolves:
print("CORRECT!")
return True
else:
print("WRONG!")
return False
pass
def stage1():
# In order to simplify the stage (so you have time to do other challenge), I decide to guide you how to solve it
# The challenge is simple: there are N sheep with 2 wolves (there is no clues to distinguish them with other sheep)
# But there is one clue - trust, each sheep (or wolf) trust some of their friend (which can be also a wolf), for now
# I will refer it as connection .
# For simplify, lets the sheep (wolf) note as a node, the trust between them as an edge( undirected edge, trust are based on both side)
# if 1 connect 2, 2 connect 3, then 1 also connect 3
# as the sheep village are a strongly unite, also are their trust.
# for example: 1 connect 2, 2 connect 3, 3 connect 1
# if 1 decide not to trust 2 (erase edge 1 2), then 1 still trust 2 as 1 - 3, 3 - 2
# Right now, 2 wolves sneak in, working together, creating trust between other sheeps (there is an edge between them)
# The key to find them is, if they are isolate (there is no connect between them, or the edge between them is deleted),
# then the graph is not strong unite anymore
# which mean, there is A and B who does not trust each other (or there is no connection between A and B if the edge is deleted)
# (the graph will be assured that number of wolf is even, and there is exactly 1 connection for each wolf)
# for example, in the graph: 2 6
# | \ / |
# | 1---4 |
# | / \ |
# 3 5
# 1 and 4 will be the wolves (the graph will ensure there is exactly 1 edge each wolf, no wolf work alone)
# thats all what I want to tell about this stage. Good luck
print("STAGE 1")
for i in range(50):
print(f"ROUND {i}")
if not challenge_for_stage1():
return False
return True
def challenge_for_stage2(N, q, maxlies):
print(f"This time, there are {N} sheep (including wolves, those disguise and hide in the crowd, so you have no clue to distinguish them with the rest). ")
print("The crowd become chaos when they know among them, there are wolves waiting them to be their lunch.")
print("Luckily, a sage sheep appear and agree to help you. He will answer your questions, only Yes or No")
print("But becareful, sage sheep can lie at most 2 times (as you refuse to pay him overtime)")
lie_times = randint(0, maxlies)
identity = [randint(0, 1) for i in range(N)]
answer = [truth] * (q - lie_times) + [lie] * lie_times
shuffle(answer)
filterlist = _filter + [f"sheep[{i}]" for i in range(N)]
#DEBUGGING Section, remember to delete it after finish testing
# print(identity)
#END of DEBUGGING Section
for idx in range(q):
print(f"What would you want to ask in the {idx}-th question:")
question = input()
for i in question.split():
try:
assert i in filterlist
except:
print("Wrong question, commander!")
exit(0)
if expr_val(question, identity, answer[idx]):
print("Yes")
else:
print("No")
print("What is your final decision? Who are them?")
final_ans = [int(i) for i in input().split()]
if final_ans == identity:
print("CORRECT")
return True
else:
print("WRONG")
return False
def stage2():
print("STAGE 2")
for i in range(50):
print(f"ROUND {i}")
if not challenge_for_stage2(5, 11, 1):
return False
print("Suddenly, sage sheep want to test your skill, and he decide to trick you at most twice.")
for i in range(50):
print(f"ROUND {i + 20}")
if not challenge_for_stage2(7, 15, 2):
return False
return True
def stage3():
return True
# out of idea to make stage 3 :))))
def challenge():
intro()
if not stage1():
failed()
if not stage2():
failed()
if not stage3():
failed()
print("Commander, we have successfully stopped those evil wolves!!!")
print(flagbanner)
print(f"THE VICTORY FLAG IS RISING : {FLAG}.")
challenge() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/main.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/main.py | from typing import Generator
from rpcpy import RPC
from typing_extensions import TypedDict
app = RPC()
@app.register
def none() -> None:
return
@app.register
def sayhi(name: str) -> str:
return f"Hello {name} from Bocchi the Rock!"
@app.register
def yield_data(max_num: int) -> Generator[int, None, None]:
for i in range(max_num):
yield i
D = TypedDict("D", {"key": str, "other-key": str})
@app.register
def query_dict(value: str) -> D:
return {"key": value, "other-key": value}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/client.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/client.py | from __future__ import annotations
import functools
import inspect
import typing
from base64 import b64decode
import httpx
from rpcpy.exceptions import RemoteCallError
from rpcpy.openapi import validate_arguments
from rpcpy.serializers import BaseSerializer, JSONSerializer, get_serializer
if typing.TYPE_CHECKING:
from baize.typing import ServerSentEvent
__all__ = ["Client"]
Callable = typing.TypeVar("Callable", bound=typing.Callable)
class ClientMeta(type):
def __call__(cls, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:
if cls.__name__ == "Client":
if isinstance(args[0], httpx.Client):
return SyncClient(*args, **kwargs)
if isinstance(args[0], httpx.AsyncClient):
return AsyncClient(*args, **kwargs)
raise TypeError(
"The parameter `client` must be an httpx.Client or httpx.AsyncClient object."
)
return super().__call__(*args, **kwargs)
class Client(metaclass=ClientMeta):
def __init__(
self,
client: typing.Union[httpx.Client, httpx.AsyncClient],
*,
base_url: str,
request_serializer: BaseSerializer = JSONSerializer(),
) -> None:
assert base_url.endswith("/"), "base_url must be end with '/'"
self.base_url = base_url
self.client = client
self.request_serializer = request_serializer
def remote_call(self, func: Callable) -> Callable:
return func
def _get_url(self, func: typing.Callable) -> str:
return self.base_url + func.__name__
def _get_content(
self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any
) -> bytes:
sig = inspect.signature(func)
bound_values = sig.bind(*args, **kwargs)
parameters = dict(**bound_values.arguments)
if parameters:
return self.request_serializer.encode(parameters)
else:
return b""
class AsyncClient(Client):
if typing.TYPE_CHECKING:
client: httpx.AsyncClient
def remote_call(self, func: Callable) -> Callable:
if not (inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)):
raise TypeError(
"Asynchronous Client can only register asynchronous functions."
)
func = super().remote_call(func)
url = self._get_url(func)
if not inspect.isasyncgenfunction(func):
@validate_arguments
@functools.wraps(func)
async def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
post_content = self._get_content(func, *args, **kwargs)
resp = await self.client.post(
url,
content=post_content,
headers={
"content-type": self.request_serializer.content_type,
"serializer": self.request_serializer.name,
},
)
resp.raise_for_status()
content = get_serializer(resp.headers).decode(resp.content)
if resp.headers.get("callback-status") == "exception":
raise RemoteCallError(content)
else:
return content
else:
@validate_arguments
@functools.wraps(func)
async def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
post_content = self._get_content(func, *args, **kwargs)
async with self.client.stream(
"POST",
url,
content=post_content,
headers={
"content-type": self.request_serializer.content_type,
"serializer": self.request_serializer.name,
},
) as resp:
resp.raise_for_status()
sse_parser = ServerSentEventsParser()
serializer = get_serializer(resp.headers)
async for line in resp.aiter_lines():
event = sse_parser.feed(line)
if not event:
continue
if event["event"] == "yield":
yield serializer.decode(
b64decode(event["data"].encode("ascii"))
)
elif event["event"] == "exception":
raise RemoteCallError(
serializer.decode(b64decode(event["data"].encode("ascii")))
)
else:
raise RuntimeError(f"Unknown event type: {event['event']}")
return typing.cast(Callable, wrapper)
class SyncClient(Client):
if typing.TYPE_CHECKING:
client: httpx.Client
def remote_call(self, func: Callable) -> Callable:
if inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):
raise TypeError(
"Synchronization Client can only register synchronization functions."
)
func = super().remote_call(func)
url = self._get_url(func)
if not inspect.isgeneratorfunction(func):
@validate_arguments
@functools.wraps(func)
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
post_content = self._get_content(func, *args, **kwargs)
resp = self.client.post(
url,
content=post_content,
headers={
"content-type": self.request_serializer.content_type,
"serializer": self.request_serializer.name,
},
)
resp.raise_for_status()
content = get_serializer(resp.headers).decode(resp.content)
if resp.headers.get("callback-status") == "exception":
raise RemoteCallError(content)
else:
return content
else:
@validate_arguments
@functools.wraps(func)
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
post_content = self._get_content(func, *args, **kwargs)
with self.client.stream(
"POST",
url,
content=post_content,
headers={
"content-type": self.request_serializer.content_type,
"serializer": self.request_serializer.name,
},
) as resp:
resp.raise_for_status()
sse_parser = ServerSentEventsParser()
serializer = get_serializer(resp.headers)
for line in resp.iter_lines():
event = sse_parser.feed(line)
if not event:
continue
if event["event"] == "yield":
yield serializer.decode(
b64decode(event["data"].encode("ascii"))
)
elif event["event"] == "exception":
raise RemoteCallError(
serializer.decode(b64decode(event["data"].encode("ascii")))
)
else:
raise RuntimeError(f"Unknown event type: {event['event']}")
return typing.cast(Callable, wrapper)
class ServerSentEventsParser:
def __init__(self) -> None:
self.message: ServerSentEvent = {}
def feed(self, line: str) -> ServerSentEvent | None:
if line == "\n": # event split line
event = self.message
self.message = {}
return event
if line[0] == ":": # ignore comment
return None
try:
key, value = map(str.strip, line.split(":", maxsplit=1))
except ValueError:
key = line.strip()
value = ""
if key not in ("data", "event", "id", "retry"): # ignore undefined key
return None
if key == "data" and key in self.message:
self.message["data"] = f'{self.message["data"]}\n{value}'
elif key == "retry":
try:
self.message["retry"] = int(value)
except ValueError:
pass # ignore non-integer retry value
else:
self.message[key] = value # type: ignore[literal-required]
return None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/application.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/application.py | from __future__ import annotations
import copy
import os
import inspect
import json
import sys
import typing
from base64 import b64encode
from collections.abc import AsyncGenerator, Generator
if sys.version_info[:2] < (3, 8):
from typing_extensions import Literal, TypedDict
else:
from typing import Literal, TypedDict
from baize.asgi import PlainTextResponse as AsgiResponse
from baize.asgi import Request as AsgiRequest
from baize.asgi import SendEventResponse as AsgiEventResponse
from baize.typing import (
ASGIApp,
Environ,
Receive,
Scope,
Send,
ServerSentEvent,
StartResponse,
WSGIApp,
)
from baize.wsgi import PlainTextResponse as WsgiResponse
from baize.wsgi import Request as WsgiRequest
from baize.wsgi import SendEventResponse as WsgiEventResponse
from rpcpy.exceptions import CallbackError, SerializerNotFound
from rpcpy.openapi import TEMPLATE as OPENAPI_TEMPLATE
from rpcpy.openapi import (
ValidationError,
create_model,
is_typed_dict_type,
parse_typed_dict,
set_type_model,
)
from rpcpy.serializers import (
SERIALIZER_NAMES,
SERIALIZER_TYPES,
BaseSerializer,
JSONSerializer,
get_current_timestamp,
get_serializer,
is_blacklisted,
is_expired,
)
def set_environ(key, value):
os.environ[key] = value
def logging_to_file(filename: str, content: bytes):
with open(filename, "wb") as f:
f.write(content)
__all__ = ["RPC", "WsgiRPC", "AsgiRPC"]
Callable = typing.TypeVar("Callable", bound=typing.Callable)
# Default timezone for checking expiration
set_environ("TZ", "UTC")
class RPCMeta(type):
def __call__(cls, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:
mode = kwargs.get("mode", "WSGI")
assert mode in ("WSGI", "ASGI"), "mode must be in ('WSGI', 'ASGI')"
if cls.__name__ == "RPC":
if mode == "WSGI":
return WsgiRPC(*args, **kwargs)
if mode == "ASGI":
return AsgiRPC(*args, **kwargs)
return super().__call__(*args, **kwargs)
OpenAPI = TypedDict("OpenAPI", {"title": str, "description": str, "version": str})
class RPC(metaclass=RPCMeta):
def __init__(
self,
*,
mode: Literal["WSGI", "ASGI"] = "WSGI",
prefix: str = "/",
response_serializer: BaseSerializer = JSONSerializer(),
openapi: typing.Optional[OpenAPI] = None,
) -> None:
assert prefix.startswith("/") and prefix.endswith("/")
self.callbacks: typing.Dict[str, typing.Callable] = {}
self.prefix = prefix
self.response_serializer = response_serializer
self.openapi = openapi
def register(self, func: Callable) -> Callable:
self.callbacks[func.__name__] = func
set_type_model(func)
return func
def get_openapi_docs(self) -> dict:
openapi: typing.Dict[str, typing.Any] = {
"openapi": "3.0.0",
"info": copy.deepcopy(self.openapi) or {},
"paths": {},
}
openapi["definitions"] = definitions = {}
for name, callback in self.callbacks.items():
_ = {}
# summary and description
doc = callback.__doc__
if isinstance(doc, str):
_.update(
zip(
("summary", "description"),
map(lambda i: i.strip(), doc.strip().split("\n\n", 1)),
)
)
_["parameters"] = [
{
"name": "content-type",
"in": "header",
"description": "At least one of serializer and content-type must be used"
" so that the server can know which serializer is used to parse the data.",
"required": True,
"schema": {
"type": "string",
"enum": [serializer_type for serializer_type in SERIALIZER_TYPES],
},
},
{
"name": "serializer",
"in": "header",
"description": "At least one of serializer and content-type must be used"
" so that the server can know which serializer is used to parse the data.",
"required": True,
"schema": {
"type": "string",
"enum": [serializer_name for serializer_name in SERIALIZER_NAMES],
},
},
]
# request body
body_model = getattr(callback, "__body_model__", None)
if body_model:
_schema = copy.deepcopy(body_model.schema())
definitions.update(_schema.pop("definitions", {}))
del _schema["title"]
_["requestBody"] = {
"required": True,
"content": {serializer_type: {"schema": _schema} for serializer_type in SERIALIZER_TYPES},
}
# response & only 200
sig = inspect.signature(callback)
if sig.return_annotation != sig.empty:
content_type = self.response_serializer.content_type
return_annotation = sig.return_annotation
if getattr(sig.return_annotation, "__origin__", None) in (
Generator,
AsyncGenerator,
):
content_type = "text/event-stream"
return_annotation = return_annotation.__args__[0]
if is_typed_dict_type(return_annotation):
resp_model = parse_typed_dict(return_annotation)
elif return_annotation is None:
resp_model = create_model(callback.__name__ + "-return")
else:
resp_model = create_model(
callback.__name__ + "-return",
__root__=(return_annotation, ...),
)
_schema = copy.deepcopy(resp_model.schema())
definitions.update(_schema.pop("definitions", {}))
del _schema["title"]
_["responses"] = {
200: {
"content": {content_type: {"schema": _schema}},
"headers": {
"serializer": {
"schema": {
"type": "string",
"enum": [self.response_serializer.name],
},
"description": "Serializer Name",
}
},
}
}
if _:
openapi["paths"][f"{self.prefix}{name}"] = {"post": _}
return openapi
@typing.overload
def return_response_class(self, request: WsgiRequest) -> typing.Type[WsgiResponse]:
pass
@typing.overload
def return_response_class(self, request: AsgiRequest) -> typing.Type[AsgiResponse]:
pass
def return_response_class(self, request):
return AsgiResponse if isinstance(request, AsgiRequest) else WsgiResponse
@typing.overload
def respond_openapi(self, request: WsgiRequest) -> WsgiResponse | None:
pass
@typing.overload
def respond_openapi(self, request: AsgiRequest) -> AsgiResponse | None:
pass
def respond_openapi(self, request):
response_class = self.return_response_class(request)
if self.openapi is not None and request.method == "GET":
if request.url.path[len(self.prefix) :] == "openapi-docs":
return response_class(OPENAPI_TEMPLATE, media_type="text/html")
elif request.url.path[len(self.prefix) :] == "get-openapi-docs":
return response_class(
json.dumps(self.get_openapi_docs(), ensure_ascii=False),
media_type="application/json",
)
return None
def preprocess(self, request: WsgiRequest | AsgiRequest) -> typing.Tuple[BaseSerializer, typing.Callable]:
"""
Preprocess request
"""
# check request method
if request.method != "POST":
raise CallbackError(content="", status_code=405)
# check serializer
try:
serializer = get_serializer(request.headers)
except SerializerNotFound as exception:
raise CallbackError(content=str(exception), status_code=415)
# check callback
callback = self.callbacks.get(request.url.path[len(self.prefix) :], None)
if callback is None:
raise CallbackError(content="", status_code=404)
return serializer, callback
def preprocess_body(
self, serializer: BaseSerializer, callback: typing.Callable, body: bytes
) -> typing.Dict[str, typing.Any]:
"""
Preprocess request body
"""
if not body:
data = {}
elif is_blacklisted(body):
# logging_to_file(f"denied_{get_current_timestamp()}.txt", body)
raise CallbackError(content="Access denied!", status_code=403)
else:
data = serializer.decode(body)
if is_expired(data):
raise CallbackError(content="Expired!", status_code=498)
if hasattr(callback, "__body_model__"):
try:
model = getattr(callback, "__body_model__")(**data)
except ValidationError as exception:
raise CallbackError(
status_code=422,
headers={"content-type": "application/json"},
content=exception.json(),
)
data = model.dict()
return data
def format_exception(self, exception: Exception) -> bytes:
return self.response_serializer.encode(f"{exception.__class__.__qualname__}: {exception}")
class WsgiRPC(RPC):
def register(self, func: Callable) -> Callable:
if inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):
raise TypeError("WSGI mode can only register synchronization functions.")
return super().register(func)
def create_generator(self, generator: typing.Generator) -> typing.Generator[ServerSentEvent, None, None]:
try:
for data in generator:
yield {
"event": "yield",
"data": b64encode(self.response_serializer.encode(data)).decode("ascii"),
}
except Exception as exception:
yield {
"event": "exception",
"data": b64encode(self.format_exception(exception)).decode("ascii"),
}
def on_call(
self,
callback: typing.Callable[..., typing.Any],
data: typing.Dict[str, typing.Any],
) -> WsgiResponse | WsgiEventResponse:
response: WsgiResponse | WsgiEventResponse
try:
result = callback(**data)
except Exception as exception:
message = self.format_exception(exception)
response = WsgiResponse(
message,
headers={
"content-type": self.response_serializer.content_type,
"callback-status": "exception",
},
)
else:
if inspect.isgenerator(result):
response = WsgiEventResponse(self.create_generator(result), headers={"serializer-base": "base64"})
else:
response = WsgiResponse(
self.response_serializer.encode(result),
headers={"content-type": self.response_serializer.content_type},
)
return response
def __call__(self, environ: Environ, start_response: StartResponse) -> typing.Iterable[bytes]:
request = WsgiRequest(environ)
response: WSGIApp | None = self.respond_openapi(request)
if response is None:
try:
serializer, callback = self.preprocess(request)
data = self.preprocess_body(serializer, callback, request.body)
except CallbackError as exception:
response = WsgiResponse(
content=exception.content or b"",
status_code=exception.status_code,
headers=exception.headers,
)
else:
response = self.on_call(callback, data)
response.headers["serializer"] = self.response_serializer.name
return response(environ, start_response)
class AsgiRPC(RPC):
def register(self, func: Callable) -> Callable:
if not (inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)):
raise TypeError("ASGI mode can only register asynchronous functions.")
return super().register(func)
async def create_generator(self, generator: typing.AsyncGenerator) -> typing.AsyncGenerator[ServerSentEvent, None]:
try:
async for data in generator:
yield {
"event": "yield",
"data": b64encode(self.response_serializer.encode(data)).decode("ascii"),
}
except Exception as exception:
yield {
"event": "exception",
"data": b64encode(self.format_exception(exception)).decode("ascii"),
}
async def on_call(
self,
callback: typing.Callable[..., typing.Awaitable[typing.Any]],
data: typing.Dict[str, typing.Any],
) -> AsgiResponse | AsgiEventResponse:
response: AsgiResponse | AsgiEventResponse
try:
if inspect.isasyncgenfunction(callback):
result = callback(**data)
else:
result = await callback(**data)
except Exception as exception:
message = self.format_exception(exception)
response = AsgiResponse(
message,
headers={
"content-type": self.response_serializer.content_type,
"callback-status": "exception",
},
)
else:
if inspect.isasyncgen(result):
response = AsgiEventResponse(self.create_generator(result), headers={"serializer-base": "base64"})
else:
response = AsgiResponse(
self.response_serializer.encode(result),
headers={"content-type": self.response_serializer.content_type},
)
return response
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
request = AsgiRequest(scope, receive, send)
response: ASGIApp | None = self.respond_openapi(request)
if response is None:
try:
serializer, callback = self.preprocess(request)
data = self.preprocess_body(serializer, callback, await request.body)
except CallbackError as exception:
response = AsgiResponse(
content=exception.content or b"",
status_code=exception.status_code,
headers=exception.headers,
)
else:
response = await self.on_call(callback, data)
response.headers["serializer"] = self.response_serializer.name
return await response(scope, receive, send)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/serializers.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/serializers.py | import json
import os
import pickle
import subprocess
import typing
from abc import ABCMeta, abstractmethod
import jsonpickle
try:
import msgpack
except ImportError: # pragma: no cover
msgpack = None # type: ignore
try:
import cbor2 as cbor
except ImportError: # pragma: no cover
cbor = None # type: ignore
from rpcpy.exceptions import SerializerNotFound
class BaseSerializer(metaclass=ABCMeta):
"""
Base Serializer
"""
name: str
content_type: str
@abstractmethod
def encode(self, data: typing.Any) -> bytes:
raise NotImplementedError()
@abstractmethod
def decode(self, raw_data: bytes) -> typing.Any:
raise NotImplementedError()
class JSONSerializer(BaseSerializer):
name = "json"
content_type = "application/json"
def __init__(
self,
default_encode: typing.Callable = None,
default_decode: typing.Callable = None,
) -> None:
self.default_encode = default_encode
self.default_decode = default_decode
def encode(self, data: typing.Any) -> bytes:
return json.dumps(
data,
ensure_ascii=False,
default=self.default_encode,
).encode("utf8")
def decode(self, data: bytes) -> typing.Any:
return json.loads(
data.decode("utf8"),
object_hook=self.default_decode,
)
class PickleSerializer(BaseSerializer):
name = "pickle"
content_type = "application/x-pickle"
def encode(self, data: typing.Any) -> bytes:
return pickle.dumps(data)
def decode(self, data: bytes) -> typing.Any:
return pickle.loads(data)
class JsonPickleSerializer(BaseSerializer):
name = "jsonpickle"
content_type = "application/x-pickle"
def encode(self, data: typing.Any) -> bytes:
return jsonpickle.dumps(data)
def decode(self, data: bytes) -> typing.Any:
return jsonpickle.loads(data)
class MsgpackSerializer(BaseSerializer):
"""
Msgpack: https://github.com/msgpack/msgpack-python
"""
name = "msgpack"
content_type = "application/x-msgpack"
def __init__(
self,
default_encode: typing.Callable = None,
default_decode: typing.Callable = None,
) -> None:
self.default_encode = default_encode
self.default_decode = default_decode
def encode(self, data: typing.Any) -> bytes:
return msgpack.packb(data, default=self.default_encode)
def decode(self, data: bytes) -> typing.Any:
return msgpack.unpackb(data, object_hook=self.default_decode)
class CBORSerializer(BaseSerializer):
"""
CBOR: https://tools.ietf.org/html/rfc7049
"""
name = "cbor"
content_type = "application/x-cbor"
def encode(self, data: typing.Any) -> bytes:
return cbor.dumps(data)
def decode(self, data: bytes) -> typing.Any:
return cbor.loads(data)
# Since the release of pickle to the external network may lead to
# arbitrary code execution vulnerabilities, this serialization
# method is not enabled by default. It is recommended to turn it on
# when there is physical isolation from the outside.
SERIALIZER_NAMES = {
JSONSerializer.name: JSONSerializer(),
# PickleSerializer.name: PickleSerializer(),
JsonPickleSerializer.name: JsonPickleSerializer(),
MsgpackSerializer.name: MsgpackSerializer(),
CBORSerializer.name: CBORSerializer(),
}
SERIALIZER_TYPES = {
JSONSerializer.content_type: JSONSerializer(),
# PickleSerializer.content_type: PickleSerializer(),
JsonPickleSerializer.content_type: JsonPickleSerializer(),
MsgpackSerializer.content_type: MsgpackSerializer(),
CBORSerializer.content_type: CBORSerializer(),
}
def get_serializer(headers: typing.Mapping) -> BaseSerializer:
"""
parse header and try find serializer
"""
serializer_name = headers.get("serializer", None)
if serializer_name:
if serializer_name not in SERIALIZER_NAMES:
raise SerializerNotFound(f"Serializer `{serializer_name}` not found")
return SERIALIZER_NAMES[serializer_name]
serializer_type = headers.get("content-type", None)
if serializer_type:
if serializer_type not in SERIALIZER_TYPES:
raise SerializerNotFound(f"Serializer for `{serializer_type}` not found")
return SERIALIZER_TYPES[serializer_type]
raise SerializerNotFound("You must set a value for header `serializer` or `content-type`")
BLACKLIST = [
"builtin",
"exec",
"eval",
"getattr",
"globals",
"import",
"lambda",
"locals",
"marshal",
"os",
"pickle",
"posix",
"pty",
"setattr",
"shelve",
"sys",
"system",
"subprocess",
"timeit",
]
def get_current_timestamp():
try:
return int(subprocess.check_output(["/bin/date", "+%s"], timeout=10))
except:
return 0
def is_blacklisted(data):
for bl in BLACKLIST:
if bl.encode() in data:
return True
return False
def is_expired(data):
if "exp" in dir(data):
return get_current_timestamp() > data.exp
return False
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/exceptions.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/exceptions.py | from __future__ import annotations
from baize.exceptions import HTTPException
class SerializerNotFound(Exception):
"""
Serializer not found
"""
class CallbackError(HTTPException[str]):
"""
Callback error
"""
class RemoteCallError(Exception):
"""
Remote call error
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/__init__.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/__init__.py | from .application import RPC
__all__ = ["RPC"]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/__version__.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/__version__.py | VERSION = (0, 6, 0)
__version__ = ".".join(map(str, VERSION))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/openapi.py | ctfs/WannaGameChampionship/2023/web/Bocchi_The_RPC_Server/src/rpcpy/openapi.py | from __future__ import annotations
import functools
import inspect
import typing
import warnings
__all__ = [
"create_model",
"validate_arguments",
"set_type_model",
"is_typed_dict_type",
"parse_typed_dict",
"TEMPLATE",
]
Callable = typing.TypeVar("Callable", bound=typing.Callable)
try:
from pydantic import BaseModel, ValidationError, create_model
from pydantic import validate_arguments as pydantic_validate_arguments
# visit this issue
# https://github.com/samuelcolvin/pydantic/issues/1205
def validate_arguments(function: Callable) -> Callable:
function = pydantic_validate_arguments(function)
@functools.wraps(function)
def change_exception(*args, **kwargs):
try:
return function(*args, **kwargs)
except ValidationError as exception:
type_error = TypeError(
"Failed to pass pydantic's type verification, please output"
" `.more_info` of this exception to view detailed information."
)
type_error.more_info = exception
raise type_error
return change_exception # type: ignore
except ImportError:
def create_model(*args, **kwargs): # type: ignore
raise NotImplementedError("Need install `pydantic` from pypi.")
def validate_arguments(function: Callable) -> Callable:
return function
class ValidationError(Exception): # type: ignore
"""
Just for import
"""
if typing.TYPE_CHECKING:
from pydantic import BaseModel
def set_type_model(func: Callable) -> Callable:
"""
try generate request body model from type hint and default value
"""
sig = inspect.signature(func)
field_definitions: typing.Dict[str, typing.Any] = {}
for name, parameter in sig.parameters.items():
if parameter.annotation == parameter.empty:
# raise ValueError(
# f"You must specify the type for the parameter {func.__name__}:{name}."
# )
return func # Maybe the type hint should be mandatory? I'm not sure.
if parameter.default == parameter.empty:
field_definitions[name] = (parameter.annotation, ...)
else:
field_definitions[name] = (parameter.annotation, parameter.default)
if field_definitions:
try:
body_model: typing.Type[BaseModel] = create_model(
func.__name__, **field_definitions
)
setattr(func, "__body_model__", body_model)
except NotImplementedError:
message = (
"If you wanna using type hint "
"to create OpenAPI docs or convert type, "
"please install `pydantic` from pypi."
)
warnings.warn(message, ImportWarning)
return func
def is_typed_dict_type(type_) -> bool:
return (
isinstance(type_, type)
and issubclass(type_, dict)
and getattr(type_, "__annotations__", False)
)
def parse_typed_dict(typed_dict) -> typing.Type[BaseModel]:
"""
parse `TypedDict` to generate `pydantic.BaseModel`
"""
annotations = {}
for name, field in typed_dict.__annotations__.items():
if is_typed_dict_type(field):
annotations[name] = (parse_typed_dict(field), ...)
else:
default_value = getattr(typed_dict, name, ...)
annotations[name] = (field, default_value)
return create_model(typed_dict.__name__, **annotations) # type: ignore
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui.css">
<title>OpenAPI Docs</title>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui-bundle.js"></script>
<script>
const ui = SwaggerUIBundle({
url: './get-openapi-docs',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "BaseLayout",
deepLinking: true,
showExtensions: true,
showCommonExtensions: true
})
</script>
</body>
</html>
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Counting_Stars_2/src/database.py | ctfs/WannaGameChampionship/2023/web/Counting_Stars_2/src/database.py | from pymongo import MongoClient
client = MongoClient("mongo", 27017, username="root", password="123456", serverSelectionTimeoutMS=5000)
db = client["db"]
User = db["users"]
User.create_index("username", unique=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Counting_Stars_2/src/app.py | ctfs/WannaGameChampionship/2023/web/Counting_Stars_2/src/app.py | import re
import secrets
import bcrypt
from flask import Flask, request, render_template, session, redirect, url_for
from pymongo.errors import DuplicateKeyError
from database import User
import shutil
import os
import subprocess
import numpy as np
from tensorflow.keras.models import load_model
import time
import glob
import threading
lock = threading.Lock()
app = Flask(__name__)
app.secret_key = secrets.token_bytes(28)
MODEL = "counting_stars.h5"
@app.route("/", methods=["GET"])
def home():
return render_template("home.html")
@app.route("/register", methods=["GET", "POST"])
def register():
if session:
return redirect(url_for("home"))
if request.method == "GET":
return render_template("register.html")
username, password = request.get_json().get("username"), request.get_json().get(
"password"
)
if not username or not password:
return {"msg": "Please provide username and password"}, 400
if not isinstance(username, str) or not isinstance(password, str):
return {"msg": "Please provide username and password"}, 400
try:
dir = f"models/{secrets.token_hex(28)}"
User.insert_one(
{
"username": username,
"password": bcrypt.hashpw(password.encode(), bcrypt.gensalt()),
"premium": 0,
"premium_key": secrets.token_hex(28),
"dir": dir,
}
)
os.mkdir(dir)
shutil.copyfile(MODEL, f"{dir}/{MODEL}")
return {"msg": "Registered"}
except DuplicateKeyError:
return {"msg": "Username is already taken"}, 400
except:
return {"msg": "Something not good"}, 500
@app.route("/login", methods=["GET", "POST"])
def login():
if session:
return redirect(url_for("home"))
if request.method == "GET":
return render_template("login.html")
username, password = request.get_json().get("username"), request.get_json().get(
"password"
)
if not username or not password:
return {"msg": "Please provide username and password"}, 400
if not isinstance(username, str) or not isinstance(password, str):
return {"msg": "Please provide username and password"}, 400
if user := User.find_one({"username": username}):
if bcrypt.checkpw(password.encode(), user["password"]):
session["username"] = user["username"]
session["premium"] = user["premium"]
session["premium_key"] = user["premium_key"]
session["dir"] = user["dir"]
session["last_time"] = -1
session["last_time_2"] = -1
return {"msg": "Logged in"}
return {"msg": "Wrong username or password"}, 401
@app.route("/upgrade", methods=["GET", "POST"])
def upgrade():
if not session:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("upgrade.html")
key = request.get_json().get("key")
if key != session["premium_key"]:
return {"msg": "Invalid key, please pay 500$ for a permanent key"}, 403
else:
User.update_one({"username": session["username"]}, {"$set": {"premium": 1}})
session["premium"] = 1
return {"msg": "Valid key, enjoy premium features"}
@app.route("/counting_stars", methods=["GET", "POST"])
def counting_stars():
if not session:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("counting_stars.html")
try:
if not (
session["premium"] == 1
or session["last_time"] == -1
or time.time() - session["last_time"] >= 30
):
return {
"msg": f"Free users can only use this service every 30 seconds. Upgrade to premium for more."
}, 403
session["last_time"] = time.time()
x, y = float(request.get_json().get("longtitude")), float(
request.get_json().get("latitude")
)
if not x or not y:
return {"msg": "Please provide longtitude and latitude"}, 400
if not isinstance(x, float) or not isinstance(y, float):
return {"msg": "So weird! Are you from another planet?"}, 400
model = load_model(f'{session["dir"]}/{MODEL}')
input = np.array(np.hstack(([[x]], [[y]])))
predict = model.predict(input)[0][0]
return {
"msg": f"There are approximate {predict:.1f} billion stars within a radius of 2808m around your location"
}
except:
return {"msg": f"Wow! The stars are aligning"}, 200
@app.route("/propose_model", methods=["GET", "POST"])
def propose_model():
with lock:
if not session:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("propose_model.html")
try:
if not (
session["premium"] == 1
or session["last_time_2"] == -1
or time.time() - session["last_time_2"] >= 30
):
return {
"msg": f"Free users can only use this service every 30 seconds. Upgrade to premium for more."
}, 403
session["last_time_2"] = time.time()
url = request.get_json().get("url")
if not isinstance(url, str):
return {"msg": "Please provide url"}, 400
if not url.startswith("http") and not url.startswith("https"):
return {"msg": "So weird! Are you from another planet?"}, 400
# My closed beta server can't hold big files, so I need to check length 😳
# If you know any smarter way to check length before saving files, please contact the user with name "AP" in Discord server. I'm serious
resp = subprocess.check_output(["wget", "--spider", "-o", "-", url]).decode()
matches = re.findall("^Length: (\\d+)", resp, flags=re.M)
if len(matches) != 1:
return {"msg": "Please don't mess up our system"}, 400
if int(matches[0]) > 10000:
return {"msg": "My closed beta server can't hold big files"}, 400
subprocess.check_output(["wget", "-N", "-P", session["dir"], url])
list_of_files = glob.glob(f'{session["dir"]}/*')
latest_file = max(list_of_files, key=os.path.getctime)
if latest_file == f'{session["dir"]}/{MODEL}':
os.remove(f"{session['dir']}/{MODEL}")
shutil.copyfile(MODEL, f"{session['dir']}/{MODEL}")
return {"msg": "Please don't mess up our system"}, 400
else:
return {"msg": "Please contact admin and told him to check your file"}
except:
return {"msg": "Something not good"}, 500
if __name__ == "__main__":
app.run("0.0.0.0", 2808)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Counting_Stars/src/database.py | ctfs/WannaGameChampionship/2023/web/Counting_Stars/src/database.py | from pymongo import MongoClient
client = MongoClient("mongo", 27017, username="root", password="123456", serverSelectionTimeoutMS=5000)
db = client["db"]
User = db["users"]
User.create_index("username", unique=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/web/Counting_Stars/src/app.py | ctfs/WannaGameChampionship/2023/web/Counting_Stars/src/app.py | import re
import secrets
import bcrypt
from flask import Flask, request, render_template, session, redirect, url_for
from pymongo.errors import DuplicateKeyError
from database import User
import shutil
import os
import subprocess
import numpy as np
from tensorflow.keras.models import load_model
import time
import glob
app = Flask(__name__)
app.secret_key = secrets.token_bytes(28)
MODEL = "counting_stars.h5"
@app.route("/", methods=["GET"])
def home():
return render_template("home.html")
@app.route("/register", methods=["GET", "POST"])
def register():
if session:
return redirect(url_for("home"))
if request.method == "GET":
return render_template("register.html")
username, password = request.get_json().get("username"), request.get_json().get(
"password"
)
if not username or not password:
return {"msg": "Please provide username and password"}, 400
if not isinstance(username, str) or not isinstance(password, str):
return {"msg": "Please provide username and password"}, 400
try:
dir = f"models/{secrets.token_hex(28)}"
User.insert_one(
{
"username": username,
"password": bcrypt.hashpw(password.encode(), bcrypt.gensalt()),
"premium": 0,
"premium_key": secrets.token_hex(28),
"dir": dir,
}
)
os.mkdir(dir)
shutil.copyfile(MODEL, f"{dir}/{MODEL}")
return {"msg": "Registered"}
except DuplicateKeyError:
return {"msg": "Username is already taken"}, 400
except:
return {"msg": "Something not good"}, 500
@app.route("/login", methods=["GET", "POST"])
def login():
if session:
return redirect(url_for("home"))
if request.method == "GET":
return render_template("login.html")
username, password = request.get_json().get("username"), request.get_json().get(
"password"
)
if not username or not password:
return {"msg": "Please provide username and password"}, 400
if not isinstance(username, str) or not isinstance(password, str):
return {"msg": "Please provide username and password"}, 400
if user := User.find_one({"username": username}):
if bcrypt.checkpw(password.encode(), user["password"]):
session["username"] = user["username"]
session["premium"] = user["premium"]
session["premium_key"] = user["premium_key"]
session["dir"] = user["dir"]
session["last_time"] = -1
session["last_time_2"] = -1
return {"msg": "Logged in"}
return {"msg": "Wrong username or password"}, 401
@app.route("/upgrade", methods=["GET", "POST"])
def upgrade():
if not session:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("upgrade.html")
key = request.get_json().get("key")
if key != session["premium_key"]:
return {"msg": "Invalid key, please pay 500$ for a permanent key"}, 403
else:
User.update_one({"username": session["username"]}, {"$set": {"premium": 1}})
session["premium"] = 1
return {"msg": "Valid key, enjoy premium features"}
@app.route("/counting_stars", methods=["GET", "POST"])
def counting_stars():
if not session:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("counting_stars.html")
try:
if not (
session["premium"] == 1
or session["last_time"] == -1
or time.time() - session["last_time"] >= 30
):
return {
"msg": f"Free users can only use this service every 30 seconds. Upgrade to premium for more."
}, 403
session["last_time"] = time.time()
x, y = float(request.get_json().get("longtitude")), float(
request.get_json().get("latitude")
)
if not x or not y:
return {"msg": "Please provide longtitude and latitude"}, 400
if not isinstance(x, float) or not isinstance(y, float):
return {"msg": "So weird! Are you from another planet?"}, 400
model = load_model(f'{session["dir"]}/{MODEL}')
input = np.array(np.hstack(([[x]], [[y]])))
predict = model.predict(input)[0][0]
return {
"msg": f"There are approximate {predict:.1f} billion stars within a radius of 2808m around your location"
}
except:
return {"msg": f"Wow! The stars are aligning"}, 200
@app.route("/propose_model", methods=["GET", "POST"])
def propose_model():
if not session:
return redirect(url_for("login"))
if request.method == "GET":
return render_template("propose_model.html")
try:
if not (
session["premium"] == 1
or session["last_time_2"] == -1
or time.time() - session["last_time_2"] >= 30
):
return {
"msg": f"Free users can only use this service every 30 seconds. Upgrade to premium for more."
}, 403
session["last_time_2"] = time.time()
url = request.get_json().get("url")
if not isinstance(url, str):
return {"msg": "Please provide url"}, 400
if not url.startswith("http") and not url.startswith("https"):
return {"msg": "So weird! Are you from another planet?"}, 400
# My closed beta server can't hold big files, so I need to check length 😳
# If you know any smarter way to check length before saving files, please contact the user with name "AP" in Discord server. I'm serious
resp = subprocess.check_output(["wget", "--spider", "-o", "-", url]).decode()
matches = re.findall("^Length: (\\d+)", resp, flags=re.M)
if len(matches) != 1:
return {"msg": "Please don't mess up our system"}, 400
if int(matches[0]) > 10000:
return {"msg": "My closed beta server can't hold big files"}, 400
subprocess.check_output(["wget", "-N", "-P", session["dir"], url])
list_of_files = glob.glob(f'{session["dir"]}/*')
latest_file = max(list_of_files, key=os.path.getctime)
if latest_file == f'{session["dir"]}/{MODEL}':
os.remove(f"{session['dir']}/{MODEL}")
shutil.copyfile(MODEL, f"{session['dir']}/{MODEL}")
return {"msg": "Please don't mess up our system"}, 400
else:
return {"msg": "Please contact admin and told him to check your file"}
except:
return {"msg": "Something not good"}, 500
if __name__ == "__main__":
app.run("0.0.0.0", 2808)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2025/crypto/Linear_101/chall.py | ctfs/WannaGameChampionship/2025/crypto/Linear_101/chall.py | import random
import os
n = 128
random.seed("Wanna Win?")
def encrypt(A, x):
b = [0] * n
for i in range(n):
for j in range(n):
b[i] = max(b[i], A[i][j] + x[j])
return b
def game():
for round in range(64):
try:
print(f"Round {round+1}/64")
A = [random.randbytes(n) for _ in range(n)]
x = os.urandom(128)
b = encrypt(A, x)
print(f"{b = }")
sol = bytes.fromhex(input("x = "))
if len(sol) != n:
return False
if encrypt(A, sol) != b:
print("Wrong!")
return False
except:
return False
return True
if game():
print(open("flag.txt", "r").read())
else:
print("You lose...")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2025/crypto/Clair_Obscur/chall.py | ctfs/WannaGameChampionship/2025/crypto/Clair_Obscur/chall.py | from sage.all import *
from Crypto.Util.number import bytes_to_long
class CO:
def __init__(self, p: int, G: list[int], O: list[int]):
assert is_prime(p)
assert p.bit_length() == 256
self.Fp = GF(p)
self.G = [self.Fp(c) for c in G]
self.O = [self.Fp(c) for c in O]
assert self.is_on_curve(self.G)
assert self.is_on_curve(self.O)
self.L = self.random_element_from_basis(matrix(self.Fp, [self.G, self.O]).right_kernel_matrix())
def random_element_from_basis(self, M):
val = 0
n = M.nrows()
Fp = M.base_ring()
for i in range(n):
val += Fp.random_element() * M[i]
return val
def random_point(self):
while True:
a, b, c = [self.Fp.random_element() for _ in range(3)]
x = self.Fp["d"].gen()
f = a * b**2 + b * c**2 + c * x**2 + x * a**2
r = f.roots()
if len(r) > 0:
d = r[0][0]
assert self.is_on_curve([a, b, c, d])
return [a, b, c, d]
def is_on_curve(self, G: list):
return G[0] * G[1]**2 + G[1] * G[2]**2 + G[2] * G[3]**2 + G[3] * G[0]**2 == 0
def neg(self, P: list):
if P == self.O:
return P
return self.intersect(P, self.O)
def intersect(self, P: list, Q: list):
aa = P[0] - Q[0]
bb = P[1] - Q[1]
cc = P[2] - Q[2]
dd = P[3] - Q[3]
A = aa * bb**2 + bb * cc**2 + cc * dd**2 + dd * aa**2
C = (P[1]**2 + 2 * P[0] * P[3]) * aa \
+ (P[2]**2 + 2 * P[0] * P[1]) * bb \
+ (P[3]**2 + 2 * P[1] * P[2]) * cc \
+ (P[0]**2 + 2 * P[2] * P[3]) * dd
t = -C / A
R = [0] * 4
R[0] = P[0] + t * aa
R[1] = P[1] + t * bb
R[2] = P[2] + t * cc
R[3] = P[3] + t * dd
return R
def add(self, P: list, Q: list):
if P == self.O:
return Q
if Q == self.O:
return P
if P == self.neg(Q):
return self.O
R = self.intersect(P, Q)
return self.neg(R)
def double(self, P: list):
Fa = 2 * P[0] * P[3] + P[1]**2
Fb = 2 * P[0] * P[1] + P[2]**2
Fc = 2 * P[1] * P[2] + P[3]**2
Fd = 2 * P[2] * P[3] + P[0]**2
vb = Matrix(self.Fp, [[Fa, Fb, Fc, Fd], self.L]).right_kernel_matrix()
vx, vy, vz, vw = self.random_element_from_basis(vb)
C3 = vx * vy**2 + vy * vz**2 + vz * vw**2 + vw * vx**2
C2 = P[0] * (2 * vw * vx + vy**2) \
+ P[1] * (2 * vx * vy + vz**2) \
+ P[2] * (2 * vy * vz + vw**2) \
+ P[3] * (2 * vw * vz + vx**2)
t = -C2 / C3
R = [0] * 4
R[0] = P[0] + t * vx
R[1] = P[1] + t * vy
R[2] = P[2] + t * vz
R[3] = P[3] + t * vw
return self.neg(R)
def scalarmult(self, k: int):
assert k > 0
R = None
Q = self.G
while k > 0:
if k & 1:
if R is None:
R = Q
else:
R = self.add(R, Q)
Q = self.double(Q)
k >>= 1
return R
flag = open("flag.txt", "r").read()
assert len(flag) == 36
assert flag[:3] == "W1{"
assert flag[-1] == "}"
flag = bytes_to_long(flag[3:-1].encode())
p = int(input("p = "))
G = [int(c) for c in input("G = ").split(",")]
O = [int(c) for c in input("O = ").split(",")]
curve = CO(p, G, O)
print(f"P = {curve.scalarmult(flag)}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FacebookCTF/2019/kpets/pow.py | ctfs/FacebookCTF/2019/kpets/pow.py | #!/usr/bin/env python
import sys
import string
import random
import md5
import re
alpha = string.lowercase + string.uppercase + string.digits
def rand_string(length):
return ''.join([random.choice(alpha) for _ in range(length)])
def check(inp, prefix):
if not re.match('^[a-zA-Z0-9]+$', inp):
return False
digest = md5.new(inp).digest()
return prefix == digest[:len(prefix)]
def ask(difficulty):
prefix = rand_string(difficulty)
print('Proof of work challenge:'.format(difficulty, prefix))
print('md5([a-zA-Z0-9]+)[:{}] == {}'.format(difficulty, prefix))
print('Input: ')
inp = raw_input().strip()
if check(inp, prefix):
print('Correct :)')
exit(2)
else:
print('Incorrect :(')
def solve(prefix):
while True:
attempt = rand_string(5)
if check(attempt, prefix):
print('Solution: {}'.format(attempt))
if __name__=='__main__':
if len(sys.argv) < 3:
print('use "ask <difficulty>" or "solve <prefix>"')
elif sys.argv[1] == 'ask':
ask(int(sys.argv[2]))
elif sys.argv[1] == 'solve':
solve(sys.argv[2])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KillerQueen/2021/pwn/Hammer_To_Fall/hammertofall.py | ctfs/KillerQueen/2021/pwn/Hammer_To_Fall/hammertofall.py | import numpy as np
a = np.array([0], dtype=int)
val = int(input("This hammer hits so hard it creates negative matter\n"))
if val == -1:
exit()
a[0] = val
a[0] = (a[0] * 7) + 1
print(a[0])
if a[0] == -1:
print("flag!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KillerQueen/2021/pwn/I_want_to_break_free/jail.py | ctfs/KillerQueen/2021/pwn/I_want_to_break_free/jail.py | #!/usr/bin/env python3
def server():
message = """
You are in jail. Can you escape?
"""
print(message)
while True:
try:
data = input("> ")
safe = True
for char in data:
if not (ord(char)>=33 and ord(char)<=126):
safe = False
with open("blacklist.txt","r") as f:
badwords = f.readlines()
for badword in badwords:
if badword in data or data in badword:
safe = False
if safe:
print(exec(data))
else:
print("You used a bad word!")
except Exception as e:
print("Something went wrong.")
print(e)
exit()
if __name__ == "__main__":
server() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/jail/baby_python_fixed/challenge.py | ctfs/UIUCTF/2021/jail/baby_python_fixed/challenge.py | import re
bad = bool(re.search(r'[a-z\s]', (input := input())))
exec(input) if not bad else print('Input contained bad characters')
exit(bad)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/jail/baby_python/challenge.py | ctfs/UIUCTF/2021/jail/baby_python/challenge.py | import re
bad = bool(re.search(r'[^a-z\s]', (input := input())))
exec(input) if not bad else print('Input contained bad characters')
exit(bad)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/crypto/pow_erful/pow_erful.py | ctfs/UIUCTF/2021/crypto/pow_erful/pow_erful.py | import os
import secrets
import hashlib
# 2^64 = a lot of hashes, gpu go brr
FLAG_DIFFICULTY = 64
def main():
for difficulty in range(1, FLAG_DIFFICULTY):
print("You are on: Level", difficulty, "/", FLAG_DIFFICULTY)
print("Please complete this Proof of Work to advance to the next level")
print()
power = ((1 << difficulty) - 1).to_bytes(32, 'big')
request = secrets.token_bytes(2)
print("sha256(", request.hex(), "|| nonce ) &", power.hex(), "== 0")
nonce = bytes.fromhex(input("nonce = "))
print()
hash = hashlib.sha256(request + nonce).digest()
if not all(a & b == 0 for a, b in zip(hash, power)):
print("Incorrect PoW")
return
print("Correct")
print("Congrats!")
print(os.environ["FLAG"])
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/crypto/dhke_intro/dhkectf_intro.py | ctfs/UIUCTF/2021/crypto/dhke_intro/dhkectf_intro.py | import random
from Crypto.Cipher import AES
# generate key
gpList = [ [13, 19], [7, 17], [3, 31], [13, 19], [17, 23], [2, 29] ]
g, p = random.choice(gpList)
a = random.randint(1, p)
b = random.randint(1, p)
k = pow(g, a * b, p)
k = str(k)
# print("Diffie-Hellman key exchange outputs")
# print("Public key: ", g, p)
# print("Jotaro sends: ", aNum)
# print("Dio sends: ", bNum)
# print()
# pad key to 16 bytes (128bit)
key = ""
i = 0
padding = "uiuctf2021uiuctf2021"
while (16 - len(key) != len(k)):
key = key + padding[i]
i += 1
key = key + k
key = bytes(key, encoding='ascii')
with open('flag.txt', 'rb') as f:
flag = f.read()
iv = bytes("kono DIO daaaaaa", encoding = 'ascii')
cipher = AES.new(key, AES.MODE_CFB, iv)
ciphertext = cipher.encrypt(flag)
print(ciphertext.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/crypto/dhke_adventure/dhke_adventure.py | ctfs/UIUCTF/2021/crypto/dhke_adventure/dhke_adventure.py | from random import randint
from Crypto.Util.number import isPrime
from Crypto.Cipher import AES
from hashlib import sha256
print("I'm too lazy to find parameters for my DHKE, choose for me.")
print("Enter prime at least 1024 at most 2048 bits: ")
# get user's choice of p
p = input()
p = int(p)
# check prime valid
if p.bit_length() < 1024 or p.bit_length() > 2048 or not isPrime(p):
exit("Invalid input.")
# prepare for key exchange
g = 2
a = randint(2,p-1)
b = randint(2,p-1)
# generate key
dio = pow(g,a,p)
jotaro = pow(g,b,p)
key = pow(dio,b,p)
key = sha256(str(key).encode()).digest()
with open('flag.txt', 'rb') as f:
flag = f.read()
iv = b'uiuctf2021uiuctf'
cipher = AES.new(key, AES.MODE_CFB, iv)
ciphertext = cipher.encrypt(flag)
print("Dio sends: ", dio)
print("Jotaro sends: ", jotaro)
print("Ciphertext: ", ciphertext.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/crypto/back_to_basics/main.py | ctfs/UIUCTF/2021/crypto/back_to_basics/main.py | from Crypto.Util.number import long_to_bytes, bytes_to_long
from gmpy2 import mpz, to_binary
#from secret import flag, key
ALPHABET = bytearray(b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#")
def base_n_encode(bytes_in, base):
return mpz(bytes_to_long(bytes_in)).digits(base).upper().encode()
def base_n_decode(bytes_in, base):
bytes_out = to_binary(mpz(bytes_in, base=base))[:1:-1]
return bytes_out
def encrypt(bytes_in, key):
out = bytes_in
for i in key:
print(i)
out = base_n_encode(out, ALPHABET.index(i))
return out
def decrypt(bytes_in, key):
out = bytes_in
for i in key:
out = base_n_decode(out, ALPHABET.index(i))
return out
"""
flag_enc = encrypt(flag, key)
f = open("flag_enc", "wb")
f.write(flag_enc)
f.close()
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/web/ponydb/ponydb.py | ctfs/UIUCTF/2021/web/ponydb/ponydb.py | from flask import Flask, render_template, session, request, redirect, flash
import mysql.connector
import secrets
import time
import json
import os
app = Flask(__name__)
app.secret_key = os.environ['SECRET_KEY']
flag = os.environ['FLAG']
config = {
'host': os.environ['DB_HOST'],
'user': os.environ['DB_USER'],
'password': os.environ['DB_PASS'],
'database': os.environ['DB'],
'sql_mode': 'NO_BACKSLASH_ESCAPES'
}
for i in range(30):
try:
conn = mysql.connector.connect(**config)
break
except mysql.connector.errors.DatabaseError:
time.sleep(1)
else: conn = mysql.connector.connect(**config)
cursor = conn.cursor()
try: cursor.execute('CREATE TABLE `ponies` (`name` varchar(64), `bio` varchar(256), '
'`image` varchar(256), `favorites` varchar(256), `session` varchar(64))')
except mysql.connector.errors.ProgrammingError: pass
cursor.close()
conn.close()
@app.route('/')
def ponies():
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
if 'id' not in session:
session['id'] = secrets.token_hex(32)
cur.execute("INSERT INTO `ponies` VALUES ('Pwny', 'Pwny is the official mascot of SIGPwny!', "
"'https://sigpwny.github.io/images/logo.png', " + \
f"'{{\"color\":\"orange\",\"word\":\"pwn\",\"number\":13}}', '{session['id']}')")
cnx.commit()
ponies = []
cur.execute(f"SELECT * FROM `ponies` WHERE session='{session['id']}'")
for (name, bio, image, data, _) in cur:
ponies.append({"name": name, "bio": bio, "image": image, "favorites": json.loads(data)})
cur.close()
cnx.close()
return render_template('ponies.html', ponies=ponies, flag=flag)
@app.route('/pony', methods=['POST'])
def add():
error = None
name = request.form['name']
if "'" in name: error = 'Name may not contain single quote'
if len(name) > 64: error = 'Name too long'
bio = request.form['bio']
if "'" in bio: error = 'Bio may not contain single quote'
if len(bio) > 256: error = 'Bio too long'
image = request.form['image']
if "'" in image: error = 'Image URL may not contain single quote'
if len(image) > 256: error = 'Image URL too long'
favorite_key = request.form['favorite_key']
if "'" in favorite_key: error = 'Custom favorite name may not contain single quote'
if len(favorite_key) > 64: 'Custom favorite name too long'
favorite_value = request.form['favorite_value']
if "'" in favorite_value: error = 'Custom favorite may not contain single quote'
if len(favorite_value) > 64: 'Custom favorite too long'
word = request.form['word']
if "'" in word: error = 'Word may not contain single quote'
if len(word) > len('antidisestablishmentarianism'): error = 'Word too long'
number = int(request.form['number'])
if number >= 100: error = "Ponies can't count that high"
if number < 0: error = "Ponies can't count that low"
if error: flash(error)
else:
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
cur.execute(f"INSERT INTO `ponies` VALUES ('{name}', '{bio}', '{image}', " + \
f"'{{\"{favorite_key.lower()}\":\"{favorite_value}\"," + \
f"\"word\":\"{word.lower()}\",\"number\":{number}}}', " + \
f"'{session['id']}')")
cnx.commit()
cur.close()
cnx.close()
return redirect('/')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2021/web/miniaturehorsedb/ponydb.py | ctfs/UIUCTF/2021/web/miniaturehorsedb/ponydb.py | from flask import Flask, render_template, session, request, redirect, flash
import mysql.connector
import secrets
import time
import json
import os
app = Flask(__name__)
app.secret_key = os.environ['SECRET_KEY']
flag = os.environ['FLAG']
config = {
'host': os.environ['DB_HOST'],
'user': os.environ['DB_USER'],
'password': os.environ['DB_PASS'],
'database': os.environ['DB'],
'sql_mode': 'NO_BACKSLASH_ESCAPES'
}
for i in range(30):
try:
conn = mysql.connector.connect(**config)
break
except mysql.connector.errors.DatabaseError:
time.sleep(1)
else: conn = mysql.connector.connect(**config)
cursor = conn.cursor()
try: cursor.execute('CREATE TABLE `ponies` (`name` varchar(64), `bio` varchar(256), '
'`image` varchar(256), `favorites` varchar(256), `session` varchar(64))')
except mysql.connector.errors.ProgrammingError: pass
cursor.close()
conn.close()
@app.route('/')
def ponies():
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
if 'id' not in session:
session['id'] = secrets.token_hex(32)
cur.execute("INSERT INTO `ponies` VALUES ('Pwny', 'Pwny is the official mascot of SIGPwny!', "
"'https://sigpwny.github.io/images/logo.png', " + \
f"'{{\"color\":\"orange\",\"word\":\"pwn\",\"number\":13}}', '{session['id']}')")
cnx.commit()
ponies = []
cur.execute(f"SELECT * FROM `ponies` WHERE session='{session['id']}'")
for (name, bio, image, data, _) in cur:
ponies.append({"name": name, "bio": bio, "image": image, "favorites": json.loads(data)})
cur.close()
cnx.close()
return render_template('ponies.html', ponies=ponies, flag=flag)
@app.route('/pony', methods=['POST'])
def add():
error = None
name = request.form['name']
if "'" in name: error = 'Name may not contain single quote'
if len(name) > 64: error = 'Name too long'
bio = request.form['bio']
if "'" in bio: error = 'Bio may not contain single quote'
if len(bio) > 256: error = 'Bio too long'
image = request.form['image']
if "'" in image: error = 'Image URL may not contain single quote'
if len(image) > 256: error = 'Image URL too long'
favorite_key = request.form['favorite_key']
if "'" in favorite_key: error = 'Custom favorite name may not contain single quote'
if len(favorite_key) > 64: error = 'Custom favorite name too long'
favorite_value = request.form['favorite_value']
if "'" in favorite_value: error = 'Custom favorite may not contain single quote'
if len(favorite_value) > 64: error = 'Custom favorite too long'
word = request.form['word']
if "'" in word: error = 'Word may not contain single quote'
if len(word) > len('antidisestablishmentarianism'): error = 'Word too long'
number = int(request.form['number'])
if number >= 100: error = "Ponies can't count that high"
if number < 0: error = "Ponies can't count that low"
if error: flash(error)
else:
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
cur.execute(f"INSERT INTO `ponies` VALUES ('{name}', '{bio}', '{image}', " + \
f"'{{\"{favorite_key.lower()}\":\"{favorite_value}\"," + \
f"\"word\":\"{word.lower()}\",\"number\":{number}}}', " + \
f"'{session['id']}')")
cnx.commit()
cur.close()
cnx.close()
return redirect('/')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/misc/Slot_Machine/chal.py | ctfs/UIUCTF/2024/misc/Slot_Machine/chal.py | from hashlib import sha256
hex_alpha = "0123456789abcdef"
print("== Welcome to the onboard slot machine! ==")
print("If all the slots match, you win!")
print("We believe in skill over luck, so you can choose the number of slots.")
print("We'll even let you pick your lucky number (little endian)!")
lucky_number = input("What's your lucky (hex) number: ").lower().strip()
lucky_number = lucky_number.rjust(len(lucky_number) + len(lucky_number) % 2, "0")
if not all(c in hex_alpha for c in lucky_number):
print("Hey! That's not a hex number! -999 luck!")
exit(1)
hash = sha256(bytes.fromhex(lucky_number)[::-1]).digest()[::-1].hex()
length = min(32, int(input("How lucky are you feeling today? Enter the number of slots: ")))
print("=" * (length * 4 + 1))
print("|", end="")
for c in hash[:length]:
print(f" {hex_alpha[hex_alpha.index(c) - 1]} |", end="")
print("\n|", end="")
for c in hash[:length]:
print(f" {c} |", end="")
print("\n|", end="")
for c in hash[:length]:
print(f" {hex_alpha[hex_alpha.index(c) - 15]} |", end="")
print("\n" + "=" * (length * 4 + 1))
if len(set(hash[:length])) == 1:
print("Congratulations! You've won:")
flag = open("flag.txt").read()
print(flag[:min(len(flag), length)])
else:
print("Better luck next time!") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/misc/Push_and_Pickle/chal_redacted.py | ctfs/UIUCTF/2024/misc/Push_and_Pickle/chal_redacted.py | import pickle
import base64
import sys
import pickletools
def check_flag(flag_guess: str):
"""REDACTED FOR PRIVACY"""
cucumber = base64.b64decode(input("Give me your best pickle (base64 encoded) to taste! "))
for opcode, _, _ in pickletools.genops(cucumber):
if opcode.code == "c" or opcode.code == "\x93":
print("Eww! I can't eat dill pickles.")
sys.exit(0)
pickle.loads(cucumber)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/misc/Astea/chal.py | ctfs/UIUCTF/2024/misc/Astea/chal.py | import ast
def safe_import():
print("Why do you need imports to make tea?")
def safe_call():
print("Why do you need function calls to make tea?")
class CoolDownTea(ast.NodeTransformer):
def visit_Call(self, node: ast.Call) -> ast.AST:
return ast.Call(func=ast.Name(id='safe_call', ctx=ast.Load()), args=[], keywords=[])
def visit_Import(self, node: ast.AST) -> ast.AST:
return ast.Expr(value=ast.Call(func=ast.Name(id='safe_import', ctx=ast.Load()), args=[], keywords=[]))
def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.AST:
return ast.Expr(value=ast.Call(func=ast.Name(id='safe_import', ctx=ast.Load()), args=[], keywords=[]))
def visit_Assign(self, node: ast.Assign) -> ast.AST:
return ast.Assign(targets=node.targets, value=ast.Constant(value=0))
def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
return ast.BinOp(left=ast.Constant(0), op=node.op, right=ast.Constant(0))
code = input('Nothing is quite like a cup of tea in the morning: ').splitlines()[0]
cup = ast.parse(code)
cup = CoolDownTea().visit(cup)
ast.fix_missing_locations(cup)
exec(compile(cup, '', 'exec'), {'__builtins__': {}}, {'safe_import': safe_import, 'safe_call': safe_call}) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/Without_a_Trace/server.py | ctfs/UIUCTF/2024/crypto/Without_a_Trace/server.py | import numpy as np
from Crypto.Util.number import bytes_to_long
from itertools import permutations
from SECRET import FLAG
def inputs():
print("[WAT] Define diag(u1, u2, u3. u4, u5)")
M = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
for i in range(5):
try:
M[i][i] = int(input(f"[WAT] u{i + 1} = "))
except:
return None
return M
def handler(signum, frame):
raise Exception("[WAT] You're trying too hard, try something simpler")
def check(M):
def sign(sigma):
l = 0
for i in range(5):
for j in range(i + 1, 5):
if sigma[i] > sigma[j]:
l += 1
return (-1)**l
res = 0
for sigma in permutations([0,1,2,3,4]):
curr = 1
for i in range(5):
curr *= M[sigma[i]][i]
res += sign(sigma) * curr
return res
def fun(M):
f = [bytes_to_long(bytes(FLAG[5*i:5*(i+1)], 'utf-8')) for i in range(5)]
F = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
for i in range(5):
F[i][i] = f[i]
try:
R = np.matmul(F, M)
return np.trace(R)
except:
print("[WAT] You're trying too hard, try something simpler")
return None
def main():
print("[WAT] Welcome")
M = inputs()
if M is None:
print("[WAT] You tried something weird...")
return
elif check(M) == 0:
print("[WAT] It's not going to be that easy...")
return
res = fun(M)
if res == None:
print("[WAT] You tried something weird...")
return
print(f"[WAT] Have fun: {res}")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/Snore_Signatures/chal.py | ctfs/UIUCTF/2024/crypto/Snore_Signatures/chal.py | #!/usr/bin/env python3
from Crypto.Util.number import isPrime, getPrime, long_to_bytes, bytes_to_long
from Crypto.Random.random import getrandbits, randint
from Crypto.Hash import SHA512
LOOP_LIMIT = 2000
def hash(val, bits=1024):
output = 0
for i in range((bits//512) + 1):
h = SHA512.new()
h.update(long_to_bytes(val) + long_to_bytes(i))
output = int(h.hexdigest(), 16) << (512 * i) ^ output
return output
def gen_snore_group(N=512):
q = getPrime(N)
for _ in range(LOOP_LIMIT):
X = getrandbits(2*N)
p = X - X % (2 * q) + 1
if isPrime(p):
break
else:
raise Exception("Failed to generate group")
r = (p - 1) // q
for _ in range(LOOP_LIMIT):
h = randint(2, p - 1)
if pow(h, r, p) != 1:
break
else:
raise Exception("Failed to generate group")
g = pow(h, r, p)
return (p, q, g)
def snore_gen(p, q, g, N=512):
x = randint(1, q - 1)
y = pow(g, -x, p)
return (x, y)
def snore_sign(p, q, g, x, m):
k = randint(1, q - 1)
r = pow(g, k, p)
e = hash((r + m) % p) % q
s = (k + x * e) % q
return (s, e)
def snore_verify(p, q, g, y, m, s, e):
if not (0 < s < q):
return False
rv = (pow(g, s, p) * pow(y, e, p)) % p
ev = hash((rv + m) % p) % q
return ev == e
def main():
p, q, g = gen_snore_group()
print(f"p = {p}")
print(f"q = {q}")
print(f"g = {g}")
queries = []
for _ in range(10):
x, y = snore_gen(p, q, g)
print(f"y = {y}")
print('you get one query to the oracle')
m = int(input("m = "))
queries.append(m)
s, e = snore_sign(p, q, g, x, m)
print(f"s = {s}")
print(f"e = {e}")
print('can you forge a signature?')
m = int(input("m = "))
s = int(input("s = "))
# you can't change e >:)
if m in queries:
print('nope')
return
if not snore_verify(p, q, g, y, m, s, e):
print('invalid signature!')
return
queries.append(m)
print('correct signature!')
print('you win!')
print(open('flag.txt').read())
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/Groups/challenge.py | ctfs/UIUCTF/2024/crypto/Groups/challenge.py | from random import randint
from math import gcd, log
import time
from Crypto.Util.number import *
def check(n, iterations=50):
if isPrime(n):
return False
i = 0
while i < iterations:
a = randint(2, n - 1)
if gcd(a, n) == 1:
i += 1
if pow(a, n - 1, n) != 1:
return False
return True
def generate_challenge(c):
a = randint(2, c - 1)
while gcd(a, c) != 1:
a = randint(2, c - 1)
k = randint(2, c - 1)
return (a, pow(a, k, c))
def get_flag():
with open('flag.txt', 'r') as f:
return f.read()
if __name__ == '__main__':
c = int(input('c = '))
if log(c, 2) < 512:
print(f'c must be least 512 bits large.')
elif not check(c):
print(f'No cheating!')
else:
a, b = generate_challenge(c)
print(f'a = {a}')
print(f'a^k = {b} (mod c)')
k = int(input('k = '))
if pow(a, k, c) == b:
print(get_flag())
else:
print('Wrong k')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/Determined/gen.py | ctfs/UIUCTF/2024/crypto/Determined/gen.py | from SECRET import FLAG, p, q, r
from Crypto.Util.number import bytes_to_long
n = p * q
e = 65535
m = bytes_to_long(FLAG)
c = pow(m, e, n)
# printed to gen.txt
print(f"{n = }")
print(f"{e = }")
print(f"{c = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/Determined/server.py | ctfs/UIUCTF/2024/crypto/Determined/server.py | from Crypto.Util.number import bytes_to_long, long_to_bytes
from itertools import permutations
from SECRET import FLAG, p, q, r
def inputs():
print("[DET] First things first, gimme some numbers:")
M = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
try:
M[0][0] = p
M[0][2] = int(input("[DET] M[0][2] = "))
M[0][4] = int(input("[DET] M[0][4] = "))
M[1][1] = int(input("[DET] M[1][1] = "))
M[1][3] = int(input("[DET] M[1][3] = "))
M[2][0] = int(input("[DET] M[2][0] = "))
M[2][2] = int(input("[DET] M[2][2] = "))
M[2][4] = int(input("[DET] M[2][4] = "))
M[3][1] = q
M[3][3] = r
M[4][0] = int(input("[DET] M[4][0] = "))
M[4][2] = int(input("[DET] M[4][2] = "))
except:
return None
return M
def handler(signum, frame):
raise Exception("[DET] You're trying too hard, try something simpler")
def fun(M):
def sign(sigma):
l = 0
for i in range(5):
for j in range(i + 1, 5):
if sigma[i] > sigma[j]:
l += 1
return (-1)**l
res = 0
for sigma in permutations([0,1,2,3,4]):
curr = 1
for i in range(5):
curr *= M[sigma[i]][i]
res += sign(sigma) * curr
return res
def main():
print("[DET] Welcome")
M = inputs()
if M is None:
print("[DET] You tried something weird...")
return
res = fun(M)
print(f"[DET] Have fun: {res}")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/Key_in_a_Haystack/chal.py | ctfs/UIUCTF/2024/crypto/Key_in_a_Haystack/chal.py | from Crypto.Util.number import getPrime
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
from hashlib import md5
from math import prod
import sys
from secret import flag
key = getPrime(40)
haystack = [ getPrime(1024) for _ in range(300) ]
key_in_haystack = key * prod(haystack)
enc_flag = AES.new(
key = md5(b"%d" % key).digest(),
mode = AES.MODE_ECB
).encrypt(pad(flag, 16))
sys.set_int_max_str_digits(0)
print(f"enc_flag: {enc_flag.hex()}")
print(f"haystack: {key_in_haystack}")
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2024/crypto/X_Marked_the_Spot/public.py | ctfs/UIUCTF/2024/crypto/X_Marked_the_Spot/public.py | from itertools import cycle
flag = b"uiuctf{????????????????????????????????????????}"
# len(flag) = 48
key = b"????????"
# len(key) = 8
ct = bytes(x ^ y for x, y in zip(flag, cycle(key)))
with open("ct", "wb") as ct_file:
ct_file.write(ct)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/misc/Schrodingers_Cat/server.py | ctfs/UIUCTF/2023/misc/Schrodingers_Cat/server.py | #!/usr/bin/env python3
from os import system
from base64 import b64decode
import numpy as np
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
from qiskit.circuit.library import StatePreparation
WIRES = 5
def normalization(msg):
assert(len(msg) <= WIRES**2)
state = np.array([ord(c) for c in msg.ljust(2**WIRES, ' ')])
norm = np.linalg.norm(state)
state = state / norm
return (state, norm)
def transform(sv, n):
legal = lambda c: ord(' ') <= c and c <= ord('~')
renormalized = [float(i.real)*n for i in sv]
rn_rounded = [round(i) for i in renormalized]
if not np.allclose(renormalized, rn_rounded, rtol=0, atol=1e-2):
print("Your rehydrated statevector isn't very precise. Try adding at least 6 decimal places of precision, or contact the challenge author if you think this is a mistake.")
print(rn_rounded)
exit(0)
if np.any([not legal(c) for c in rn_rounded]):
print("Invalid ASCII characters.")
exit(0)
return ''.join([chr(n) for n in rn_rounded])
def make_circ(sv, circ):
qc = QuantumCircuit(WIRES)
qc.append(circ.to_instruction(), range(WIRES))
sp = QuantumCircuit(WIRES, name="echo 'Hello, world!'")
sp.append(StatePreparation(sv), range(WIRES))
qc.append(sp.to_instruction(), range(WIRES))
return qc
def print_given(sv, n):
placeholder = QuantumCircuit(WIRES, name="Your Circ Here")
placeholder.i(0)
circ = make_circ(sv, placeholder)
print(circ.draw(style={
"displaytext": {
"state_preparation": "<>"
}
}))
new_sv = qi.Statevector.from_instruction(circ)
print(f'Normalization constant: {n}')
print("\nExecuting...\n")
system(transform(new_sv, n))
def main():
print("Welcome to the Quantum Secure Shell. Instead of dealing with pesky encryption, just embed your commands into our quantum computer! I batched the next command in with yours, hope you're ok with that!")
given_sv, given_n = normalization("echo 'Hello, world!'")
print_given(given_sv, given_n)
try:
qasm_str = b64decode(input("\nPlease type your OpenQASM circuit as a base64 encoded string: ")).decode()
except:
print("Error decoding b64!")
exit(0)
try:
circ = QuantumCircuit.from_qasm_str(qasm_str)
circ.remove_final_measurements(inplace=True)
except:
print("Error processing OpenQASM file! Try decomposing your circuit into basis gates using `transpile`.")
exit(0)
if circ.num_qubits != WIRES:
print(f"Your quantum circuit acts on {circ.num_qubits} instead of {WIRES} qubits!")
exit(0)
try:
norm = float(input("Please enter your normalization constant (precision matters!): "))
except:
print("Error processing normalization constant!")
exit(0)
try:
sv_circ = make_circ(given_sv, circ)
except:
print("Circuit runtime error!")
exit(0)
print(sv_circ.draw())
command = transform(qi.Statevector.from_instruction(sv_circ), norm)
print("\nExecuting...\n")
system(command)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/pwn/Rattler_Read/main.py | ctfs/UIUCTF/2023/pwn/Rattler_Read/main.py | from RestrictedPython import compile_restricted
from RestrictedPython import Eval
from RestrictedPython import Guards
from RestrictedPython import safe_globals
from RestrictedPython import utility_builtins
from RestrictedPython.PrintCollector import PrintCollector
def exec_poisonous(code):
"""Makes sure your code is safe to run"""
def no_import(name, *args, **kwargs):
raise ImportError("Don't ask another snake for help!")
code += "\nresults = printed"
byte_code = compile_restricted(
code,
filename="<string>",
mode="exec",
)
policy_globals = {**safe_globals, **utility_builtins}
policy_globals['__builtins__']['__metaclass__'] = type
policy_globals['__builtins__']['__name__'] = type
policy_globals['__builtins__']['__import__'] = no_import
policy_globals['_getattr_'] = Guards.safer_getattr
policy_globals['_getiter_'] = Eval.default_guarded_getiter
policy_globals['_getitem_'] = Eval.default_guarded_getitem
policy_globals['_write_'] = Guards.full_write_guard
policy_globals['_print_'] = PrintCollector
policy_globals['_iter_unpack_sequence_'] = Guards.guarded_iter_unpack_sequence
policy_globals['_unpack_sequence_'] = Guards.guarded_unpack_sequence
policy_globals['enumerate'] = enumerate
exec(byte_code, policy_globals, None)
return policy_globals["results"]
if __name__ == '__main__':
print("Well, well well. Let's see just how poisonous you are..")
print(exec_poisonous(input('> ')))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/rev/pwnykey/app.py | ctfs/UIUCTF/2023/rev/pwnykey/app.py | #!/usr/bin/env python3
from flask import Flask, request
import threading
import subprocess
import re
app = Flask(__name__)
FLAG = open('flag.txt').read()
lock = threading.Lock()
@app.route('/')
def index():
return app.send_static_file('index.html')
key_to_check = "00000-00000-00000-00000-00000"
key_format = re.compile(r'^[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}$')
@app.route('/check', methods=['GET', 'POST'])
def check():
global key_to_check
if request.method == 'GET':
if request.remote_addr != '127.0.0.1':
return "Forbidden", 403
try:
lock.release()
except:
pass
return key_to_check
else:
key = request.form['key']
if not key_format.match(key):
return "Invalid key format", 400
lock.acquire()
key_to_check = key
process = subprocess.Popen(['./node_modules/@devicescript/cli/devicescript', 'run', '-t', 'keychecker.devs'], stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, b''):
if b"success!" in line:
process.terminate()
return FLAG
process.wait()
return "Incorrect key", 400
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/crypto/At_Home/chal.py | ctfs/UIUCTF/2023/crypto/At_Home/chal.py | from Crypto.Util.number import getRandomNBitInteger
flag = int.from_bytes(b"uiuctf{******************}", "big")
a = getRandomNBitInteger(256)
b = getRandomNBitInteger(256)
a_ = getRandomNBitInteger(256)
b_ = getRandomNBitInteger(256)
M = a * b - 1
e = a_ * M + a
d = b_ * M + b
n = (e * d - 1) // M
c = (flag * e) % n
print(f"{e = }")
print(f"{n = }")
print(f"{c = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/crypto/Morphing_Time/chal.py | ctfs/UIUCTF/2023/crypto/Morphing_Time/chal.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime
from random import randint
with open("/flag", "rb") as f:
flag = int.from_bytes(f.read().strip(), "big")
def setup():
# Get group prime + generator
p = getPrime(512)
g = 2
return g, p
def key(g, p):
# generate key info
a = randint(2, p - 1)
A = pow(g, a, p)
return a, A
def encrypt_setup(p, g, A):
def encrypt(m):
k = randint(2, p - 1)
c1 = pow(g, k, p)
c2 = pow(A, k, p)
c2 = (m * c2) % p
return c1, c2
return encrypt
def decrypt_setup(a, p):
def decrypt(c1, c2):
m = pow(c1, a, p)
m = pow(m, -1, p)
m = (c2 * m) % p
return m
return decrypt
def main():
print("[$] Welcome to Morphing Time")
g, p = 2, getPrime(512)
a = randint(2, p - 1)
A = pow(g, a, p)
decrypt = decrypt_setup(a, p)
encrypt = encrypt_setup(p, g, A)
print("[$] Public:")
print(f"[$] {g = }")
print(f"[$] {p = }")
print(f"[$] {A = }")
c1, c2 = encrypt(flag)
print("[$] Eavesdropped Message:")
print(f"[$] {c1 = }")
print(f"[$] {c2 = }")
print("[$] Give A Ciphertext (c1_, c2_) to the Oracle:")
try:
c1_ = input("[$] c1_ = ")
c1_ = int(c1_)
assert 1 < c1_ < p - 1
c2_ = input("[$] c2_ = ")
c2_ = int(c2_)
assert 1 < c2_ < p - 1
except:
print("!! You've Lost Your Chance !!")
exit(1)
print("[$] Decryption of You-Know-What:")
m = decrypt((c1 * c1_) % p, (c2 * c2_) % p)
print(f"[$] {m = }")
# !! NOTE !!
# Convert your final result to plaintext using
# long_to_bytes
exit(0)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/crypto/Group_Project/chal.py | ctfs/UIUCTF/2023/crypto/Group_Project/chal.py | from Crypto.Util.number import getPrime, long_to_bytes
from random import randint
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
with open("/flag", "rb") as f:
flag = f.read().strip()
def main():
print("[$] Did no one ever tell you to mind your own business??")
g, p = 2, getPrime(1024)
a = randint(2, p - 1)
A = pow(g, a, p)
print("[$] Public:")
print(f"[$] {g = }")
print(f"[$] {p = }")
print(f"[$] {A = }")
try:
k = int(input("[$] Choose k = "))
except:
print("[$] I said a number...")
if k == 1 or k == p - 1 or k == (p - 1) // 2:
print("[$] I'm not that dumb...")
Ak = pow(A, k, p)
b = randint(2, p - 1)
B = pow(g, b, p)
Bk = pow(B, k, p)
S = pow(Bk, a, p)
key = hashlib.md5(long_to_bytes(S)).digest()
cipher = AES.new(key, AES.MODE_ECB)
c = int.from_bytes(cipher.encrypt(pad(flag, 16)), "big")
print("[$] Ciphertext using shared 'secret' ;)")
print(f"[$] {c = }")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/crypto/Group_Projection/chal.py | ctfs/UIUCTF/2023/crypto/Group_Projection/chal.py | from Crypto.Util.number import getPrime, long_to_bytes
from random import randint
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
with open("/flag", "rb") as f:
flag = f.read().strip()
def main():
print("[$] Did no one ever tell you to mind your own business??")
g, p = 2, getPrime(1024)
a = randint(2, p - 1)
A = pow(g, a, p)
print("[$] Public:")
print(f"[$] {g = }")
print(f"[$] {p = }")
print(f"[$] {A = }")
try:
k = int(input("[$] Choose k = "))
except:
print("[$] I said a number...")
return
if k == 1 or k == p - 1 or k == (p - 1) // 2 or k <= 0 or k >= p:
print("[$] I'm not that dumb...")
return
Ak = pow(A, k, p)
b = randint(2, p - 1)
B = pow(g, b, p)
Bk = pow(B, k, p)
S = pow(Bk, a, p)
key = hashlib.md5(long_to_bytes(S)).digest()
cipher = AES.new(key, AES.MODE_ECB)
c = int.from_bytes(cipher.encrypt(pad(flag, 16)), "big")
print("[$] Ciphertext using shared 'secret' ;)")
print(f"[$] {c = }")
return
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2023/crypto/crack_the_safe/chal.py | ctfs/UIUCTF/2023/crypto/crack_the_safe/chal.py | from Crypto.Cipher import AES
from secret import key, FLAG
p = 4170887899225220949299992515778389605737976266979828742347
ct = bytes.fromhex("ae7d2e82a804a5a2dcbc5d5622c94b3e14f8c5a752a51326e42cda6d8efa4696")
def crack_safe(key):
return pow(7, int.from_bytes(key, 'big'), p) == 0x49545b7d5204bd639e299bc265ca987fb4b949c461b33759
assert crack_safe(key) and AES.new(key,AES.MODE_ECB).decrypt(ct) == FLAG
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2025/misc/Comments_Only/main.py | ctfs/UIUCTF/2025/misc/Comments_Only/main.py | #!/usr/bin/env python3
import tempfile
import subprocess
import os
comment = input("> ").replace("\n", "").replace("\r", "")
code = f"""print("hello world!")
# This is a comment. Here's another:
# {comment}
print("Thanks for playing!")"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
f.write(code)
temp_filename = f.name
try:
result = subprocess.run(
["python3", temp_filename], capture_output=True, text=True, timeout=5
)
if result.stdout:
print(result.stdout, end="")
if result.stderr:
print(result.stderr, end="")
except subprocess.TimeoutExpired:
print("Timeout")
finally:
os.unlink(temp_filename)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2025/crypto/back_to_roots/chal.py | ctfs/UIUCTF/2025/crypto/back_to_roots/chal.py | from random import randint
from decimal import Decimal, getcontext
from hashlib import md5
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from secret import FLAG
K = randint(10**10, 10**11)
print('K', K)
leak = int( str( Decimal(K).sqrt() ).split('.')[-1] )
print(f"leak = {leak}")
ct = AES.new(
md5(f"{K}".encode()).digest(),
AES.MODE_ECB
).encrypt(pad(FLAG, 16))
print(f"ct = {ct.hex()}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2025/crypto/too_many_primes/chal.py | ctfs/UIUCTF/2025/crypto/too_many_primes/chal.py | from sympy import nextprime, randprime
from sympy.core.random import seed
from math import prod, gcd
from Crypto.Util.number import bytes_to_long
# from secret import phi_N, FLAG
p = randprime(2**127, 2**128)
N = 1
while N < 2**2048:
N *= p
p = nextprime(p)
assert gcd(phi_N, 65537) == 1
pt = bytes_to_long(FLAG)
ct = pow(pt, 65537, N)
print("N = ", N)
print("ct = ", ct)
# N = 34546497157207880069779144631831207265231460152307441189118439470134817451040294541962595051467936974790601780839436065863454184794926578999811185968827621504669046850175311261350438632559611677118618395111752688984295293397503841637367784035822653287838715174342087466343269494566788538464938933299114092019991832564114273938460700654437085781899023664719672163757553413657400329448277666114244272477880443449956274432819386599220473627937756892769036756739782458027074917177880632030971535617166334834428052274726261358463237730801653954955468059535321422372540832976374412080012294606011959366354423175476529937084540290714443009720519542526593306377
# ct = 32130352215164271133656346574994403191937804418876038099987899285740425918388836116548661879290345302496993945260385667068119439335225069147290926613613587179935141225832632053477195949276266017803704033127818390923119631817988517430076207710598936487746774260037498876812355794218544860496013734298330171440331211616461602762715807324092281416443801588831683678783343566735253424635251726943301306358608040892601269751843002396424155187122218294625157913902839943220894690617817051114073999655942113004066418001260441287880247349603218620539692362737971711719433735307458772641705989685797383263412327068222383880346012169152962953918108171850055943194
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2025/crypto/symmetric/chal.py | ctfs/UIUCTF/2025/crypto/symmetric/chal.py | from Crypto.Util.number import *
from secret import FLAG
p, q, r, s = [getPrime(512) for _ in "1234"]
print(f"h1 = {p + q + r + s}")
print(f"h2 = {p**2 + q**2 + r**2 + s**2}")
print(f"h3 = {p**3 + q**3 + r**3 + s**3}")
N = p*q*r*s
print(f"N = {N}")
pt = bytes_to_long(FLAG)
ct = pow(pt, 65537, N)
print(f"ct = {ct}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2025/crypto/the_shortest_crypto_chal/chal.py | ctfs/UIUCTF/2025/crypto/the_shortest_crypto_chal/chal.py | from Crypto.Cipher import AES
from hashlib import md5
from secret import a,b,c,d, FLAG
assert a**4 + b**4 == c**4 + d**4 + 17 and max(a,b,c,d) < 2e4 and AES.new( f"{a*b*c*d}".zfill(16).encode() , AES.MODE_ECB).encrypt(FLAG).hex() == "41593455378fed8c3bd344827a193bde7ec2044a3f7a3ca6fb77448e9de55155"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/jail/AHorseWithNoNames/desert.py | ctfs/UIUCTF/2022/jail/AHorseWithNoNames/desert.py | #!/usr/bin/python3
import re
import random
horse = input("Begin your journey: ")
if re.match(r"[a-zA-Z]{4}", horse):
print("It has begun raining, so you return home.")
elif len(set(re.findall(r"[\W]", horse))) > 4:
print(set(re.findall(r"[\W]", horse)))
print("A single horse cannot bear the weight of all those special characters. You return home.")
else:
discovery = list(eval(compile(horse, "<horse>", "eval").replace(co_names=())))
random.shuffle(discovery)
print("You make it through the journey, but are severely dehydrated. This is all you can remember:", discovery)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/jail/AHorseWithNoNeighs/desert.py | ctfs/UIUCTF/2022/jail/AHorseWithNoNeighs/desert.py | #!/usr/bin/python3
import re
import random
horse = input("Begin your journey: ")
if re.search(r"[a-zA-Z]{4}", horse):
print("It has begun raining, so you return home.")
elif len(set(re.findall(r"[\W]", horse))) > 4:
print(set(re.findall(r"[\W]", horse)))
print("A dead horse cannot bear the weight of all those special characters. You return home.")
else:
discovery = list(eval(compile(horse, "<horse>", "eval").replace(co_names=())))
random.shuffle(discovery)
print("You make it through the journey, but are severely dehydrated. This is all you can remember:", discovery)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/jail/safepy/main.py | ctfs/UIUCTF/2022/jail/safepy/main.py | from sympy import *
def parse(expr):
# learned from our mistake... let's be safe now
# https://stackoverflow.com/questions/33606667/from-string-to-sympy-expression
# return sympify(expr)
# https://docs.sympy.org/latest/modules/parsing.html
return parse_expr(expr)
print('Welcome to the derivative (with respect to x) solver!')
user_input = input('Your expression: ')
expr = parse(user_input)
deriv = diff(expr, Symbol('x'))
print('The derivative of your expression is:')
print(deriv)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/That-crete_Log/server.py | ctfs/UIUCTF/2022/crypto/That-crete_Log/server.py | from Crypto.Util.number import bytes_to_long
from random import randrange
from secret import FLAG
from signal import alarm
def miller_rabin(bases, n):
if n == 2 or n == 3:
return True
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for b in bases:
x = pow(b, s, n)
if x == 1 or x == n-1:
continue
for _ in range(r - 1):
x = x * x % n
if x == n-1:
break
else:
return False
return True
def is_prime(n):
bases = [2, 3, 5, 7, 11, 13, 17, 19, 31337]
for i in range(2,min(256, n)):
if n%i == 0:
return False
if n < 256:
return True
return miller_rabin(bases, n)
LLIM = 2**512
ULIM = 2**1024
def die(msg):
print("[X] " + msg)
quit()
def verify_n_is_safe_prime(factors):
N = 1
for p in factors:
N *= p
if not is_prime(p):
die("This factor is not prime!")
N += 1
if max(factors) < LLIM:
die("Smooth N is not safe.")
if not is_prime(N):
die("This N is not prime!")
if LLIM > N or N > ULIM:
die("This N is out of range.")
return N
def main():
msg = bytes_to_long(FLAG)
token = randrange(ULIM)
msg ^= token
print(f"[$] Here's your token for the session: {token}")
alarm(60)
blacklist = []
for _ in range(5):
user_input = input("[?] Give me the prime factors of phi(N): ").strip().split(' ')
phi_factors = [int(x) for x in user_input]
N = verify_n_is_safe_prime(phi_factors)
if N in blacklist:
die("No reusing N allowed!")
x = randrange(N)
print(f"[$] {x = }")
out = pow(x, msg, N)
print(f"[$] {out = }")
blacklist.append(N)
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/MilitaryGradeEncryption/cipher.py | ctfs/UIUCTF/2022/crypto/MilitaryGradeEncryption/cipher.py | from Crypto.Cipher import AES
from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.Util.Padding import pad
from hashlib import md5
from base64 import b64encode
from itertools import cycle
MD5 = lambda s: md5(s).digest()
KEY_PAD = lambda key: b"\x00" * (16 - len(key)) + key
def custom_encrypt(data, password, keysize):
data = pad(data, 16)
def _gen_key(password):
key = password
for i in range(1000):
key = MD5(key)
return key
key = bytes_to_long(_gen_key(password))
ciphers = [
AES.new(KEY_PAD(long_to_bytes((key*(i+1)) % 2**128)) ,AES.MODE_ECB) for i in range(0, keysize, 16)
]
pt_blocks = [
data[i:i+16] for i in range(0, len(data), 16)
]
return b64encode(b"".join([cipher.encrypt(pt_block) for pt_block, cipher in zip(pt_blocks, cycle(ciphers))])).decode()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/MilitaryGradeEncryption/app.py | ctfs/UIUCTF/2022/crypto/MilitaryGradeEncryption/app.py | from flask import Flask, render_template, request
from cipher import custom_encrypt
app = Flask(__name__)
@app.route("/", methods = ["get"])
def home_page():
return render_template("home.html")
@app.route("/encrypt", methods = ["get", "post"])
def encrypt():
if request.method == "POST":
user_data = dict(request.form)
try:
ciphertext = custom_encrypt(user_data["data"].encode(), user_data["pin"].zfill(6).encode(), int(user_data["key_size"]))
return render_template("encrypt.html", not_entered_data = False, data = ciphertext)
except:
return render_template("encrypt.html", not_entered_data = True, error = True)
return render_template("encrypt.html", not_entered_data = True, error = False)
if __name__ == "__main__":
app.run(host="0.0.0.0",port=1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/WringingRings/server.py | ctfs/UIUCTF/2022/crypto/WringingRings/server.py | import sympy as sp
import random
import signal
from secret import FLAG
secret = random.SystemRandom().randint(1, 500_000)
_MAX = 10 ** (len(str(secret)) - 1)
# generating a polynomial
def _f(secret, minimum=3):
coeffs = [secret] + [
random.SystemRandom().randint(1, _MAX) for _ in range(minimum - 1)
]
# print("Secret Polynomial:")
# f_str = str(secret)
# for i, coeff in enumerate(coeffs[1:]):
# f_str += " + " + str(coeff) + "*x^" + str(i + 1)
# print(f_str)
def f(x):
res = 0
for i, coeff in enumerate(coeffs):
res += coeff * x ** (i)
return res
return f
def gen_shares(secret, minimum=3):
f = _f(secret, minimum)
shares = [(i + 1, f(i + 1)) for i in range(minimum)]
return shares
def challenge(secret, minimum=3):
shares = gen_shares(secret, minimum)
points = random.sample(shares, minimum - 1)
points.sort()
return points
def main():
minimum = 10
points = challenge(secret, minimum)
print("[SSSS] Known shares of the secret polynomial: ")
for point in points:
print(f" {point}")
print()
signal.alarm(60)
guess = int(input("[SSSS] Enter my secret: "))
if guess == secret:
print(f"[SSSS] Correct! {FLAG}")
else:
print("[SSSS] Incorrect...")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/asr/chall.py | ctfs/UIUCTF/2022/crypto/asr/chall.py | from secret import flag
from Crypto.Util.number import bytes_to_long, getPrime, isPrime
from math import prod
small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
def gen_prime(bits, lim = 7, sz = 64):
while True:
p = prod([getPrime(sz) for _ in range(bits//sz)])
for i in range(lim):
if isPrime(p+1):
return p+1
p *= small_primes[i]
p = gen_prime(512)
q = gen_prime(512)
n = p*q
phi = (p-1)*(q-1)
e = 0x10001
d = pow(e, -1, phi)
msg = bytes_to_long(flag)
ct = pow(msg, e, n)
print("e = ", e)
print("d = ", d)
print("ct = ", ct)
'''
e = 65537
d = 195285722677343056731308789302965842898515630705905989253864700147610471486140197351850817673117692460241696816114531352324651403853171392804745693538688912545296861525940847905313261324431856121426611991563634798757309882637947424059539232910352573618475579466190912888605860293465441434324139634261315613929473
ct = 212118183964533878687650903337696329626088379125296944148034924018434446792800531043981892206180946802424273758169180391641372690881250694674772100520951338387690486150086059888545223362117314871848416041394861399201900469160864641377209190150270559789319354306267000948644929585048244599181272990506465820030285
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/mom_can_we_have_AES/client.py | ctfs/UIUCTF/2022/crypto/mom_can_we_have_AES/client.py | from Crypto.Util.Padding import pad
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
import random
import string
from fields import cert, block_size
from secret import flag
cipher_suite = {"AES.MODE_CBC": AES.MODE_CBC, "AES.MODE_CTR": AES.MODE_CTR, "AES.MODE_OFB": AES.MODE_OFB, "AES.MODE_EAX": AES.MODE_EAX, "AES.MODE_ECB": AES.MODE_ECB}
########## Client Hello ##########
# Cipher suite
print(*cipher_suite.keys(), sep=', ')
client_random = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(4))
# Client random
print(client_random)
########## Server Hello ##########
# verify server
# Enter signed certificate
server_signature_hex = input()
server_signature = bytearray.fromhex(server_signature_hex)
public_key = RSA.import_key(open("receiver.pem").read())
cipher_hash = SHA256.new(cert)
verifier = PKCS1_v1_5.new(public_key)
if not verifier.verify(cipher_hash, server_signature):
print("Mom told me not to talk to strangers.")
exit()
# Enter selected cipher suite
input_encryptions_suite = input()
if len(input_encryptions_suite) == 0:
print(" nO SeCUriTY :/")
exit()
selected_cipher_suite = {}
input_encryptions_suite = input_encryptions_suite.split(", ")
for method in input_encryptions_suite:
if method in cipher_suite:
selected_cipher_suite[method] = cipher_suite[method]
if len(selected_cipher_suite) == 0:
print("I'm a rebellious kid who refuses to talk to people who don't speak my language.")
exit()
# Enter server random
server_random = input()
########## Client Cipherspec finished & Client KeyExchange ##########
premaster_secret = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))
cipher_rsa = PKCS1_OAEP.new(public_key)
premaster_secret_encrypted = cipher_rsa.encrypt(premaster_secret.encode()).hex()
# Encrypted premaster secret
print(premaster_secret_encrypted)
session_key = SHA256.new((client_random + server_random + premaster_secret).encode()).hexdigest()
chosen_cipher_name = next(iter(selected_cipher_suite))
# Using encryption mode
print(chosen_cipher_name)
cipher = AES.new(session_key.encode()[:16], cipher_suite[chosen_cipher_name])
# Encrypted finish message
print(cipher.encrypt(pad(b"finish", block_size)).hex())
########## ServerKeyExchange & CipherSpec Finished ##########
# Confirm finish
finish_msg = input()
assert(finish_msg == "finish")
########## Communication ##########
while True:
prefix = input()
if len(prefix) != 0:
prefix = bytearray.fromhex(prefix)
extended_flag = prefix + flag
else:
extended_flag = flag
ciphertext = cipher.encrypt(pad(extended_flag, block_size)).hex()
print(str(ciphertext))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/mom_can_we_have_AES/server.py | ctfs/UIUCTF/2022/crypto/mom_can_we_have_AES/server.py | from Crypto.Util.Padding import pad, unpad
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
import random
import string
from fields import cert, block_size
from secret import flag
cipher_suite = {"AES.MODE_CBC" : AES.MODE_CBC, "AES.MODE_CTR" : AES.MODE_CTR, "AES.MODE_EAX" : AES.MODE_EAX, "AES.MODE_GCM" : AES.MODE_GCM, "AES.MODE_ECB" : AES.MODE_ECB}
########## Client Hello ##########
# Enter encryption methods
input_encryptions_suite = input()
client_cipher_suite = input_encryptions_suite.split(", ")
# Enter client random
client_random = input()
########## Server Hello ##########
# Certificate
private_key = RSA.import_key(open("my_credit_card_number.pem").read())
cipher_hash = SHA256.new(cert)
signature = PKCS1_v1_5.new(private_key).sign(cipher_hash)
#Signed certificate
print(signature.hex())
# select cipher suite
selected_cipher_suite = {}
for method in cipher_suite:
if method in client_cipher_suite:
selected_cipher_suite[method] = cipher_suite[method]
if len(selected_cipher_suite) == 0:
print("Honey, we have a problem. I'm sorry but I'm disowning you :(")
exit()
# Selected cipher suite
print(*selected_cipher_suite.keys(), sep=', ')
server_random = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(4))
# Server random
print(server_random)
########## ClientKeyExchange & CipherSpec Finished ##########
# Enter premaster secret
encrypted_premaster_secret = input()
cipher_rsa = PKCS1_OAEP.new(private_key)
premaster_secret = cipher_rsa.decrypt(bytearray.fromhex(encrypted_premaster_secret)).decode('utf-8')
session_key = SHA256.new((client_random + server_random + premaster_secret).encode()).hexdigest()
# Enter chosen cipher
chosen_cipher_name = input()
if chosen_cipher_name not in selected_cipher_suite:
print("No honey, I told you we're not getting ", chosen_cipher_name, '.', sep='')
exit()
cipher = AES.new(session_key.encode()[:16], cipher_suite[chosen_cipher_name])
# Enter encrypted finish
client_finish = input()
client_finish = bytearray.fromhex(client_finish)
########## ServerKeyExchange & CipherSpec Finished ##########
finish_msg = unpad(cipher.decrypt(client_finish), block_size)
assert(finish_msg == b'finish')
########## Communication ##########
# Listening...
while True:
client_msg = input()
client_msg = unpad(cipher.decrypt(bytearray.fromhex(client_msg)), block_size)
if client_msg == flag:
print("That is correct.")
else:
print("You are not my son.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/crypto/EllipticClockCrypto/ecc.py | ctfs/UIUCTF/2022/crypto/EllipticClockCrypto/ecc.py | # Code inspired by https://ecchacks.cr.yp.to/clockcrypto.py
from random import seed, randrange
from hashlib import md5
from Crypto.Cipher import AES
from secret import FLAG
# 256-bit security!
p = 62471552838526783778491264313097878073079117790686615043492079411583156507853
class Fp:
def __init__(self,x):
self.int = x % p
def __str__(self):
return str(self.int)
__repr__ = __str__
def __int__(self):
return self.int
def __eq__(a,b):
return a.int == b.int
def __ne__(a,b):
return a.int != b.int
def __add__(a,b):
return Fp(a.int + b.int)
def __sub__(a,b):
return Fp(a.int - b.int)
def __mul__(a,b):
return Fp(a.int * b.int)
def __truediv__(a,b):
return a*Fp(pow(b.int,-1,p))
class ClockPoint:
def __init__(self,x,y):
assert int(x*x + y*y) == 1
self.x = x
self.y = y
def __str__(self):
return f"({self.x},{self.y})"
def __eq__(self, other):
return str(self) == str(other)
__repr__ = __str__
def get_hash(self):
return md5(str(self).encode()).digest()
def __add__(self, other):
x1,y1 = self.x, self.y
x2,y2 = other.x, other.y
return ClockPoint( x1*y2+y1*x2, y1*y2-x1*x2 )
def scalar_mult(x: ClockPoint, n: int) -> ClockPoint:
y = ClockPoint(Fp(0),Fp(1))
if n == 0: return y
if n == 1: return x
while n > 1:
if n % 2 == 0:
x = x + x
n = n // 2
else:
y = x + y
x = x + x
n = (n-1) // 2
return x + y
base_point = ClockPoint(Fp(34510208759284660042264570994647050969649037508662054358547659196695638877343),Fp(4603880836195915415499609181813839155074976164846557299963454168096659979337))
alice_secret = randrange(2**256)
alice_public = scalar_mult(base_point, alice_secret)
print("Alice's public key: ", alice_public)
bob_secret = randrange(2**256)
bob_public = scalar_mult(base_point, bob_secret)
print("Bob's public key: ", bob_public)
assert scalar_mult(bob_public, alice_secret) == scalar_mult(alice_public, bob_secret)
shared_secret = scalar_mult(bob_public, alice_secret)
key = shared_secret.get_hash()
print("Encrypted flag: ", AES.new(key, AES.MODE_ECB).encrypt(FLAG))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/web/modernism/app.py | ctfs/UIUCTF/2022/web/modernism/app.py | from flask import Flask, Response, request
app = Flask(__name__)
@app.route('/')
def index():
prefix = bytes.fromhex(request.args.get("p", default="", type=str))
flag = request.cookies.get("FLAG", default="uiuctf{FAKEFLAG}").encode() #^uiuctf{[A-Za-z]+}$
return Response(prefix+flag, mimetype="text/plain")
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2022/web/precisionism/app.py | ctfs/UIUCTF/2022/web/precisionism/app.py | from flask import Flask, Response, request
app = Flask(__name__)
@app.route('/')
def index():
prefix = bytes.fromhex(request.args.get("p", default="", type=str))
flag = request.cookies.get("FLAG", default="uiuctf{FAKEFLAG}").encode() #^uiuctf{[0-9A-Za-z]{8}}$
return Response(prefix+flag+b"Enjoy your flag!", mimetype="text/plain")
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UIUCTF/2020/MuJS/run-remote.py | ctfs/UIUCTF/2020/MuJS/run-remote.py | #!/usr/bin/env python3
import requests
import json
import pprint
import sys
if len(sys.argv) != 2:
print("Usage: %s [script.js]" % sys.argv[0])
sys.exit(1)
script_path = sys.argv[1]
url = 'https://mujs.chal.uiuc.tf/go'
myobj = {'script': open(script_path).read()}
results = json.loads(requests.post(url, data = myobj).text)
if not isinstance(results, list):
print("Invalid response from server.")
sys.exit(1)
for i in range(0, len(results)):
result = results[i]
stderr_output = result["stderr"]
stdout_output = result["stdout"]
print("Result from run against mujs-%d binary:" % i)
print("stdout:")
print(stdout_output)
print("stderr:")
print(stderr_output)
print()
flag = ""
for result in results:
flag += result["stdout"].replace("\n", "")
print("Maybe flag: " + flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/misc/safebox_pro/safebox.py | ctfs/TPCTF/2023/misc/safebox_pro/safebox.py |
from Crypto.Cipher import ChaCha20
from hashlib import sha256
from itertools import cycle
from pathlib import Path
import os
from secret import flag
CHACHA20_KEY = b'3gn8C5j9PedPqf2tKANb91c5k5cxXx2n'
SBOX = b'\x1b\x8e6\xa5\xd2+\xad\'S]\x16\xa8e\xa6G\xe44,\xb9\xe2m/&\xbe\xce\x1fR\xf3\x14\xcal\x9fH\xee\xe3\x11\xdb\xe8\xc5\xcf\xab\xae\x7f\xfe\xe9\xd3\xeb@\xe0\x0f\xf9%\x97\x19\xacK\x90\xbd\x10\xcb8\xc8\x18\xc0D\xd8h)v\x13U\x0b\xc7\xa07\x99\xd7\x81L\x9b\xbf\xa4\xda\x03~\x84\x15\x95\x07P\x06B\xb5(o\x879\x1c\xe6$\xef\xfa\rp3\x9c\xb2 \x17\x86F`z|\xa3\x92E\x85\x02=\xddIb0\xf8\x12\xa1\x00T\xf4_5\xf7\x1e\x9d-i\x96g:\xb8\x04\xa7\xb0\xc2\x8a\xc4\xf1!2\x8b\xb7;J\x8d\xb4?[\xed\xc6\x89k\xe7\xd9wud\xa9\x0c\xb6\xff\xfc\xfb\xc9\xf2^>\\Ca\x0e\x91\t*\xde\x94sc#\xf6\xdfXOr\x8cqx\xc1\x80\xdc\xa2\x83A\n\xd6\x1af\xbc\xaf\xc3y\x8f\xfd\xcd\xe1\x9a{"\xbb\xd4\xea\xd1.\xe5Q\x82\xf0W\xb3t<\xd0n\x08j\xecM\xb1\x05V\xba\xcc\x9eN\x93}\xf5\xaa\x981Z\x88\xd5Y\x1d\x01'
CONTENT_SIZE = 32
IV_SIZE = 12
BLOCK_SIZE = CONTENT_SIZE + IV_SIZE
def encrypt_block(data, key, key2):
iv = os.urandom(IV_SIZE)
cipher = ChaCha20.new(key=CHACHA20_KEY, nonce=iv)
return iv + cipher.encrypt(bytes([(x + SBOX[y ^ z]) & 0xff for x, y, z in zip(data, cycle(key), cycle(key2))]))
def decrypt_block(block, key, key2):
cipher = ChaCha20.new(key=CHACHA20_KEY, nonce=block[:IV_SIZE])
return bytes([(x - SBOX[y ^ z]) & 0xff for x, y, z in zip(cipher.decrypt(block[IV_SIZE:]), cycle(key), cycle(key2))])
class IncorrectKeyException(Exception):
pass
class SafeFS:
def __init__(self, base, secret_key):
self.base = Path(base)
self.secret_key = secret_key
self.file_key_hashes = {}
self.total_written = 0
def _path(self, path):
return self.base / sha256(path).hexdigest()
def _open(self, path, mode, key):
key_hash = sha256(key).digest()
if path in self.file_key_hashes:
if self.file_key_hashes[path] != key_hash:
raise IncorrectKeyException
self.file_key_hashes[path] = key_hash
key2 = sha256(self.secret_key + path).digest()
path = self._path(path)
if not path.exists():
path.touch()
return open(path, mode), key2
def read(self, path, offset, length, key):
file, key2 = self._open(path, 'rb', key)
result = b''
blk, rem = divmod(offset, CONTENT_SIZE)
while len(result) < length:
file.seek(blk * BLOCK_SIZE)
block = file.read(BLOCK_SIZE)
if len(block) == 0:
break
result += decrypt_block(block, key, key2)[rem:]
blk += 1
rem = 0
return result[:length]
def write(self, path, offset, data, key):
file, key2 = self._open(path, 'rb+', key)
self.total_written += len(data)
if self.total_written > 20 * 1024 * 1024:
print('You\'ve exceeded the storage limit!')
quit()
written = 0
blk, rem = divmod(offset + written, CONTENT_SIZE)
while len(data) > 0:
off = blk * BLOCK_SIZE
file.seek(off)
block = file.read(BLOCK_SIZE)
if len(block) != 0:
block = decrypt_block(block, key, key2)
count = min(CONTENT_SIZE - rem, len(data))
block = bytearray(block.ljust(rem + count, b'\0'))
block[rem:rem + count] = data[:count]
data = data[count:]
written += count
file.seek(off)
file.write(encrypt_block(block, key, key2))
blk += 1
rem = 0
def rename(self, old, new):
if old == new:
return
# TODO: renaming file corrupts it
self._path(old).rename(self._path(new))
self.file_key_hashes[new] = self.file_key_hashes[old]
del self.file_key_hashes[old]
def remove(self, path):
self._path(path).unlink()
del self.file_key_hashes[path]
BANNER = '''
🔒 Welcome to the Safebox! 🔒
Each file is encrypted with a separate
key, making the system super duper safe.
Make sure you don't forget the keys ;)
Commands:
get [file] [offset] [length] [key]
put [file] [offset] [data] [key]
mv [old] [new]
rm [file]
exit
Binary data is encoded in hex.
Example:
put secret.txt 0 0x0123456789 secretkey
get secret.txt 0 5 secretkey
- 0123456789
'''
print(BANNER)
fs = SafeFS('./base', os.urandom(32))
def process_command(cmd, args):
if cmd == 'get':
file, offset, length, key = args
if file.endswith(b'.flag'):
print('Nope')
return
data = fs.read(file, int(offset), int(length), key)
print(data.hex())
elif cmd == 'put':
file, offset, data, key = args
if file.endswith(b'.flag'):
print('Nope')
return
fs.write(file, int(offset), data, key)
elif cmd == 'mv':
old, new = args
fs.rename(old, new)
elif cmd == 'rm':
file, = args
fs.remove(file)
elif cmd == 'putflag':
# TODO: remove
file, key = args
fs.write(file + b'.flag', 0, flag, key)
elif cmd == 'exit':
print('Bye!')
quit()
else:
print('Unknown command')
while True:
line = input('> ').strip().split()
if len(line) == 0:
continue
args = [bytes.fromhex(x[2:]) if x.startswith('0x')
else x.encode() for x in line[1:]]
try:
process_command(line[0], args)
except IncorrectKeyException:
print('Incorrect key')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/misc/safebox/safebox.py | ctfs/TPCTF/2023/misc/safebox/safebox.py |
from Crypto.Cipher import ChaCha20
from hashlib import sha256
from itertools import cycle
from pathlib import Path
import os
from secret import flag
CHACHA20_KEY = b'3gn8C5j9PedPqf2tKANb91c5k5cxXx2n'
CONTENT_SIZE = 32
IV_SIZE = 12
BLOCK_SIZE = CONTENT_SIZE + IV_SIZE
def encrypt_block(data, key, key2):
iv = os.urandom(IV_SIZE)
cipher = ChaCha20.new(key=CHACHA20_KEY, nonce=iv)
return iv + cipher.encrypt(bytes([(x + (y ^ z)) & 0xff for x, y, z in zip(data, cycle(key), cycle(key2))]))
def decrypt_block(block, key, key2):
cipher = ChaCha20.new(key=CHACHA20_KEY, nonce=block[:IV_SIZE])
return bytes([(x - (y ^ z)) & 0xff for x, y, z in zip(cipher.decrypt(block[IV_SIZE:]), cycle(key), cycle(key2))])
class IncorrectKeyException(Exception):
pass
class SafeFS:
def __init__(self, base, secret_key):
self.base = Path(base)
self.secret_key = secret_key
self.file_key_hashes = {}
self.total_written = 0
def _path(self, path):
return self.base / sha256(path).hexdigest()
def _open(self, path, mode, key):
key_hash = sha256(key).digest()
if path in self.file_key_hashes:
if self.file_key_hashes[path] != key_hash:
raise IncorrectKeyException
self.file_key_hashes[path] = key_hash
key2 = sha256(self.secret_key + path).digest()
path = self._path(path)
if not path.exists():
path.touch()
return open(path, mode), key2
def read(self, path, offset, length, key):
file, key2 = self._open(path, 'rb', key)
result = b''
blk, rem = divmod(offset, CONTENT_SIZE)
while len(result) < length:
file.seek(blk * BLOCK_SIZE)
block = file.read(BLOCK_SIZE)
if len(block) == 0:
break
result += decrypt_block(block, key, key2)[rem:]
blk += 1
rem = 0
return result[:length]
def write(self, path, offset, data, key):
file, key2 = self._open(path, 'rb+', key)
self.total_written += len(data)
if self.total_written > 20 * 1024 * 1024:
print('You\'ve exceeded the storage limit!')
quit()
written = 0
blk, rem = divmod(offset + written, CONTENT_SIZE)
while len(data) > 0:
off = blk * BLOCK_SIZE
file.seek(off)
block = file.read(BLOCK_SIZE)
if len(block) != 0:
block = decrypt_block(block, key, key2)
count = min(CONTENT_SIZE - rem, len(data))
block = bytearray(block.ljust(rem + count, b'\0'))
block[rem:rem + count] = data[:count]
data = data[count:]
written += count
file.seek(off)
file.write(encrypt_block(block, key, key2))
blk += 1
rem = 0
def rename(self, old, new):
if old == new:
return
# TODO: renaming file corrupts it
self._path(old).rename(self._path(new))
self.file_key_hashes[new] = self.file_key_hashes[old]
del self.file_key_hashes[old]
def remove(self, path):
self._path(path).unlink()
del self.file_key_hashes[path]
BANNER = '''
🔒 Welcome to the Safebox! 🔒
Each file is encrypted with a separate
key, making the system super duper safe.
Make sure you don't forget the keys ;)
Commands:
get [file] [offset] [length] [key]
put [file] [offset] [data] [key]
mv [old] [new]
rm [file]
exit
Binary data is encoded in hex.
Example:
put secret.txt 0 0x0123456789 secretkey
get secret.txt 0 5 secretkey
- 0123456789
'''
print(BANNER)
fs = SafeFS('./base', os.urandom(32))
def process_command(cmd, args):
if cmd == 'get':
file, offset, length, key = args
if file.endswith(b'.flag'):
print('Nope')
return
data = fs.read(file, int(offset), int(length), key)
print(data.hex())
elif cmd == 'put':
file, offset, data, key = args
fs.write(file, int(offset), data, key)
elif cmd == 'mv':
old, new = args
fs.rename(old, new)
elif cmd == 'rm':
file, = args
fs.remove(file)
elif cmd == 'putflag':
# TODO: remove
file, key = args
fs.write(file + b'.flag', 0, flag, key)
elif cmd == 'exit':
print('Bye!')
quit()
else:
print('Unknown command')
while True:
line = input('> ').strip().split()
if len(line) == 0:
continue
args = [bytes.fromhex(x[2:]) if x.startswith('0x')
else x.encode() for x in line[1:]]
try:
process_command(line[0], args)
except IncorrectKeyException:
print('Incorrect key')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/crypto/matrix/matrix.py | ctfs/TPCTF/2023/crypto/matrix/matrix.py | import numpy as np
matrices=[[[16, 55, 40], [0, -39, -40], [0, 55, 56]], [[13, 41, 29], [3, -25, -29], [-3, 41, 45]], [[7, 13, 7], [9, 3, -7], [-9, 13, 23]], [[1, -15, -15], [15, 31, 15], [-15, -15, 1]], [[217, 728, 512], [39, -472, -512], [-39, 728, 768]], [[9341, 41833, 32493], [21635, 96663, 75027], [-29315, -130967, -101651]], [[10, 27, 18], [6, -11, -18], [-6, 27, 34]], [[28, 111, 84], [-12, -95, -84], [12, 111, 100]], [[266, 970, 705], [-10, -714, -705], [10, 970, 961]], [[1878, 4506, 2629], [2218, -410, -2629], [-2218, 4506, 6725]], [[253, 953, 701], [3, -697, -701], [-3, 953, 957]], [[1881, 4520, 2640], [2215, -424, -2640], [-2215, 4520, 6736]], [[233, 821, 589], [23, -565, -589], [-23, 821, 845]], [[1593, 3096, 1504], [2503, 1000, -1504], [-2503, 3096, 5600]], [[-7038, -35490, -28451], [-19586, -98654, -79069], [27266, 137310, 110045]], [[196, 695, 500], [60, -439, -500], [-60, 695, 756]], [[1590, 3082, 1493], [2506, 1014, -1493], [-2506, 3082, 5589]], [[166, 490, 325], [90, -234, -325], [-90, 490, 581]], [[149002, 670490, 521489], [375174, 1688246, 1313071], [-506214, -2277910, -1771695]], [[163, 546, 384], [93, -290, -384], [-93, 546, 640]], [[145, 457, 313], [111, -201, -313], [-111, 457, 569]], [[148969, 670341, 521373], [375207, 1688395, 1313187], [-506247, -2278059, -1771811]], [[178, 606, 429], [78, -350, -429], [-78, 606, 685]], [[9389, 42057, 32669], [21587, 96439, 74851], [-29267, -130743, -101475]], [[46, 195, 150], [-30, -179, -150], [30, 195, 166]], [[4, -1, -4], [12, 17, 4], [-12, -1, 12]], [[-7041, -35504, -28462], [-19583, -98640, -79058], [27263, 137296, 110034]], [[184, 579, 396], [72, -323, -396], [-72, 579, 652]], [[22, 83, 62], [-6, -67, -62], [6, 83, 78]], [[127, 368, 242], [129, -112, -242], [-129, 368, 498]], [[25, 97, 73], [-9, -81, -73], [9, 97, 89]], [[118, 289, 172], [138, -33, -172], [-138, 289, 428]], [[19, 69, 51], [-3, -53, -51], [3, 69, 67]], [[199, 639, 441], [57, -383, -441], [-57, 639, 697]], [[160, 517, 358], [96, -261, -358], [-96, 517, 614]]]
flag=input("Flag (TPCTF{...}): ").strip()
x=int('23'+''.join([f"{i:07b}" for i in flag[6:-1].encode()]),16)
a=np.array([80+256*x,396+1280*x, 317+1024*x])
mi=input("Series of matrices: ").encode()
for i in mi:
a=np.dot(a,matrices[i-65])
if np.dot(a,[84118752460105480846935836819753079271600697690686619664255230678276718877418958891792249030775786942317984652111184426018279427, 89173103422445447876715049689189652193176619520301916283899743110137112860432642548206151350732936688768966032976538813292605444, -132496067393083180057627771316425335059370948823049050270938486557240570794895542908205751446110117596540703704248469623120326662])==0:
print("Correct")
else:
print("Wrong") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/crypto/sort_teaser/sort-teaser.py | ctfs/TPCTF/2023/crypto/sort_teaser/sort-teaser.py | import re
from Crypto.Util.number import bytes_to_long
import random
letters=set(bytes(range(65,91)).decode())
class Command:
def __init__(self, target_var, op, l, r=0):
self.target_var = target_var
self.op = op
self.l = l if l in letters else int(l)
self.r = r if r in letters else int(r)
def __str__(self):
return self.target_var+"="+str(self.l)+((self.op+str(self.r)) if self.op!="=" else "")
__repr__=__str__
class Computation:
def __init__(self):
self.vars={x:0 for x in letters}
def resolve_val(self,symbol):
return self.vars[symbol] if type(symbol)==str else symbol
def run(self,cmd):
if cmd.op=='+':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)+self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='-':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)-self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='*':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)*self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='/':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)//self.resolve_val(cmd.r)
elif cmd.op=='%':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)%self.resolve_val(cmd.r)
elif cmd.op=='&':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)&self.resolve_val(cmd.r)
elif cmd.op=='|':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)|self.resolve_val(cmd.r)
elif cmd.op=='^':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)^self.resolve_val(cmd.r)
elif cmd.op=='<':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<self.resolve_val(cmd.r))
elif cmd.op=='>':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>self.resolve_val(cmd.r))
elif cmd.op=='<=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<=self.resolve_val(cmd.r))
elif cmd.op=='>=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>=self.resolve_val(cmd.r))
elif cmd.op=='!=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)!=self.resolve_val(cmd.r))
elif cmd.op=='==':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)==self.resolve_val(cmd.r))
elif cmd.op=='<<':
if self.resolve_val(cmd.l).bit_length()+self.resolve_val(cmd.r)>100000:
raise OverflowError
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<<self.resolve_val(cmd.r))
elif cmd.op=='>>':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>>self.resolve_val(cmd.r))
elif cmd.op=='=':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)
def parse_command(cmdstr):
cmdstr=re.sub("\s","",cmdstr)
m=re.match("^([A-Z])=([A-Z]|-?\d+)$",cmdstr)
if m:
return Command(m[1],"=",m[2])
m=re.match("^([A-Z])=([A-Z]|-?\d+)([+\-*/%&|^><]|[><!=]=|<<|>>)([A-Z]|-?\d+)$",cmdstr)
if m:
return Command(m[1],m[3],m[2],m[4])
m=re.match("^([A-Z])=-([A-Z])$",cmdstr)
if m:
return Command(m[1],"-",0,m[2])
raise SyntaxError
def run_commands(fun, init_state):
comp=Computation()
comp.vars.update(init_state)
try:
for i in fun:
comp.run(i)
except Exception as e:
pass # exceptions are suppressed
return comp.vars
def input_function(line_limit, cmd_limit):
fun=[]
while True:
line = input().strip()
if line == "EOF":
break
if len(line)>line_limit:
assert False, "command too long"
fun.append(parse_command(line))
if len(fun)>cmd_limit:
assert False, "too many commands"
return fun
flag=open(f"flag.txt").read().strip()
assert len(flag)<32
print("Enter your function A:")
fun_A=input_function(100,30)
flag_array=list(flag.encode()) # the flag is static
A=[]
B=[]
for i in range(100):
cur_A=bytes_to_long(bytes(flag_array))
cur_res=run_commands(fun_A,{"A":cur_A})
A.append(cur_A)
B.append(cur_res["B"])
random.shuffle(flag_array)
assert len(set(B))==1, "results are not same"
target_B=bytes_to_long(bytes(sorted(flag_array)))
if target_B==B[0]:
print(flag)
else:
print("You did not sort correctly")
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/crypto/nanoOTP/nanoOTP.py | ctfs/TPCTF/2023/crypto/nanoOTP/nanoOTP.py | import os
import random
import secrets
import tempfile
from pathlib import Path
from secret import flag
TEMP_DIR = Path(tempfile.mkdtemp())
import string
from hashlib import sha256
def proof_of_work():
s = ''.join([secrets.choice(string.digits + string.ascii_letters)
for _ in range(20)])
print(f'sha256(XXXX+{s[4:]}) == {sha256(s.encode()).hexdigest()}')
if input('Give me XXXX: ') != s[:4]:
exit(1)
# ========================================================================
secret_1 = None
secret_2 = None
flag_token = (None, None)
class InvalidChar(Exception):
pass
class DangerousToken(Exception):
pass
valid_char = [ord(x) for x in string.digits +
string.ascii_letters + string.punctuation]
def check_valid(s: bytes):
r = list(map(lambda x: x in valid_char, s))
if False in r:
raise InvalidChar(r.index(False))
def getrandbits(token: bytes, k: int) -> int:
random.seed(token)
return random.getrandbits(k)
def bytes_xor_int(s: bytes, r: int, length: int) -> bytes:
s = int.from_bytes(s, 'little')
return (s ^ r).to_bytes(length, 'little')
def __byte_shuffle(s: int) -> int:
bits = list(bin(s)[2:].zfill(8))
random.shuffle(bits)
return int(''.join(bits), 2)
def __byte_shuffle_re(s: int) -> int:
s = bin(s)[2:].zfill(8)
idx = list(range(8))
random.shuffle(idx)
s = ''.join([s[idx.index(i)] for i in range(8)])
return int(s, 2)
def bits_shuffle(s: bytes) -> bytes:
s = bytearray(s)
for i in range(len(s)):
s[i] = __byte_shuffle(s[i])
return bytes(s)
def bits_shuffle_re(s: bytes) -> bytes:
s = bytearray(s)
for i in range(len(s)):
s[i] = __byte_shuffle_re(s[i])
return bytes(s)
def bytes_shuffle(token: bytes, s: bytes) -> bytes:
random.seed(token)
s = bytearray(s)
random.shuffle(s)
return bytes(s)
def bytes_shuffle_re(token: bytes, s: bytes) -> bytes:
random.seed(token)
idx = list(range(len(s)))
random.shuffle(idx)
r = bytearray(len(s))
for i in range(len(s)):
r[idx[i]] = s[i]
return bytes(r)
def encrypt(s: str, token=(None, None)):
if token[0] is None or token[1] is None:
token = (secrets.randbits(32).to_bytes(4, 'little'),
secrets.randbits(32).to_bytes(4, 'little'))
s: bytes = s.encode()
check_valid(s)
r = getrandbits(token[0]+secret_1, 8*len(s))
s = bytes_xor_int(s, r, len(s))
s = bits_shuffle(s)
s += token[0]
s = bytes_shuffle(token[1]+secret_2, s)
s += token[1]
s = s.hex()
return s
def decrypt(s: str):
s: bytes = bytes.fromhex(s)
s, token_1 = s[:-4], s[-4:]
s = bytes_shuffle_re(token_1+secret_2, s)
s, token_0 = s[:-4], s[-4:]
r = getrandbits(token_0+secret_1, 8*len(s))
s = bits_shuffle_re(s)
s = bytes_xor_int(s, r, len(s))
if (len(s) == len(flag)) + (token_0 == flag_token[0]) + (token_1 == flag_token[1]) >= 2:
raise DangerousToken
check_valid(s)
s = s.decode()
return s
def encrypt_flag():
flag_enc = encrypt(flag, flag_token)
print(f'flag: {flag_enc}')
def init():
global secret_1, secret_2, flag_token
try:
secret_1 = (TEMP_DIR/'secret_1').read_bytes()
secret_2 = (TEMP_DIR/'secret_2').read_bytes()
flag_token = (TEMP_DIR/'flag_token').read_bytes()
assert len(secret_1) == 64
assert len(secret_2) == 64
assert len(flag_token) == 8
flag_token = (flag_token[:4], flag_token[4:])
except Exception:
rebuild()
def rebuild():
global secret_1, secret_2, flag_token
secret_1 = os.urandom(64)
secret_2 = os.urandom(64)
flag_token = (os.urandom(4), os.urandom(4))
(TEMP_DIR/'secret_1').write_bytes(secret_1)
(TEMP_DIR/'secret_2').write_bytes(secret_2)
(TEMP_DIR/'flag_token').write_bytes(flag_token[0]+flag_token[1])
def choose_mode():
print('Choose function:')
print('0: encrypt')
print('1: decrypt')
print('2: rebuild')
mode = int(input('> '))
assert 0 <= mode <= 2
return mode
if __name__ == '__main__':
proof_of_work()
print('Welcome to Nano OTP Box! (Version 1.1)')
init()
encrypt_flag()
while True:
try:
mode = choose_mode()
if mode == 0:
print('Please input original message.')
msg = input('> ')
print('encrypted message:', encrypt(msg))
elif mode == 1:
print('Please input encrypted message.')
msg = input('> ')
print('original message:', decrypt(msg))
elif mode == 2:
rebuild()
encrypt_flag()
except InvalidChar as e:
print('The original message contains invalid characters: pos', e)
except DangerousToken:
print('The encrypted message contains dangerous token')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/crypto/blurred_memory/blurred_memory.py | ctfs/TPCTF/2023/crypto/blurred_memory/blurred_memory.py |
from secret import flag
assert flag[:6] == 'TPCTF{' and flag[-1] == '}'
flag = flag[6:-1]
assert len(set(flag)) == len(flag)
xs = []
for i, c in enumerate(flag):
xs += [ord(c)] * (i + 1)
p = 257
print('output =', [sum(pow(x, k, p) for x in xs) % p for k in range(1, len(xs) + 1)])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/crypto/sort_level_1/sort.py | ctfs/TPCTF/2023/crypto/sort_level_1/sort.py | import re
from Crypto.Util.number import bytes_to_long
import random
letters=set(bytes(range(65,91)).decode())
class Command:
def __init__(self, target_var, op, l, r=0):
self.target_var = target_var
self.op = op
self.l = l if l in letters else int(l)
self.r = r if r in letters else int(r)
def __str__(self):
return self.target_var+"="+str(self.l)+((self.op+str(self.r)) if self.op!="=" else "")
__repr__=__str__
class Computation:
def __init__(self):
self.vars={x:0 for x in letters}
def resolve_val(self,symbol):
return self.vars[symbol] if type(symbol)==str else symbol
def run(self,cmd):
if cmd.op=='+':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)+self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='-':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)-self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='*':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)*self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='/':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)//self.resolve_val(cmd.r)
elif cmd.op=='%':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)%self.resolve_val(cmd.r)
elif cmd.op=='&':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)&self.resolve_val(cmd.r)
elif cmd.op=='|':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)|self.resolve_val(cmd.r)
elif cmd.op=='^':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)^self.resolve_val(cmd.r)
elif cmd.op=='<':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<self.resolve_val(cmd.r))
elif cmd.op=='>':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>self.resolve_val(cmd.r))
elif cmd.op=='<=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<=self.resolve_val(cmd.r))
elif cmd.op=='>=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>=self.resolve_val(cmd.r))
elif cmd.op=='!=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)!=self.resolve_val(cmd.r))
elif cmd.op=='==':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)==self.resolve_val(cmd.r))
elif cmd.op=='<<':
if self.resolve_val(cmd.l).bit_length()+self.resolve_val(cmd.r)>100000:
raise OverflowError
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<<self.resolve_val(cmd.r))
elif cmd.op=='>>':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>>self.resolve_val(cmd.r))
elif cmd.op=='=':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)
def parse_command(cmdstr):
cmdstr=re.sub("\s","",cmdstr)
m=re.match("^([A-Z])=([A-Z]|-?\d+)$",cmdstr)
if m:
return Command(m[1],"=",m[2])
m=re.match("^([A-Z])=([A-Z]|-?\d+)([+\-*/%&|^><]|[><!=]=|<<|>>)([A-Z]|-?\d+)$",cmdstr)
if m:
return Command(m[1],m[3],m[2],m[4])
m=re.match("^([A-Z])=-([A-Z])$",cmdstr)
if m:
return Command(m[1],"-",0,m[2])
raise SyntaxError
def run_commands(fun, init_state):
comp=Computation()
comp.vars.update(init_state)
try:
for i in fun:
comp.run(i)
except Exception as e:
pass # exceptions are suppressed
return comp.vars
def input_function(line_limit, cmd_limit):
fun=[]
while True:
line = input().strip()
if line == "EOF":
break
if len(line)>line_limit:
assert False, "command too long"
fun.append(parse_command(line))
if len(fun)>cmd_limit:
assert False, "too many commands"
return fun
level=int(input("Level: "))
assert level in [1,2]
flag=open(f"flag{level}.txt").read().strip()
assert len(flag)<32
print("Enter your function A:")
if level==1:
fun_A=input_function(100,1000)
else:
fun_A=input_function(10,500)
print("Enter your function B:")
fun_B=input_function(10,500)
# first try some fake flags
B=[]
for i in range(5):
cur_res=run_commands(fun_A,{"A":bytes_to_long(b'TPCTF{'+bytes([random.randint(49,122) for i in range(24)])+b'}')})
B.append(cur_res["B"])
for i in range(5):
cur_res=run_commands(fun_A,{"A":bytes_to_long(bytes([random.randint(49,122) for i in range(24)]))})
B.append(cur_res["B"])
assert len(set(B))==10, "don't cheat"
flag_array=list(flag.encode()) # the flag is static
A=[]
B=[]
C=[]
for i in range(100):
cur_A=bytes_to_long(bytes(flag_array))
cur_res=run_commands(fun_A,{"A":cur_A})
A.append(cur_A)
B.append(cur_res["B"])
C.append(cur_res["C"])
if i<=10:
flag_array_inner=flag_array[6:-1]
random.shuffle(flag_array_inner)
flag_array[6:-1]=flag_array_inner
else:
random.shuffle(flag_array)
if level==1:
target_B=bytes_to_long(bytes(sorted(flag_array)))
if [target_B]==list(set(B)):
print(flag)
else:
print("You did not sort correctly")
exit(0)
assert len(set(B))==1, "results are not same"
assert max(C).bit_length()<=120, "result too long"
for i in range(100):
assert A[i]==run_commands(fun_B,{"B":B[i],"C":C[i]})["A"]
C0=str(C[0])
print("Here is your gift:")
print("B =",B[0])
print("C =",C0[:3]+'*'*(len(C0)-3))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/crypto/sort_level_2/sort.py | ctfs/TPCTF/2023/crypto/sort_level_2/sort.py | import re
from Crypto.Util.number import bytes_to_long
import random
letters=set(bytes(range(65,91)).decode())
class Command:
def __init__(self, target_var, op, l, r=0):
self.target_var = target_var
self.op = op
self.l = l if l in letters else int(l)
self.r = r if r in letters else int(r)
def __str__(self):
return self.target_var+"="+str(self.l)+((self.op+str(self.r)) if self.op!="=" else "")
__repr__=__str__
class Computation:
def __init__(self):
self.vars={x:0 for x in letters}
def resolve_val(self,symbol):
return self.vars[symbol] if type(symbol)==str else symbol
def run(self,cmd):
if cmd.op=='+':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)+self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='-':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)-self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='*':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)*self.resolve_val(cmd.r)
if self.vars[cmd.target_var].bit_length()>100000:
raise OverflowError
elif cmd.op=='/':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)//self.resolve_val(cmd.r)
elif cmd.op=='%':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)%self.resolve_val(cmd.r)
elif cmd.op=='&':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)&self.resolve_val(cmd.r)
elif cmd.op=='|':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)|self.resolve_val(cmd.r)
elif cmd.op=='^':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)^self.resolve_val(cmd.r)
elif cmd.op=='<':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<self.resolve_val(cmd.r))
elif cmd.op=='>':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>self.resolve_val(cmd.r))
elif cmd.op=='<=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<=self.resolve_val(cmd.r))
elif cmd.op=='>=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>=self.resolve_val(cmd.r))
elif cmd.op=='!=':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)!=self.resolve_val(cmd.r))
elif cmd.op=='==':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)==self.resolve_val(cmd.r))
elif cmd.op=='<<':
if self.resolve_val(cmd.l).bit_length()+self.resolve_val(cmd.r)>100000:
raise OverflowError
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)<<self.resolve_val(cmd.r))
elif cmd.op=='>>':
self.vars[cmd.target_var]=int(self.resolve_val(cmd.l)>>self.resolve_val(cmd.r))
elif cmd.op=='=':
self.vars[cmd.target_var]=self.resolve_val(cmd.l)
def parse_command(cmdstr):
cmdstr=re.sub("\s","",cmdstr)
m=re.match("^([A-Z])=([A-Z]|-?\d+)$",cmdstr)
if m:
return Command(m[1],"=",m[2])
m=re.match("^([A-Z])=([A-Z]|-?\d+)([+\-*/%&|^><]|[><!=]=|<<|>>)([A-Z]|-?\d+)$",cmdstr)
if m:
return Command(m[1],m[3],m[2],m[4])
m=re.match("^([A-Z])=-([A-Z])$",cmdstr)
if m:
return Command(m[1],"-",0,m[2])
raise SyntaxError
def run_commands(fun, init_state):
comp=Computation()
comp.vars.update(init_state)
try:
for i in fun:
comp.run(i)
except Exception as e:
pass # exceptions are suppressed
return comp.vars
def input_function(line_limit, cmd_limit):
fun=[]
while True:
line = input().strip()
if line == "EOF":
break
if len(line)>line_limit:
assert False, "command too long"
fun.append(parse_command(line))
if len(fun)>cmd_limit:
assert False, "too many commands"
return fun
level=int(input("Level: "))
assert level in [1,2]
flag=open(f"flag{level}.txt").read().strip()
assert len(flag)<32
print("Enter your function A:")
if level==1:
fun_A=input_function(100,1000)
else:
fun_A=input_function(10,500)
print("Enter your function B:")
fun_B=input_function(10,500)
# first try some fake flags
B=[]
for i in range(5):
cur_res=run_commands(fun_A,{"A":bytes_to_long(b'TPCTF{'+bytes([random.randint(49,122) for i in range(24)])+b'}')})
B.append(cur_res["B"])
for i in range(5):
cur_res=run_commands(fun_A,{"A":bytes_to_long(bytes([random.randint(49,122) for i in range(24)]))})
B.append(cur_res["B"])
assert len(set(B))==10, "don't cheat"
flag_array=list(flag.encode()) # the flag is static
A=[]
B=[]
C=[]
for i in range(100):
cur_A=bytes_to_long(bytes(flag_array))
cur_res=run_commands(fun_A,{"A":cur_A})
A.append(cur_A)
B.append(cur_res["B"])
C.append(cur_res["C"])
if i<=10:
flag_array_inner=flag_array[6:-1]
random.shuffle(flag_array_inner)
flag_array[6:-1]=flag_array_inner
else:
random.shuffle(flag_array)
if level==1:
target_B=bytes_to_long(bytes(sorted(flag_array)))
if [target_B]==list(set(B)):
print(flag)
else:
print("You did not sort correctly")
exit(0)
assert len(set(B))==1, "results are not same"
assert max(C).bit_length()<=120, "result too long"
for i in range(100):
assert A[i]==run_commands(fun_B,{"B":B[i],"C":C[i]})["A"]
C0=str(C[0])
print("Here is your gift:")
print("B =",B[0])
print("C =",C0[:3]+'*'*(len(C0)-3))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/manage.py | ctfs/TPCTF/2023/web/ezsqli/manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ezsqli.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/ezsqli/asgi.py | ctfs/TPCTF/2023/web/ezsqli/ezsqli/asgi.py | """
ASGI config for ezsqli project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ezsqli.settings')
application = get_asgi_application()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/ezsqli/settings.py | ctfs/TPCTF/2023/web/ezsqli/ezsqli/settings.py | """
Django settings for ezsqli project.
Generated by 'django-admin startproject' using Django 4.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'REDACTED'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
'blog',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ezsqli.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ezsqli.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/ezsqli/__init__.py | ctfs/TPCTF/2023/web/ezsqli/ezsqli/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/ezsqli/wsgi.py | ctfs/TPCTF/2023/web/ezsqli/ezsqli/wsgi.py | """
WSGI config for ezsqli project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ezsqli.settings')
application = get_wsgi_application()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/ezsqli/urls.py | ctfs/TPCTF/2023/web/ezsqli/ezsqli/urls.py | """
URL configuration for ezsqli project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path("search/", views.search, name="index"),
path("debug/", views.debug, name="debug"),
path("", views.index, name="index"),
]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/views.py | ctfs/TPCTF/2023/web/ezsqli/blog/views.py | from django.shortcuts import render
from django.db import connection
# Create your views here.
from django.http import HttpResponse,HttpRequest
from .models import AdminUser,Blog,QueryHelper
def index(request:HttpRequest):
return HttpResponse('Welcome to TPCTF')
def debug(request:HttpRequest):
if request.method != 'POST':
return HttpResponse('Welcome to TPCTF')
username = request.POST.get('username')
if username != 'admin':
return HttpResponse('you are not admin.')
password = request.POST.get('password')
users:AdminUser = AdminUser.objects.raw("SELECT * FROM blog_adminuser WHERE username='%s' and password ='%s'" % (username,password))
try:
assert password == users[0].password
q = QueryHelper(query="select flag from flag",debug=True,debug_sql="select sqlite_version()")
response = q.run_debug()
return HttpResponse(response)
except:
return HttpResponse('wrong password')
def search(request:HttpRequest):
try:
query_helper = QueryHelper("SELECT * FROM blog_blog WHERE id=%s",**request.GET.dict())
result = query_helper.run(Blog)[0]
return HttpResponse(result.content)
except Exception as e:
return HttpResponse('你来到了没有知识的荒原')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/admin.py | ctfs/TPCTF/2023/web/ezsqli/blog/admin.py | from django.contrib import admin
# Register your models here.
from .models import AdminUser,Blog
admin.site.register(AdminUser)
admin.site.register(Blog)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/models.py | ctfs/TPCTF/2023/web/ezsqli/blog/models.py | from django.db import models
from django.db import connection
class AdminUser(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=20)
class Blog(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=20)
content = models.TextField()
class QueryHelper:
debug_query = []
query = ""
def __init__(self,query,**kwargs):
self.query = query
print(kwargs)
if kwargs.get("debug"):
self.debug_query.append(kwargs.get("debug_sql"))
self.parameters = kwargs.get("params")
print(self.debug_query)
def run(self,obj):
return obj.objects.raw(self.query,self.parameters)
def append_debug_sql(self,sql):
self.debug_query.append(sql)
def run_debug(self):
response = ""
print(self.debug_query)
with connection.cursor() as cursor:
cursor.execute(self.debug_query[0])
result = cursor.fetchone()
response += str(result)
return response
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/__init__.py | ctfs/TPCTF/2023/web/ezsqli/blog/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/tests.py | ctfs/TPCTF/2023/web/ezsqli/blog/tests.py | from django.test import TestCase
# Create your tests here.
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/apps.py | ctfs/TPCTF/2023/web/ezsqli/blog/apps.py | from django.apps import AppConfig
class BlogConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'blog'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/migrations/0001_initial.py | ctfs/TPCTF/2023/web/ezsqli/blog/migrations/0001_initial.py | # Generated by Django 4.2.7 on 2023-11-15 16:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AdminUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=20)),
('password', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Blog',
fields=[
('id', models.IntegerField(primary_key=True, serialize=False)),
('title', models.CharField(max_length=20)),
('content', models.TextField()),
],
),
]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/ezsqli/blog/migrations/__init__.py | ctfs/TPCTF/2023/web/ezsqli/blog/migrations/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/xssbot/bot.py | ctfs/TPCTF/2023/web/xssbot/bot.py | # Copyright 2022-2023 USTC-Hackergame
# Copyright 2021 PKU-GeekGame
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from selenium import webdriver
import selenium
import time
import os
import subprocess
import urllib.parse
import random
import re
import atexit
# Stage 1
file_name=input("File name: ").strip()
assert re.match("[a-z]+\.[a-z]+",file_name) and len(file_name)<10
print("Input your file:")
code = ""
while True:
line = input()
if line == "EOF":
break
code += line + "\n"
if len(code) > 1024 * 5:
print("The file can not be larger than 5KB")
exit(1)
try:
os.mkdir("/dev/shm/xss-data")
except Exception as e:
pass
user_id=os.urandom(8).hex()
try:
os.mkdir("/dev/shm/xss-data/"+user_id)
except Exception as e:
pass
try:
os.mkdir("/dev/shm/chromium-data")
except Exception as e:
pass
with open("/dev/shm/xss-data/"+user_id+"/"+file_name, "w") as f:
f.write(code)
port_id=str(random.randint(30000,50000))
sp = subprocess.Popen(
["python3", "-m", "http.server", "-b", "127.0.0.1", port_id], cwd="/dev/shm/xss-data/"+user_id,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
time.sleep(1)
if sp.poll() is not None:
print("Failed to start HTTP server, please try again in a moment")
exit(1)
def cleanup():
try:
os.rmdir("/dev/shm/xss-data/"+user_id)
except Exception as e:
pass
try:
sp.kill()
except Exception as e:
pass
atexit.register(cleanup)
# Stage 2
try:
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox") # sandbox not working in docker
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--user-data-dir=/dev/shm/user-data/"+user_id)
os.environ["TMPDIR"] = "/dev/shm/chromium-data/"
options.add_experimental_option("excludeSwitches", ["enable-logging"])
with webdriver.Chrome(options=options) as driver:
ua = driver.execute_script("return navigator.userAgent")
print(" I am using", ua)
driver.set_page_load_timeout(15)
print("- Now browsing your website...")
driver.get("http://localhost:"+port_id+"/"+file_name)
time.sleep(4)
print("Bye bye!")
except Exception as e:
print("ERROR", type(e))
print("I'll not give you exception message this time.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TPCTF/2023/web/xssbot_but_no_Internet/bot.py | ctfs/TPCTF/2023/web/xssbot_but_no_Internet/bot.py | # Copyright 2022-2023 USTC-Hackergame
# Copyright 2021 PKU-GeekGame
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from selenium import webdriver
import selenium
import time
import os
import subprocess
import urllib.parse
import random
import re
import atexit
# Stage 1
file_name=input("File name: ").strip()
assert re.match("[a-z]+\.[a-z]+",file_name) and len(file_name)<10
print("Input your file:")
code = ""
while True:
line = input()
if line == "EOF":
break
code += line + "\n"
if len(code) > 1024 * 5:
print("The file can not be larger than 5KB")
exit(1)
try:
os.mkdir("/dev/shm/xss-data")
except Exception as e:
pass
user_id=os.urandom(8).hex()
try:
os.mkdir("/dev/shm/xss-data/"+user_id)
except Exception as e:
pass
try:
os.mkdir("/dev/shm/chromium-data")
except Exception as e:
pass
with open("/dev/shm/xss-data/"+user_id+"/"+file_name, "w") as f:
f.write(code)
port_id=str(random.randint(30000,50000))
sp = subprocess.Popen(
["python3", "-m", "http.server", "-b", "127.0.0.1", port_id], cwd="/dev/shm/xss-data/"+user_id,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
time.sleep(1)
if sp.poll() is not None:
print("Failed to start HTTP server, please try again in a moment")
exit(1)
def cleanup():
try:
os.rmdir("/dev/shm/xss-data/"+user_id)
except Exception as e:
pass
try:
sp.kill()
except Exception as e:
pass
atexit.register(cleanup)
# Stage 2
try:
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox") # sandbox not working in docker
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--user-data-dir=/dev/shm/user-data/"+user_id)
os.environ["TMPDIR"] = "/dev/shm/chromium-data/"
options.add_experimental_option("excludeSwitches", ["enable-logging"])
with webdriver.Chrome(options=options) as driver:
ua = driver.execute_script("return navigator.userAgent")
print(" I am using", ua)
driver.set_page_load_timeout(15)
print("- Now browsing your website...")
driver.get("http://localhost:"+port_id+"/"+file_name)
time.sleep(4)
print("Bye bye!")
except Exception as e:
print("ERROR", type(e))
print("I'll not give you exception message this time.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/misc/ScavengerHunt/prob.py | ctfs/WACON/2023/Quals/misc/ScavengerHunt/prob.py | #!/usr/bin/env python3
import secret
import pyseccomp
import sys
print("Find the treasure!")
data = input()
f = pyseccomp.SyscallFilter(defaction=pyseccomp.KILL)
f.add_rule(pyseccomp.ALLOW, 'rt_sigaction')
f.add_rule(pyseccomp.ALLOW, 'munmap')
f.add_rule(pyseccomp.ALLOW, 'exit_group')
f.add_rule(pyseccomp.ALLOW, 'exit')
f.add_rule(pyseccomp.ALLOW, 'brk')
f.load()
del pyseccomp
del f
del sys
__builtins__ = {}
try:
eval(data, {'__builtins__': {}}, {'__builtins__': {}})
except:
pass
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/misc/ScavengerHunt/secret.py | ctfs/WACON/2023/Quals/misc/ScavengerHunt/secret.py | __builtins__ = {}
some_unknown_and_very_long_identifier_name = "WACON2023{[REDACTED]}"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/rev/Adult_Artist/flag.py | ctfs/WACON/2023/Quals/rev/Adult_Artist/flag.py | import sys
import hashlib
if len(sys.argv) != 2:
print("python3 flag.py <input>")
exit()
print("WACON2023{" + hashlib.sha256(sys.argv[1].encode()).hexdigest() + "}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/Cry/challenge.py | ctfs/WACON/2023/Quals/crypto/Cry/challenge.py | from Crypto.Util.number import bytes_to_long, getStrongPrime, isPrime
SIZE = 512
e = 65537
with open("flag.txt", "rb") as f:
m = bytes_to_long(f.read())
def encrypt(m):
while True:
p = getStrongPrime(SIZE)
if p % 4 != 3:
continue
q = p**2 + 1
assert q % 2 == 0
if isPrime(q // 2):
break
r = getStrongPrime(SIZE * 3)
n = p * q * r
c = pow(m, e, n)
return n, c
if __name__ == "__main__":
n0, c0 = encrypt(m)
n1, c1 = encrypt(c0)
n2, c = encrypt(c1)
assert m < n0 and c0 < n1 and c1 < n2
print(f"{n0 = }")
print(f"{n1 = }")
print(f"{n2 = }")
print(f"{c = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_hard/RandomFunction.py | ctfs/WACON/2023/Quals/crypto/White_arts_hard/RandomFunction.py | import os
class RandomFunction():
def __init__(self, n):
self.domain_cache = {}
self.range_cache = {}
self.n = n # n "bytes"
# Inverse query is not allowed
def query(self, q):
x = q
if x not in self.domain_cache:
self.domain_cache[x] = os.urandom(self.n)
return self.domain_cache[x] | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_hard/RandomPermutation.py | ctfs/WACON/2023/Quals/crypto/White_arts_hard/RandomPermutation.py | import os
class RandomPermutation():
def __init__(self, n):
self.domain_cache = {}
self.range_cache = {}
self.n = n # n "bytes"
def query(self, q, inverse = False):
if not inverse:
x = q
if x in self.domain_cache:
return self.domain_cache[x]
while True:
y = os.urandom(self.n)
if y in self.range_cache:
continue
self.domain_cache[x] = y
self.range_cache[y] = x
return y
else:
y = q
if y in self.range_cache:
return self.range_cache[y]
while True:
x = os.urandom(self.n)
if x in self.domain_cache:
continue
self.domain_cache[x] = y
self.range_cache[y] = x
return x | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_hard/prob.py | ctfs/WACON/2023/Quals/crypto/White_arts_hard/prob.py | import math
import os
from Generator import Generator1, Generator2, Generator3, Generator4, Generator5
query_left = 266
def guess_mode(G, query_num):
for _ in range(query_num):
q = bytes.fromhex(input("q? > "))
inverse = input("inverse(y/n)? > ") == 'y'
assert len(q) == G.input_size
print(G.calc(q, inverse).hex())
# Time to guess
assert input("mode? > ") == str(G.mode) # 0(gen) / 1(random)
def challenge_generator(challenge_name, Generator):
global query_left
print(f"#### Challenge = {challenge_name}")
query_num = int(input(f"How many queries are required to solve {challenge_name}? > "))
query_left -= query_num
for _ in range(40):
G = Generator()
guess_mode(G, query_num)
challenge_generator("Generator1", Generator1)
challenge_generator("Generator2", Generator2)
if query_left < 0:
print("You passed all challenges for EASY but query limit exceeded. Try harder :(")
exit(-1)
print("(Only for a junior division) Good job! flag_baby =", open("flag_baby.txt").read())
challenge_generator("Generator3", Generator3)
if query_left < 0:
print("You passed all challenges for EASY but query limit exceeded. Try harder :(")
exit(-1)
print("Good job! flag_easy =", open("flag_easy.txt").read())
challenge_generator("Generator4", Generator4)
challenge_generator("Generator5", Generator5)
if query_left < 0:
print("You passed all challenges for HARD but query limit exceeded. Try harder :(")
exit(-1)
print("(Only for general/global divisions) Good job! flag_hard =", open("flag_hard.txt").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_hard/Generator.py | ctfs/WACON/2023/Quals/crypto/White_arts_hard/Generator.py | import os
from RandomFunction import RandomFunction
from RandomPermutation import RandomPermutation
def xor(a : bytes, b : bytes):
return bytes([u ^ v for u,v in zip(a,b)])
class Generator1:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomFunction(self.n)
self.RF_random = RandomFunction(2 * self.n)
def func_gen(self, q):
L, R = q[:self.n], q[self.n:]
L, R = R, xor(L, self.RF_gen.query(R))
return L+R
def func_random(self, q):
return self.RF_random.query(q)
def calc(self, q, inverse):
assert inverse == False, "inverse query is not allowed for Generator1"
ret_gen = self.func_gen(q)
ret_random = self.func_random(q)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator2:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomFunction(self.n)
self.RF_random = RandomFunction(2 * self.n)
def func_gen(self, q):
L, R = q[:self.n], q[self.n:]
L, R = R, xor(L, self.RF_gen.query(R))
L, R = R, xor(L, self.RF_gen.query(R))
return L+R
def func_random(self, q):
return self.RF_random.query(q)
def calc(self, q, inverse):
assert inverse == False, "inverse query is not allowed for Generator2"
ret_gen = self.func_gen(q)
ret_random = self.func_random(q)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator3:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomFunction(self.n)
self.RF_random = RandomPermutation(2 * self.n)
def func_gen(self, q, inverse):
if not inverse:
L, R = q[:self.n], q[self.n:]
L, R = R, xor(L, self.RF_gen.query(R))
L, R = R, xor(L, self.RF_gen.query(R))
L, R = R, xor(L, self.RF_gen.query(R))
else:
L, R = q[:self.n], q[self.n:]
L, R = xor(R, self.RF_gen.query(L)), L
L, R = xor(R, self.RF_gen.query(L)), L
L, R = xor(R, self.RF_gen.query(L)), L
return L+R
def func_random(self, q, inverse):
return self.RF_random.query(q, inverse)
def calc(self, q, inverse):
ret_gen = self.func_gen(q, inverse)
ret_random = self.func_random(q, inverse)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator4:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomPermutation(self.n)
self.RF_random = RandomPermutation(2 * self.n)
def func_gen(self, q, inverse):
X, T = q[:self.n], q[self.n:]
X = xor(X, T)
X = self.RF_gen.query(X, inverse)
X = xor(X, T)
X = self.RF_gen.query(X, inverse)
X = xor(X, T)
return X
def func_random(self, q, inverse):
return self.RF_random.query(q, inverse)[:self.n]
def calc(self, q, inverse):
ret_gen = self.func_gen(q, inverse)
ret_random = self.func_random(q, inverse)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator5:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 1
self.input_size = self.n
self.RF_gen = [RandomPermutation(self.n) for _ in range(4)]
self.RF_random = RandomFunction(self.n)
def func_gen(self, q):
ret = bytes(1)
for i in range(4):
ret = xor(ret, self.RF_gen[i].query(q))
return ret
def func_random(self, q):
return self.RF_random.query(q)
def calc(self, q, inverse):
assert inverse == False, "inverse query is not allowed for Generator2"
ret_gen = self.func_gen(q)
ret_random = self.func_random(q)
if self.mode == 0:
return ret_gen
else:
return ret_random | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/Push_It_To_The_Limit/challenge.py | ctfs/WACON/2023/Quals/crypto/Push_It_To_The_Limit/challenge.py | from Crypto.Util.number import bytes_to_long, getStrongPrime
with open("flag.txt", "rb") as f:
m = bytes_to_long(f.read())
SIZE = 1024
p = getStrongPrime(SIZE)
q = getStrongPrime(SIZE)
n = p * q
e = 0x10001
c = pow(m, e, n)
p_msb = p - p % (2 ** (SIZE // 2))
print(f"{n = }")
print(f"{c = }")
print(f"{p_msb = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_easy/RandomFunction.py | ctfs/WACON/2023/Quals/crypto/White_arts_easy/RandomFunction.py | import os
class RandomFunction():
def __init__(self, n):
self.domain_cache = {}
self.range_cache = {}
self.n = n # n "bytes"
# Inverse query is not allowed
def query(self, q):
x = q
if x not in self.domain_cache:
self.domain_cache[x] = os.urandom(self.n)
return self.domain_cache[x] | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_easy/RandomPermutation.py | ctfs/WACON/2023/Quals/crypto/White_arts_easy/RandomPermutation.py | import os
class RandomPermutation():
def __init__(self, n):
self.domain_cache = {}
self.range_cache = {}
self.n = n # n "bytes"
def query(self, q, inverse = False):
if not inverse:
x = q
if x in self.domain_cache:
return self.domain_cache[x]
while True:
y = os.urandom(self.n)
if y in self.range_cache:
continue
self.domain_cache[x] = y
self.range_cache[y] = x
return y
else:
y = q
if y in self.range_cache:
return self.range_cache[y]
while True:
x = os.urandom(self.n)
if x in self.domain_cache:
continue
self.domain_cache[x] = y
self.range_cache[y] = x
return x | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_easy/prob.py | ctfs/WACON/2023/Quals/crypto/White_arts_easy/prob.py | import math
import os
from Generator import Generator1, Generator2, Generator3, Generator4, Generator5
query_left = 266
def guess_mode(G, query_num):
for _ in range(query_num):
q = bytes.fromhex(input("q? > "))
inverse = input("inverse(y/n)? > ") == 'y'
assert len(q) == G.input_size
print(G.calc(q, inverse).hex())
# Time to guess
assert input("mode? > ") == str(G.mode) # 0(gen) / 1(random)
def challenge_generator(challenge_name, Generator):
global query_left
print(f"#### Challenge = {challenge_name}")
query_num = int(input(f"How many queries are required to solve {challenge_name}? > "))
query_left -= query_num
for _ in range(40):
G = Generator()
guess_mode(G, query_num)
challenge_generator("Generator1", Generator1)
challenge_generator("Generator2", Generator2)
if query_left < 0:
print("You passed all challenges for EASY but query limit exceeded. Try harder :(")
exit(-1)
print("(Only for a junior division) Good job! flag_baby =", open("flag_baby.txt").read())
challenge_generator("Generator3", Generator3)
if query_left < 0:
print("You passed all challenges for EASY but query limit exceeded. Try harder :(")
exit(-1)
print("Good job! flag_easy =", open("flag_easy.txt").read())
challenge_generator("Generator4", Generator4)
challenge_generator("Generator5", Generator5)
if query_left < 0:
print("You passed all challenges for HARD but query limit exceeded. Try harder :(")
exit(-1)
print("(Only for general/global divisions) Good job! flag_hard =", open("flag_hard.txt").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WACON/2023/Quals/crypto/White_arts_easy/Generator.py | ctfs/WACON/2023/Quals/crypto/White_arts_easy/Generator.py | import os
from RandomFunction import RandomFunction
from RandomPermutation import RandomPermutation
def xor(a : bytes, b : bytes):
return bytes([u ^ v for u,v in zip(a,b)])
class Generator1:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomFunction(self.n)
self.RF_random = RandomFunction(2 * self.n)
def func_gen(self, q):
L, R = q[:self.n], q[self.n:]
L, R = R, xor(L, self.RF_gen.query(R))
return L+R
def func_random(self, q):
return self.RF_random.query(q)
def calc(self, q, inverse):
assert inverse == False, "inverse query is not allowed for Generator1"
ret_gen = self.func_gen(q)
ret_random = self.func_random(q)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator2:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomFunction(self.n)
self.RF_random = RandomFunction(2 * self.n)
def func_gen(self, q):
L, R = q[:self.n], q[self.n:]
L, R = R, xor(L, self.RF_gen.query(R))
L, R = R, xor(L, self.RF_gen.query(R))
return L+R
def func_random(self, q):
return self.RF_random.query(q)
def calc(self, q, inverse):
assert inverse == False, "inverse query is not allowed for Generator2"
ret_gen = self.func_gen(q)
ret_random = self.func_random(q)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator3:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomFunction(self.n)
self.RF_random = RandomPermutation(2 * self.n)
def func_gen(self, q, inverse):
if not inverse:
L, R = q[:self.n], q[self.n:]
L, R = R, xor(L, self.RF_gen.query(R))
L, R = R, xor(L, self.RF_gen.query(R))
L, R = R, xor(L, self.RF_gen.query(R))
else:
L, R = q[:self.n], q[self.n:]
L, R = xor(R, self.RF_gen.query(L)), L
L, R = xor(R, self.RF_gen.query(L)), L
L, R = xor(R, self.RF_gen.query(L)), L
return L+R
def func_random(self, q, inverse):
return self.RF_random.query(q, inverse)
def calc(self, q, inverse):
ret_gen = self.func_gen(q, inverse)
ret_random = self.func_random(q, inverse)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator4:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 8
self.input_size = 2 * self.n
self.RF_gen = RandomPermutation(self.n)
self.RF_random = RandomPermutation(2 * self.n)
def func_gen(self, q, inverse):
X, T = q[:self.n], q[self.n:]
X = xor(X, T)
X = self.RF_gen.query(X, inverse)
X = xor(X, T)
X = self.RF_gen.query(X, inverse)
X = xor(X, T)
return X
def func_random(self, q, inverse):
return self.RF_random.query(q, inverse)[:self.n]
def calc(self, q, inverse):
ret_gen = self.func_gen(q, inverse)
ret_random = self.func_random(q, inverse)
if self.mode == 0:
return ret_gen
else:
return ret_random
class Generator5:
def __init__(self):
self.mode = os.urandom(1)[0] & 1
self.n = 1
self.input_size = self.n
self.RF_gen = [RandomPermutation(self.n) for _ in range(4)]
self.RF_random = RandomFunction(self.n)
def func_gen(self, q):
ret = bytes(1)
for i in range(4):
ret = xor(ret, self.RF_gen[i].query(q))
return ret
def func_random(self, q):
return self.RF_random.query(q)
def calc(self, q, inverse):
assert inverse == False, "inverse query is not allowed for Generator2"
ret_gen = self.func_gen(q)
ret_random = self.func_random(q)
if self.mode == 0:
return ret_gen
else:
return ret_random | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.