code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def index() -> Response:
"""Main page of flag service"""
# Users can't see this anyways so there is no need to beautify it
# TODO Create html for the page
return jsonify({"message": "Welcome to the homepage"}) | Main page of flag service | index | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/flag_page/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/flag_page/app.py | MIT |
def flag() -> Response:
"""Flag endpoint for the service"""
return jsonify({"message": f"This is the flag: {FLAG}"}) | Flag endpoint for the service | flag | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/flag_page/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/flag_page/app.py | MIT |
def is_safe_url(target):
"""Check if the target URL is safe to redirect to. Only works for within Flask request context."""
ref_url = urlparse(request.host_url)
test_url = urlparse(urljoin(request.host_url, target))
return test_url.scheme in ('http', 'https') and \
ref_url.netloc == test_url.netloc | Check if the target URL is safe to redirect to. Only works for within Flask request context. | is_safe_url | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/utils.py | MIT |
def is_admin() -> bool:
"""Check if the user is an admin"""
return request.cookies.get('cookie') == ADMIN_COOKIE | Check if the user is an admin | is_admin | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | MIT |
def url(id: int) -> Response:
"""Redirect to the url in post if its sanitized"""
url = Url.query.get_or_404(id)
return redirect(url.url) | Redirect to the url in post if its sanitized | url | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | MIT |
def sanitize_content(content: str) -> str:
"""Sanitize the content of the post"""
# Replace URLs with in house url tracker
urls = re.findall(URL_REGEX, content)
for url in urls:
url = url[0]
url_obj = Url(url=url)
db.session.add(url_obj)
content = content.replace(url, f"/url/{url_obj.id}")
return content | Sanitize the content of the post | sanitize_content | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | MIT |
def send_post() -> Response:
"""Send a post to the admin"""
if request.method == 'GET':
return render_template('send_post.html')
url = request.form.get('url', '/')
title = request.form.get('title', None)
content = request.form.get('content', None)
if None in (url, title, content):
flash('Please fill all fields', 'danger')
return redirect(url_for('send_post'))
# Bot visit
url_value = make_post(url, title, content)
flash('Post sent successfully', 'success')
flash('Url id: ' + str(url_value), 'info')
return redirect('/send_post') | Send a post to the admin | send_post | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | MIT |
def make_post(url: str, title: str, user_content: str) -> int:
"""Make a post to the admin"""
with requests.Session() as s:
visit_url = f"{BASE_URL}/login?next={url}"
resp = s.get(visit_url, timeout=10)
content = resp.content.decode('utf-8')
# Login routine (If website is buggy we run it again.)
for _ in range(2):
print('Logging in... at:', resp.url, file=sys.stderr)
if "bot_login" in content:
# Login routine
resp = s.post(resp.url, data={
'username': 'admin',
'password': FLAG,
})
# Make post
resp = s.post(f"{resp.url}/post", data={
'title': title,
'content': user_content,
})
return db.session.query(Url).count() | Make a post to the admin | make_post | python | sajjadium/ctf-archives | ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py | MIT |
def SkToPk(cls, privkey: int) -> BLSPubkey:
"""
The SkToPk algorithm takes a secret key SK and outputs the
corresponding public key PK.
Raise `ValidationError` when there is input validation error.
"""
try:
# Inputs validation
assert cls._is_valid_privkey(privkey)
except Exception as e:
raise ValidationError(e)
# Procedure
return G1_to_pubkey(multiply(G1, privkey)) | The SkToPk algorithm takes a secret key SK and outputs the
corresponding public key PK.
Raise `ValidationError` when there is input validation error. | SkToPk | python | sajjadium/ctf-archives | ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | MIT |
def _CoreSign(cls, SK: int, message: bytes, DST: bytes) -> BLSSignature:
"""
The CoreSign algorithm computes a signature from SK, a secret key,
and message, an octet string.
Raise `ValidationError` when there is input validation error.
"""
try:
# Inputs validation
assert cls._is_valid_privkey(SK)
assert cls._is_valid_message(message)
except Exception as e:
raise ValidationError(e)
# Procedure
message_point = hash_to_G2(message, DST, cls.xmd_hash_function)
signature_point = multiply(message_point, SK)
return G2_to_signature(signature_point) | The CoreSign algorithm computes a signature from SK, a secret key,
and message, an octet string.
Raise `ValidationError` when there is input validation error. | _CoreSign | python | sajjadium/ctf-archives | ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | MIT |
def Aggregate(cls, signatures: Sequence[BLSSignature]) -> BLSSignature:
"""
The Aggregate algorithm aggregates multiple signatures into one.
Raise `ValidationError` when there is input validation error.
"""
try:
# Inputs validation
for signature in signatures:
assert cls._is_valid_signature(signature)
# Preconditions
assert len(signatures) >= 1
except Exception as e:
raise ValidationError(e)
# Procedure
aggregate = Z2 # Seed with the point at infinity
for signature in signatures:
signature_point = signature_to_G2(signature)
aggregate = add(aggregate, signature_point)
return G2_to_signature(aggregate) | The Aggregate algorithm aggregates multiple signatures into one.
Raise `ValidationError` when there is input validation error. | Aggregate | python | sajjadium/ctf-archives | ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | MIT |
def _is_valid_pubkey(cls, pubkey: bytes) -> bool:
"""
Note: PopVerify is a precondition for -Verify APIs
However, it's difficult to verify it with the API interface in runtime.
To ensure KeyValidate has been checked, we check it in the input validation.
See https://github.com/cfrg/draft-irtf-cfrg-bls-signature/issues/27 for the discussion.
"""
if not super()._is_valid_pubkey(pubkey):
return False
return cls.KeyValidate(BLSPubkey(pubkey)) | Note: PopVerify is a precondition for -Verify APIs
However, it's difficult to verify it with the API interface in runtime.
To ensure KeyValidate has been checked, we check it in the input validation.
See https://github.com/cfrg/draft-irtf-cfrg-bls-signature/issues/27 for the discussion. | _is_valid_pubkey | python | sajjadium/ctf-archives | ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | MIT |
def _AggregatePKs(PKs: Sequence[BLSPubkey]) -> BLSPubkey:
"""
Aggregate the public keys.
Raise `ValidationError` when there is input validation error.
"""
try:
assert len(PKs) >= 1, 'Insufficient number of PKs. (n < 1)'
except Exception as e:
raise ValidationError(e)
aggregate = Z1 # Seed with the point at infinity
for pk in PKs:
pubkey_point = pubkey_to_G1(pk)
aggregate = add(aggregate, pubkey_point)
return G1_to_pubkey(aggregate) | Aggregate the public keys.
Raise `ValidationError` when there is input validation error. | _AggregatePKs | python | sajjadium/ctf-archives | ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py | MIT |
def __init__(self,T,R):
'''
Inputs:
T -- Transition function: |A| x |S| x |S'| array
R -- Reward function: |A| x |S| array
'''
self.nActions = T.shape[0]
self.nStates = T.shape[1]
self.T = T
self.R = R
self.discount = 0.99 | Inputs:
T -- Transition function: |A| x |S| x |S'| array
R -- Reward function: |A| x |S| array | __init__ | python | sajjadium/ctf-archives | ctfs/TU/2023/programming/CaRLsLabrinth/maze.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TU/2023/programming/CaRLsLabrinth/maze.py | MIT |
def sampleRewardAndNextState(self,state,action):
'''
state -- current state
action -- action to be executed
reward -- sampled reward
nextState -- sampled next state
'''
reward = self.R[action,state]
nextState = np.argmax(np.random.multinomial(1,self.T[action,state,:]))
return [reward,nextState] | state -- current state
action -- action to be executed
reward -- sampled reward
nextState -- sampled next state | sampleRewardAndNextState | python | sajjadium/ctf-archives | ctfs/TU/2023/programming/CaRLsLabrinth/maze.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TU/2023/programming/CaRLsLabrinth/maze.py | MIT |
def main():
rsa = RSA()
print(f"p = {rsa.p}")
print(f"e = {rsa.e}")
c = rsa.encrypt(bytes_to_long(flag))
print('c = ', c)
'''
p = 11545307730112922786664290405312669819594345207377186481347514368962838475959085036399074594822885814719354871659183685801279739518405830244888530641898849
e = 65537
c = 114894293598203268417380013863687165686775727976061560608696207173455730179934925684529986102237419507146768083815607566149240438056135058988227916482404733131796310418493418060300571541865427288945087911872630289527954636816219365941817260989104786329938318143577075200571833575709614521758701838099810751
''' | p = 11545307730112922786664290405312669819594345207377186481347514368962838475959085036399074594822885814719354871659183685801279739518405830244888530641898849
e = 65537
c = 114894293598203268417380013863687165686775727976061560608696207173455730179934925684529986102237419507146768083815607566149240438056135058988227916482404733131796310418493418060300571541865427288945087911872630289527954636816219365941817260989104786329938318143577075200571833575709614521758701838099810751 | main | python | sajjadium/ctf-archives | ctfs/TU/2022/crypto/MoreEffort/more_effort.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TU/2022/crypto/MoreEffort/more_effort.py | MIT |
def main():
inp = input("""
Welcome to the TU Image Program
It can convert images to TIMGs
It will also display TIGMs
[1] Convert Image to TIMG
[2] Display TIMG
""")
match inp:
case "1":
conv()
case "2":
display() #TODO: Add
'''
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠛⠛⠛⠋⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⠛⠿⠻⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠀⡀⠠⠤⠒⢂⣉⣉⣉⣑⣒⣒⠒⠒⠒⠒⠒⠒⠒⠀⠀⠐⠒⠚⠻⠿⠿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⠀⡠⠔⠉⣀⠔⠒⠉⣀⣀⠀⠀⠀⣀⡀⠈⠉⠑⠒⠒⠒⠒⠒⠈⠉⠉⠉⠁⠂⠀⠈⠙⢿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠔⠁⠠⠖⠡⠔⠊⠀⠀⠀⠀⠀⠀⠀⠐⡄⠀⠀⠀⠀⠀⠀⡄⠀⠀⠀⠀⠉⠲⢄⠀⠀⠀⠈⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⠋⠀⠀⠀⠀⠀⠀⠀⠊⠀⢀⣀⣤⣤⣤⣤⣀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠜⠀⠀⠀⠀⣀⡀⠀⠈⠃⠀⠀⠀⠸⣿⣿⣿⣿
⣿⣿⣿⣿⡿⠥⠐⠂⠀⠀⠀⠀⡄⠀⠰⢺⣿⣿⣿⣿⣿⣟⠀⠈⠐⢤⠀⠀⠀⠀⠀⠀⢀⣠⣶⣾⣯⠀⠀⠉⠂⠀⠠⠤⢄⣀⠙⢿⣿⣿
⣿⡿⠋⠡⠐⠈⣉⠭⠤⠤⢄⡀⠈⠀⠈⠁⠉⠁⡠⠀⠀⠀⠉⠐⠠⠔⠀⠀⠀⠀⠀⠲⣿⠿⠛⠛⠓⠒⠂⠀⠀⠀⠀⠀⠀⠠⡉⢢⠙⣿
⣿⠀⢀⠁⠀⠊⠀⠀⠀⠀⠀⠈⠁⠒⠂⠀⠒⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⢀⣀⡠⠔⠒⠒⠂⠀⠈⠀⡇⣿
⣿⠀⢸⠀⠀⠀⢀⣀⡠⠋⠓⠤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠄⠀⠀⠀⠀⠀⠀⠈⠢⠤⡀⠀⠀⠀⠀⠀⠀⢠⠀⠀⠀⡠⠀⡇⣿
⣿⡀⠘⠀⠀⠀⠀⠀⠘⡄⠀⠀⠀⠈⠑⡦⢄⣀⠀⠀⠐⠒⠁⢸⠀⠀⠠⠒⠄⠀⠀⠀⠀⠀⢀⠇⠀⣀⡀⠀⠀⢀⢾⡆⠀⠈⡀⠎⣸⣿
⣿⣿⣄⡈⠢⠀⠀⠀⠀⠘⣶⣄⡀⠀⠀⡇⠀⠀⠈⠉⠒⠢⡤⣀⡀⠀⠀⠀⠀⠀⠐⠦⠤⠒⠁⠀⠀⠀⠀⣀⢴⠁⠀⢷⠀⠀⠀⢰⣿⣿
⣿⣿⣿⣿⣇⠂⠀⠀⠀⠀⠈⢂⠀⠈⠹⡧⣀⠀⠀⠀⠀⠀⡇⠀⠀⠉⠉⠉⢱⠒⠒⠒⠒⢖⠒⠒⠂⠙⠏⠀⠘⡀⠀⢸⠀⠀⠀⣿⣿⣿
⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠑⠄⠰⠀⠀⠁⠐⠲⣤⣴⣄⡀⠀⠀⠀⠀⢸⠀⠀⠀⠀⢸⠀⠀⠀⠀⢠⠀⣠⣷⣶⣿⠀⠀⢰⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠁⢀⠀⠀⠀⠀⠀⡙⠋⠙⠓⠲⢤⣤⣷⣤⣤⣤⣤⣾⣦⣤⣤⣶⣿⣿⣿⣿⡟⢹⠀⠀⢸⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣧⡀⠀⠀⠀⠀⠀⠀⠀⠑⠀⢄⠀⡰⠁⠀⠀⠀⠀⠀⠈⠉⠁⠈⠉⠻⠋⠉⠛⢛⠉⠉⢹⠁⢀⢇⠎⠀⠀⢸⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣀⠈⠢⢄⡉⠂⠄⡀⠀⠈⠒⠢⠄⠀⢀⣀⣀⣰⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⢀⣎⠀⠼⠊⠀⠀⠀⠘⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⡀⠉⠢⢄⡈⠑⠢⢄⡀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠁⠀⠀⢀⠀⠀⠀⠀⠀⢻⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣀⡈⠑⠢⢄⡀⠈⠑⠒⠤⠄⣀⣀⠀⠉⠉⠉⠉⠀⠀⠀⣀⡀⠤⠂⠁⠀⢀⠆⠀⠀⢸⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣄⡀⠁⠉⠒⠂⠤⠤⣀⣀⣉⡉⠉⠉⠉⠉⢀⣀⣀⡠⠤⠒⠈⠀⠀⠀⠀⣸⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣶⣤⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣶⣶⣤⣤⣤⣤⣀⣀⣤⣤⣤⣶⣾⣿⣿⣿⣿⣿
'''
case _:
return 0
return 0 | )
match inp:
case "1":
conv()
case "2":
display() #TODO: Add | main | python | sajjadium/ctf-archives | ctfs/TU/2024/rev/Custom_Image_Generator/timg.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TU/2024/rev/Custom_Image_Generator/timg.py | MIT |
def receive_public(self, data):
"""
Remember to include the nonce for ultra-secure key exchange!
"""
Px = int(data["Px"])
Py = int(data["Py"])
self.recieved = Point(Px, Py, curve=secp256k1)
self.nonce = int(data['nonce']) | Remember to include the nonce for ultra-secure key exchange! | receive_public | python | sajjadium/ctf-archives | ctfs/Union/2021/crypto/human_server/human_server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/crypto/human_server/human_server.py | MIT |
def get_shared_secret(self):
"""
Generates the ultra secure secret with added nonce randomness
"""
assert self.nonce.bit_length() > 64
self.key = (self.recieved * self.private).x ^ self.nonce | Generates the ultra secure secret with added nonce randomness | get_shared_secret | python | sajjadium/ctf-archives | ctfs/Union/2021/crypto/human_server/human_server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/crypto/human_server/human_server.py | MIT |
def check_fingerprint(self, h2: str):
"""
If this is failing, remember that you must send the SAME
nonce to both Alice and Bob for the shared secret to match
"""
h1 = hashlib.sha256(long_to_bytes(self.key)).hexdigest()
return h1 == h2 | If this is failing, remember that you must send the SAME
nonce to both Alice and Bob for the shared secret to match | check_fingerprint | python | sajjadium/ctf-archives | ctfs/Union/2021/crypto/human_server/human_server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/crypto/human_server/human_server.py | MIT |
def check_my_users(user):
"""Check if user exists and its credentials.
Take a look at encrypt_app.py and encrypt_cli.py
to see how to encrypt passwords
"""
user_data = my_users.get(user["username"])
if not user_data:
return False # <--- invalid credentials
elif user_data.get("password") == user["password"]:
return True # <--- user is logged in!
return False # <--- invalid credentials | Check if user exists and its credentials.
Take a look at encrypt_app.py and encrypt_cli.py
to see how to encrypt passwords | check_my_users | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/app.py | MIT |
def be_admin(username):
"""Validator to check if user has admin role"""
user_data = my_users.get(username)
if not user_data or "admin" not in user_data.get("roles", []):
return "User does not have admin role" | Validator to check if user has admin role | be_admin | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/app.py | MIT |
def have_approval(username):
"""Validator: all users approved, return None"""
return | Validator: all users approved, return None | have_approval | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/app.py | MIT |
def create_user(**data):
"""Creates user with encrypted password"""
if "username" not in data or "password" not in data:
raise ValueError("username and password are required.")
# Hash the user password
data["password"] = generate_password_hash(
data.pop("password"), method="pbkdf2:sha256"
)
# Here you insert the `data` in your users database
# for this simple example we are recording in a json file
db_users = json.load(open("users.json"))
# add the new created user to json
db_users[data["username"]] = data
# commit changes to database
json.dump(db_users, open("users.json", "w"))
return data | Creates user with encrypted password | create_user | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def with_app(f):
"""Calls function passing app as first argument"""
@wraps(f)
def decorator(*args, **kwargs):
app = create_app()
configure_extensions(app)
configure_views(app)
return f(app=app, *args, **kwargs)
return decorator | Calls function passing app as first argument | with_app | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def main():
"""Flask Simple Login Example App""" | Flask Simple Login Example App | main | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def adduser(app, username, password):
"""Add new user with admin access"""
with app.app_context():
create_user(username=username, password=password)
click.echo("user created!") | Add new user with admin access | adduser | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def runserver(app=None, reloader=None, debug=None, host=None, port=None):
"""Run the Flask development server i.e. app.run()"""
debug = debug or app.config.get("DEBUG", False)
reloader = reloader or app.config.get("RELOADER", False)
host = host or app.config.get("HOST", "127.0.0.1")
port = port or app.config.get("PORT", 5000)
app.run(use_reloader=reloader, debug=debug, host=host, port=port) | Run the Flask development server i.e. app.run() | runserver | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/manage.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/manage.py | MIT |
def from_current_app(cls, label):
"""Helper to get messages from Flask's current_app"""
return current_app.extensions["simplelogin"].messages.get(label) | Helper to get messages from Flask's current_app | from_current_app | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def default_login_checker(user):
"""user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''}
"""
username = user.get("username")
password = user.get("password")
the_username = os.environ.get(
"SIMPLELOGIN_USERNAME", current_app.config.get("SIMPLELOGIN_USERNAME", "admin")
)
the_password = os.environ.get(
"SIMPLELOGIN_PASSWORD", current_app.config.get("SIMPLELOGIN_PASSWORD", "secret")
)
if username == the_username and password == the_password:
return True
return False | user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''} | default_login_checker | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def is_logged_in(username=None):
"""Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list"""
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return "simple_logged_in" in session and get_username() in username
return "simple_logged_in" in session | Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list | is_logged_in | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def get_username():
"""Get current logged in username"""
return session.get("simple_username") | Get current logged in username | get_username | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return Message.from_current_app("auth_error").format(error), 403 | Return in the first validation error, else return None | login_required.check | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def simple_decorator(*args, **kwargs):
"""This is for when decorator is @login_required"""
return dispatch(function, *args, **kwargs) | This is for when decorator is @login_required | login_required.simple_decorator | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def decorator(f):
"""This is for when decorator is @login_required(...)"""
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap | This is for when decorator is @login_required(...) | login_required.decorator | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function])
"""
if function and not callable(function):
raise ValueError(
"Decorator receives only named arguments, "
'try login_required(username="foo")'
)
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return Message.from_current_app("auth_error").format(error), 403
def dispatch(fun, *args, **kwargs):
if basic and request.is_json:
return dispatch_basic_auth(fun, *args, **kwargs)
if is_logged_in(username=username):
return check(must) or fun(*args, **kwargs)
elif is_logged_in():
return Message.from_current_app("access_denied"), 403
else:
SimpleLogin.flash("login_required")
return redirect(url_for("simplelogin.login", next=request.path))
def dispatch_basic_auth(fun, *args, **kwargs):
simplelogin = current_app.extensions["simplelogin"]
auth_response = simplelogin.basic_auth()
if auth_response is True:
return check(must) or fun(*args, **kwargs)
else:
return auth_response
if function:
@wraps(function)
def simple_decorator(*args, **kwargs):
"""This is for when decorator is @login_required"""
return dispatch(function, *args, **kwargs)
return simple_decorator
def decorator(f):
"""This is for when decorator is @login_required(...)"""
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap
return decorator | Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function]) | login_required | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def login_checker(self, f):
"""To set login_checker as decorator:
@simple.login_checher
def foo(user): ...
"""
self._login_checker = f
return f | To set login_checker as decorator:
@simple.login_checher
def foo(user): ... | login_checker | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def basic_auth(self, response=None):
"""Support basic_auth via /login or login_required(basic=True)"""
auth = request.authorization
if auth and self._login_checker(
{"username": auth.username, "password": auth.password}
):
session["simple_logged_in"] = True
session["simple_basic_auth"] = True
session["simple_username"] = auth.username
return response or True
else:
headers = {"WWW-Authenticate": 'Basic realm="Login Required"'}
return "Invalid credentials", 401, headers | Support basic_auth via /login or login_required(basic=True) | basic_auth | python | sajjadium/ctf-archives | ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py | MIT |
def append_PKCS7_padding(s):
"""return s padded to a multiple of 16-bytes by PKCS7 padding"""
numpads = 16 - (len(s)%16)
return s + numpads*chr(numpads) | return s padded to a multiple of 16-bytes by PKCS7 padding | append_PKCS7_padding | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def strip_PKCS7_padding(s):
"""return s stripped of PKCS7 padding"""
if len(s)%16 or not s:
raise(ValueError("String of len %d can't be PCKS7-padded" % len(s)))
numpads = ord(s[-1])
if numpads > 16:
raise(ValueError("String ending with %r can't be PCKS7-padded" % s[-1]))
return s[:-numpads] | return s stripped of PKCS7 padding | strip_PKCS7_padding | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def getSBoxValue(self,num):
"""Retrieves a given S-Box Value"""
return self.sbox[num] | Retrieves a given S-Box Value | getSBoxValue | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def getSBoxInvert(self,num):
"""Retrieves a given Inverted S-Box Value"""
return self.rsbox[num] | Retrieves a given Inverted S-Box Value | getSBoxInvert | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def rotate(self, word):
""" Rijndael's key schedule rotate operation.
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
Word is an char list of size 4 (32 bits overall).
"""
return word[1:] + word[:1] | Rijndael's key schedule rotate operation.
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
Word is an char list of size 4 (32 bits overall). | rotate | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def getRconValue(self, num):
"""Retrieves a given Rcon Value"""
return self.Rcon[num] | Retrieves a given Rcon Value | getRconValue | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def core(self, word, iteration):
"""Key schedule core."""
# rotate the 32-bit word 8 bits to the left
word = self.rotate(word)
# apply S-Box substitution on all 4 parts of the 32-bit word
for i in range(4):
word[i] = self.getSBoxValue(word[i])
# XOR the output of the rcon operation with i to the first part
# (leftmost) only
word[0] = word[0] ^ self.getRconValue(iteration)
return word | Key schedule core. | core | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def expandKey(self, key, size, expandedKeySize):
"""Rijndael's key expansion.
Expands an 128,192,256 key into an 176,208,240 bytes key
expandedKey is a char list of large enough size,
key is the non-expanded key.
"""
# current expanded keySize, in bytes
currentSize = 0
rconIteration = 1
expandedKey = [0] * expandedKeySize
# set the 16, 24, 32 bytes of the expanded key to the input key
for j in range(size):
expandedKey[j] = key[j]
currentSize += size
while currentSize < expandedKeySize:
# assign the previous 4 bytes to the temporary value t
t = expandedKey[currentSize-4:currentSize]
# every 16,24,32 bytes we apply the core schedule to t
# and increment rconIteration afterwards
if currentSize % size == 0:
t = self.core(t, rconIteration)
rconIteration += 1
# For 256-bit keys, we add an extra sbox to the calculation
if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
for l in range(4): t[l] = self.getSBoxValue(t[l])
# We XOR t with the four-byte block 16,24,32 bytes before the new
# expanded key. This becomes the next four bytes in the expanded
# key.
for m in range(4):
expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
t[m]
currentSize += 1
return expandedKey | Rijndael's key expansion.
Expands an 128,192,256 key into an 176,208,240 bytes key
expandedKey is a char list of large enough size,
key is the non-expanded key. | expandKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def addRoundKey(self, state, roundKey):
"""Adds (XORs) the round key to the state."""
for i in range(16):
state[i] ^= roundKey[i]
return state | Adds (XORs) the round key to the state. | addRoundKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def createRoundKey(self, expandedKey, roundKeyPointer):
"""Create a round key.
Creates a round key from the given expanded key and the
position within the expanded key.
"""
roundKey = [0] * 16
for i in range(4):
for j in range(4):
roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
return roundKey | Create a round key.
Creates a round key from the given expanded key and the
position within the expanded key. | createRoundKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def galois_multiplication(self, a, b):
"""Galois multiplication of 8 bit characters a and b."""
p = 0
for counter in range(8):
if b & 1: p ^= a
hi_bit_set = a & 0x80
a <<= 1
# keep a 8 bit
a &= 0xFF
if hi_bit_set:
a ^= 0x1b
b >>= 1
return p | Galois multiplication of 8 bit characters a and b. | galois_multiplication | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def encryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
"""encrypt `data` using `key`
`key` should be a string of bytes.
returned cipher is a string of bytes prepended with the initialization
vector.
"""
key = map(ord, key)
if mode == AESModeOfOperation.modeOfOperation["CBC"]:
data = append_PKCS7_padding(data)
keysize = len(key)
assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
# create a new iv using random data
iv = [ord(i) for i in os.urandom(16)]
moo = AESModeOfOperation()
(mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
# With padding, the original length does not need to be known. It's a bad
# idea to store the original message length.
# prepend the iv.
return ''.join(map(chr, iv)) + ''.join(map(chr, ciph)) | encrypt `data` using `key`
`key` should be a string of bytes.
returned cipher is a string of bytes prepended with the initialization
vector. | encryptData | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def decryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
"""decrypt `data` using `key`
`key` should be a string of bytes.
`data` should have the initialization vector prepended as a string of
ordinal values.
"""
key = map(ord, key)
keysize = len(key)
assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
# iv is first 16 bytes
iv = map(ord, data[:16])
data = map(ord, data[16:])
moo = AESModeOfOperation()
decr = moo.decrypt(data, None, mode, key, keysize, iv)
if mode == AESModeOfOperation.modeOfOperation["CBC"]:
decr = strip_PKCS7_padding(decr)
return decr | decrypt `data` using `key`
`key` should be a string of bytes.
`data` should have the initialization vector prepended as a string of
ordinal values. | decryptData | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def generateRandomKey(keysize):
"""Generates a key from random data of length `keysize`.
The returned key is a string of bytes.
"""
if keysize not in (16, 24, 32):
emsg = 'Invalid keysize, %s. Should be one of (16, 24, 32).'
raise(ValueError, emsg % keysize)
return os.urandom(keysize) | Generates a key from random data of length `keysize`.
The returned key is a string of bytes. | generateRandomKey | python | sajjadium/ctf-archives | ctfs/UTCTF/2023/crypto/Affinity/aes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UTCTF/2023/crypto/Affinity/aes.py | MIT |
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Login = channel.unary_unary(
'/tamuctf.EchoService/Login',
request_serializer=protobuf__pb2.Request.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.Logout = channel.unary_unary(
'/tamuctf.EchoService/Logout',
request_serializer=protobuf__pb2.ServiceUser.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.SendEcho = channel.unary_unary(
'/tamuctf.EchoService/SendEcho',
request_serializer=protobuf__pb2.Request.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.ReceiveEcho = channel.unary_unary(
'/tamuctf.EchoService/ReceiveEcho',
request_serializer=protobuf__pb2.ServiceUser.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
) | Constructor.
Args:
channel: A grpc.Channel. | __init__ | python | sajjadium/ctf-archives | ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2_grpc.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2_grpc.py | MIT |
def aes_cbc_encrypt(msg: bytes, key: bytes) -> bytes:
"""
Encrypts a message using AES in CBC mode.
Parameters:
msg (bytes): The plaintext message to encrypt.
key (bytes): The encryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The initialization vector (IV) concatenated with the encrypted ciphertext.
"""
if len(key) not in {16, 24, 32}:
raise ValueError("Key must be 16, 24, or 32 bytes long.")
# Generate a random Initialization Vector (IV)
iv = os.urandom(16)
# Pad the message to be a multiple of the block size (16 bytes for AES)
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_msg = padder.update(msg) + padder.finalize()
# Create the AES cipher in CBC mode
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Encrypt the padded message
ciphertext = encryptor.update(padded_msg) + encryptor.finalize()
# Return IV concatenated with ciphertext
return iv + ciphertext | Encrypts a message using AES in CBC mode.
Parameters:
msg (bytes): The plaintext message to encrypt.
key (bytes): The encryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The initialization vector (IV) concatenated with the encrypted ciphertext. | aes_cbc_encrypt | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | MIT |
def aes_cbc_decrypt(encrypted_msg: bytes, key: bytes) -> bytes:
"""
Decrypts a message encrypted using AES in CBC mode.
Parameters:
encrypted_msg (bytes): The encrypted message (IV + ciphertext).
key (bytes): The decryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The original plaintext message.
"""
if len(key) not in {16, 24, 32}:
raise ValueError("Key must be 16, 24, or 32 bytes long.")
# Extract the IV (first 16 bytes) and ciphertext (remaining bytes)
iv = encrypted_msg[:16]
ciphertext = encrypted_msg[16:]
# Create the AES cipher in CBC mode
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
# Decrypt the ciphertext
padded_msg = decryptor.update(ciphertext) + decryptor.finalize()
# Remove padding from the decrypted message
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
msg = unpadder.update(padded_msg) + unpadder.finalize()
return msg | Decrypts a message encrypted using AES in CBC mode.
Parameters:
encrypted_msg (bytes): The encrypted message (IV + ciphertext).
key (bytes): The decryption key (must be 16, 24, or 32 bytes long).
Returns:
bytes: The original plaintext message. | aes_cbc_decrypt | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py | MIT |
def place_order():
if 'cart' not in session or not session['cart']:
flash('購物車是空的', 'warning')
return redirect(url_for('cart'))
try:
cursor = db.cursor(dictionary=True)
# 計算訂單金額
total_amount = sum(item['price'] * item['quantity'] for item in session['cart'])
shipping_fee = 100 if total_amount < 3000 else 0
discount_amount = 0
# 處理折扣碼
discount_code = request.form.get('discount_code')
if discount_code:
cursor.execute("""
SELECT * FROM discount_codes
WHERE code = %s
AND is_active = TRUE
AND start_date <= NOW()
AND end_date >= NOW()
AND (usage_limit IS NULL OR used_count < usage_limit)
""", (discount_code,))
discount = cursor.fetchone()
if discount and total_amount >= discount['min_purchase']:
if discount['discount_type'] == 'percentage':
discount_amount = total_amount * (discount['discount_value'] / 100)
else:
discount_amount = discount['discount_value']
# 更新折扣碼使用次數
cursor.execute("""
UPDATE discount_codes
SET used_count = used_count + 1
WHERE id = %s
""", (discount['id'],))
final_amount = total_amount + shipping_fee - discount_amount
# 創建訂單
cursor.execute("""
INSERT INTO orders (
user_id,
total_amount,
shipping_fee,
recipient_name,
recipient_phone,
recipient_email,
shipping_address,
note,
payment_method
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
session.get('user_id'),
final_amount,
shipping_fee,
request.form.get('name'),
request.form.get('phone'),
request.form.get('email'),
request.form.get('address'),
request.form.get('note'),
request.form.get('payment')
))
order_id = cursor.lastrowid
# 保存訂單項目
for item in session['cart']:
# 插入訂單項目
cursor.execute("""
INSERT INTO order_items (
order_id,
product_id,
quantity,
price,
is_custom
) VALUES (%s, %s, %s, %s, %s)
""", (
order_id,
item['id'],
item['quantity'],
item['price'],
item['type'] == 'custom'
))
# 獲取插入的訂單項目 ID
item_id = cursor.lastrowid
# 如果是客製化商品,保存配置
if item['type'] == 'custom' and 'custom_components' in item:
for category, component in item['custom_components'].items():
cursor.execute("""
INSERT INTO order_configurations (
order_item_id,
category_name,
component_name
) VALUES (%s, %s, %s)
""", (
item_id, # 使用正確的訂單項目 ID
category,
component
))
# 如果使用了折扣碼,記錄使用情況
if discount_code and discount:
cursor.execute("""
INSERT INTO discount_usage (
discount_code_id, order_id, user_id
) VALUES (%s, %s, %s)
""", (discount['id'], order_id, session['user_id']))
db.commit()
# 清空購物車
session.pop('cart', None)
flash('訂單已成功建立!', 'success')
return redirect(url_for('order_complete', order_id=order_id))
except Exception as e:
db.rollback()
flash('訂單建立失敗,請重試', 'danger')
print(f"Error: {str(e)}")
return redirect(url_for('checkout')) | , (discount_code,))
discount = cursor.fetchone()
if discount and total_amount >= discount['min_purchase']:
if discount['discount_type'] == 'percentage':
discount_amount = total_amount * (discount['discount_value'] / 100)
else:
discount_amount = discount['discount_value']
# 更新折扣碼使用次數
cursor.execute( | place_order | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | MIT |
def order_detail(order_id):
if 'user_id' not in session:
flash('請先登入', 'danger')
return redirect(url_for('login'))
cursor = db.cursor(dictionary=True)
# 獲取訂單基本信息
cursor.execute("""
SELECT * FROM orders
WHERE id = %s AND user_id = %s
""", (order_id, session['user_id']))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('orders'))
# 獲取訂單項目
cursor.execute("""
SELECT order_items.*, products.name as product_name
FROM order_items
JOIN products ON order_items.product_id = products.id
WHERE order_items.order_id = %s
""", (order_id,))
items = cursor.fetchall()
# 獲取客製化配置
for item in items:
if item['is_custom']:
cursor.execute("""
SELECT category_name, component_name
FROM order_configurations
WHERE order_item_id = %s
""", (item['id'],))
item['configurations'] = cursor.fetchall()
return render_template('order_detail.html', order=order, items=items) | , (order_id, session['user_id']))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('orders'))
# 獲取訂單項目
cursor.execute( | order_detail | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | MIT |
def admin_order_detail(order_id):
cursor = db.cursor(dictionary=True)
# 獲取訂單基本信息
cursor.execute("""
SELECT orders.*, users.username
FROM orders
LEFT JOIN users ON orders.user_id = users.id
WHERE orders.id = %s
""", (order_id,))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('admin_orders'))
# 獲取訂單項目
cursor.execute("""
SELECT order_items.*, products.name as product_name
FROM order_items
JOIN products ON order_items.product_id = products.id
WHERE order_items.order_id = %s
""", (order_id,))
items = cursor.fetchall()
# 獲取客製化配置
for item in items:
if item['is_custom']:
cursor.execute("""
SELECT category_name, component_name
FROM order_configurations
WHERE order_item_id = %s
""", (item['id'],))
item['configurations'] = cursor.fetchall()
return render_template('admin/order_detail.html', order=order, items=items) | , (order_id,))
order = cursor.fetchone()
if not order:
flash('找不到此訂單', 'danger')
return redirect(url_for('admin_orders'))
# 獲取訂單項目
cursor.execute( | admin_order_detail | python | sajjadium/ctf-archives | ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py | MIT |
def score(sid: str):
"""Score viewer"""
title = db().hget(sid, 'title')
link = db().hget(sid, 'link')
if link is None:
flask.flash("Score not found")
return flask.redirect(flask.url_for('upload'))
return flask.render_template("score.html", sid=sid, link=link.decode(), title=title.decode()) | Score viewer | score | python | sajjadium/ctf-archives | ctfs/zer0pts/2023/web/ScoreShare/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2023/web/ScoreShare/service/app.py | MIT |
def authenticate(self):
"""Login prompt"""
username = password = b''
with Timeout(30):
# Receive username
self.response(b"Username: ")
username = self.recvline()
if username is None: return
if username in LOGIN_USERS:
password = LOGIN_USERS[username]
else:
self.response(b"No such a user exists.\n")
return
with Timeout(30):
# Receive password
self.response(b"Password: ")
i = 0
while i < len(password):
c = self._conn.recv(1)
if c == b'':
return
elif c != password[i:i+1]:
self.response(b"Incorrect password.\n")
return
i += 1
if self._conn.recv(1) != b'\n':
self.response(b"Incorrect password.\n")
return
self.response(b"Logged in.\n")
self._auth = True
self._user = username | Login prompt | authenticate | python | sajjadium/ctf-archives | ctfs/zer0pts/2023/misc/NetFS_1/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2023/misc/NetFS_1/server.py | MIT |
def serve(self):
"""Serve files"""
with Timeout(60):
while True:
# Receive filepath
self.response(b"File: ")
filepath = self.recvline()
if filepath is None: return
# Check filepath
if not self.is_admin and \
any(map(lambda name: name in filepath, PROTECTED)):
self.response(b"Permission denied.\n")
continue
# Serve file
try:
f = open(filepath, 'rb')
except FileNotFoundError:
self.response(b"File not found.\n")
continue
except PermissionError:
self.response(b"Permission denied.\n")
continue
except:
self.response(b"System error.\n")
continue
try:
self.response(f.read(MAX_SIZE))
except OSError:
self.response(b"System error.\n")
finally:
f.close() | Serve files | serve | python | sajjadium/ctf-archives | ctfs/zer0pts/2023/misc/NetFS_1/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2023/misc/NetFS_1/server.py | MIT |
def index():
"""Home"""
return flask.render_template(
"index.html",
is_post=False,
title="Create Paste",
sitekey=RECAPTCHA_SITE_KEY
) | Home | index | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def get_post(id):
"""Read a ticket"""
# Get ticket by ID
content = get_redis_conn(DB_TICKET).get(id)
if content is None:
return flask.abort(404, "not found")
# Check if admin
content = json.loads(content)
key = flask.request.args.get("key")
is_admin = isinstance(key, str) and get_key(id) == key
return flask.render_template(
"index.html",
**content,
is_post=True,
panel=f"""
<strong>Hello admin! Your flag is: {FLAG}</strong><br>
<form id="delete-form" method="post" action="/api/delete">
<input name="id" type="hidden" value="{id}">
<input name="key" type="hidden" value="{key}">
<button id="modal-button-delete" type="button">Delete This Post</button>
</form>
""" if is_admin else "",
url=flask.request.url,
sitekey=RECAPTCHA_SITE_KEY
) | Read a ticket | get_post | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_new():
"""Create a new ticket"""
# Get parameters
try:
title = flask.request.form["title"]
content = flask.request.form["content"]
except:
return flask.abort(400, "Invalid request")
# Register a new ticket
id = b64digest(os.urandom(16))[:16]
get_redis_conn(DB_TICKET).set(
id, json.dumps({"title": title, "content": content})
)
return flask.jsonify({"result": "OK",
"message": "Post created! Click here to see your post",
"action": f"{flask.request.url_root}post/{id}"}) | Create a new ticket | api_new | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_delete():
"""Delete a ticket"""
# Get parameters
try:
id = flask.request.form["id"]
key = flask.request.form["key"]
except:
return flask.abort(400, "Invalid request")
if get_key(id) != key:
return flask.abort(401, "Unauthorized")
# Delete
if get_redis_conn(DB_TICKET).delete(id) == 0:
return flask.jsonify({"result": "NG", "message": "Post not found"})
return flask.jsonify({"result": "OK", "message": "This post was successfully deleted"}) | Delete a ticket | api_delete | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def api_report():
"""Reoprt an invitation ticket"""
# Get parameters
try:
url = flask.request.form["url"]
reason = flask.request.form["reason"]
recaptcha_token = flask.request.form["g-recaptcha-response"]
except Exception:
return flask.abort(400, "Invalid request")
# Check reCAPTCHA
score = verify_recaptcha(recaptcha_token)
if score == -1:
return flask.jsonify({"result": "NG", "message": "Recaptcha verify failed"})
if score <= 0.3:
return flask.jsonify({"result": "NG", "message": f"Bye robot (score: {score})"})
# Check URL
parsed = urllib.parse.urlparse(url.split('?', 1)[0])
if len(parsed.query) != 0:
return flask.jsonify({"result": "NG", "message": "Query string is not allowed"})
if f'{parsed.scheme}://{parsed.netloc}/' != flask.request.url_root:
return flask.jsonify({"result": "NG", "message": "Invalid host"})
# Parse path
adapter = app.url_map.bind(flask.request.host)
endpoint, args = adapter.match(parsed.path)
if endpoint != "get_post" or "id" not in args:
return flask.jsonify({"result": "NG", "message": "Invalid endpoint"})
# Check ID
if not get_redis_conn(DB_TICKET).exists(args["id"]):
return flask.jsonify({"result": "NG", "message": "Invalid ID"})
key = get_key(args["id"])
message = f"URL: {url}?key={key}\nReason: {reason}"
try:
get_redis_conn(DB_BOT).rpush(
'report', message[:MESSAGE_LENGTH_LIMIT]
)
except Exception:
return flask.jsonify({"result": "NG", "message": "Post failed"})
return flask.jsonify({"result": "OK", "message": "Successfully reported"}) | Reoprt an invitation ticket | api_report | python | sajjadium/ctf-archives | ctfs/zer0pts/2022/web/disco-party/web/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/zer0pts/2022/web/disco-party/web/app.py | MIT |
def angle_between(p1, p2):
""" Returns the angle in radians between two points """
angle = np.arctan2(p2[1] - p1[1], p2[0] - p1[0])
return angle | Returns the angle in radians between two points | angle_between | python | sajjadium/ctf-archives | ctfs/corCTF/2023/web/msfrognymize/src/anonymize_faces.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2023/web/msfrognymize/src/anonymize_faces.py | MIT |
def step(x: Pair, n: int):
'''Performs n steps to x.'''
return apply(x, calculate(n)) | Performs n steps to x. | step | python | sajjadium/ctf-archives | ctfs/corCTF/2024/crypto/steps/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/crypto/steps/main.py | MIT |
def generate_random_board(n: int) -> list[int]:
"""
Generate a random n x n Lights Out board.
Args:
n (int): The size of the board (n x n).
Returns:
list[int]: A list representing the board, where each element
is either 0 (off) or 1 (on).
"""
board = [random.randint(0, 1) for _ in range(n * n)]
return board | Generate a random n x n Lights Out board.
Args:
n (int): The size of the board (n x n).
Returns:
list[int]: A list representing the board, where each element
is either 0 (off) or 1 (on). | generate_random_board | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def create_vector_representations(n: int) -> list[list[int]]:
"""
Create vector representations for each position on the n x n board.
Args:
n (int): The size of the board (n x n).
Returns:
list[list[int]]: A list of vectors representing the effect of
toggling each light.
"""
vectors = []
for i in range(n * n):
vector = [0] * (n * n)
vector[i] = 1
if i % n != 0:
vector[i - 1] = 1 # left
if i % n != n - 1:
vector[i + 1] = 1 # right
if i >= n:
vector[i - n] = 1 # up
if i < n * (n - 1):
vector[i + n] = 1 # down
vectors.append(vector)
return vectors | Create vector representations for each position on the n x n board.
Args:
n (int): The size of the board (n x n).
Returns:
list[list[int]]: A list of vectors representing the effect of
toggling each light. | create_vector_representations | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def create_augmented_matrix(vectors: list[list[int]],
board: list[int]) -> list[list[int]]:
"""
Create an augmented matrix from the vectors and board state.
Args:
vectors (list[list[int]]): The vector representations.
board (list[int]): The current state of the board.
Returns:
list[list[int]]: The augmented matrix.
"""
matrix = [vec + [board[i]] for i, vec in enumerate(vectors)]
return matrix | Create an augmented matrix from the vectors and board state.
Args:
vectors (list[list[int]]): The vector representations.
board (list[int]): The current state of the board.
Returns:
list[list[int]]: The augmented matrix. | create_augmented_matrix | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def print_board(board: list[int], n: int) -> str:
"""
Generate a string representation of the n x n board.
Args:
board (list[int]): The board state.
n (int): The size of the board (n x n).
Returns:
str: The string representation of the board.
"""
board_string = ""
for i in range(n):
row = ""
for j in range(n):
row += "#" if board[i * n + j] else "."
board_string += row + "\n"
return board_string | Generate a string representation of the n x n board.
Args:
board (list[int]): The board state.
n (int): The size of the board (n x n).
Returns:
str: The string representation of the board. | print_board | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def gauss_jordan_elimination(matrix: list[list[int]]) -> list[list[int]]:
"""
Perform Gauss-Jordan elimination on the given matrix to produce its
Reduced Row Echelon Form (RREF).
Args:
matrix (list[list[int]]): The matrix to be reduced.
Returns:
list[list[int]]: The matrix in RREF.
"""
rows, cols = len(matrix), len(matrix[0])
r = 0
for c in range(cols - 1):
if r >= rows:
break
pivot = None
for i in range(r, rows):
if matrix[i][c] == 1:
pivot = i
break
if pivot is None:
continue
if r != pivot:
matrix[r], matrix[pivot] = matrix[pivot], matrix[r]
for i in range(rows):
if i != r and matrix[i][c] == 1:
for j in range(cols):
matrix[i][j] ^= matrix[r][j]
r += 1
return matrix | Perform Gauss-Jordan elimination on the given matrix to produce its
Reduced Row Echelon Form (RREF).
Args:
matrix (list[list[int]]): The matrix to be reduced.
Returns:
list[list[int]]: The matrix in RREF. | gauss_jordan_elimination | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def is_solvable(matrix: list[list[int]]) -> bool:
"""
Check if the given augmented matrix represents a solvable system.
Args:
matrix (list[list[int]]): The augmented matrix.
Returns:
bool: True if the system is solvable, False otherwise.
"""
rref = gauss_jordan_elimination(matrix)
for row in rref:
if row[-1] == 1 and all(val == 0 for val in row[:-1]):
return False
return True | Check if the given augmented matrix represents a solvable system.
Args:
matrix (list[list[int]]): The augmented matrix.
Returns:
bool: True if the system is solvable, False otherwise. | is_solvable | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def get_solution(board: list[int], n: int) -> list[int] | None:
"""
Get a solution for the Lights Out board if it exists.
Args:
board (list[int]): The current state of the board.
n (int): The size of the board (n x n).
Returns:
list[int] | None: A list representing the solution, or None
if no solution exists.
"""
vectors = create_vector_representations(n)
matrix = create_augmented_matrix(vectors, board)
if not is_solvable(matrix):
return None
rref_matrix = gauss_jordan_elimination(matrix)
# DEBUG
# x = [row[-1] for row in rref_matrix[:n * n]]
# xx = ""
# for i in x:
# xx += "#" if i else "."
# print(xx)
# END DEBUG
return [row[-1] for row in rref_matrix[:n * n]] | Get a solution for the Lights Out board if it exists.
Args:
board (list[int]): The current state of the board.
n (int): The size of the board (n x n).
Returns:
list[int] | None: A list representing the solution, or None
if no solution exists. | get_solution | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def check_solution(board: list[int], solution: list[int], n: int) -> bool:
"""
Check if the given solution solves the Lights Out board.
Args:
board (list[int]): The current state of the board.
solution (list[int]): The proposed solution.
n (int): The size of the board (n x n).
Returns:
bool: True if the solution is correct, False otherwise.
"""
for i in range(n * n):
if solution[i] == 1:
board[i] ^= 1
if i % n != 0:
board[i - 1] ^= 1 # left
if i % n != n - 1:
board[i + 1] ^= 1 # right
if i >= n:
board[i - n] ^= 1 # up
if i < n * (n - 1):
board[i + n] ^= 1 # down
return all(val == 0 for val in board) | Check if the given solution solves the Lights Out board.
Args:
board (list[int]): The current state of the board.
solution (list[int]): The proposed solution.
n (int): The size of the board (n x n).
Returns:
bool: True if the solution is correct, False otherwise. | check_solution | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def main() -> None:
"""
Generates a Lights Out board, sends it to the client,
and checks the client's solution.
"""
print(
"\nWelcome to Lights Out!\n"
"\nThe goal of the game is to turn off all the lights on "
"the board.\n"
"You can toggle any light by entering its position in "
"a string format,\n"
"where # represents ON and . represents OFF.\n"
"Each toggle will also flip the state of its adjacent "
"lights (above, below, left, right).\n"
"Try to turn off all the lights to win!\n"
"\nEnter your solution as a string of #s and .s "
"for ALL board positions, read "
"from left to right, top to bottom (e.g., ..##...#.)\n"
"\nEXAMPLE\n"
"To solve the board:\n\n"
"\t###\n\t#.#\n\t.##\n\n"
"Your solution would be: ..##...#.\n\n\n")
sys.stdout.flush()
while True:
n = random.randint(15, 25)
board = generate_random_board(n)
solution = get_solution(board, n)
if solution is None:
continue
print("\nLights Out Board:\n\n")
print(print_board(board, n))
print("\nYour Solution: ")
sys.stdout.flush()
start_time = time.time()
user_input = input()[:1024].strip()
if time.time() - start_time > 10:
print("\n\nTime out. Generating a new board...\n")
sys.stdout.flush()
continue
user_solution = [1 if c == "#" else 0 for c in user_input]
if len(user_solution) == n * n and check_solution(
board[:], user_solution, n):
print(os.environ.get("FLAG", "corctf{test_flag}"))
sys.stdout.flush()
break
print("\n\nIncorrect solution. Generating a new board...\n")
sys.stdout.flush() | Generates a Lights Out board, sends it to the client,
and checks the client's solution. | main | python | sajjadium/ctf-archives | ctfs/corCTF/2024/misc/lights_out/lights_out.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/corCTF/2024/misc/lights_out/lights_out.py | MIT |
def pick_user(connected, ssh_connection):
"""Pick an available user"""
uids = set(range(MIN_UID, MAX_UID)) - set(connected)
if not uids:
logger.error("no uid available")
sys.exit(1)
uid = sorted(uids)[0]
try:
create_user(uid, uid, ssh_connection)
except FileExistsError:
connected.append(uid)
return pick_user(connected, ssh_connection)
return uid | Pick an available user | pick_user | python | sajjadium/ctf-archives | ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | MIT |
def connected_uids():
"""Return a list of connected users."""
# walk /proc/ to retrieve running processes
uids = set([])
for pid in os.listdir("/proc/"):
if not re.match("^[0-9]+$", pid):
continue
try:
uid = os.stat(f"/proc/{pid}").st_uid
except FileNotFoundError:
continue
if uid in range(MIN_UID, MAX_UID):
uids.add(uid)
return list(uids) | Return a list of connected users. | connected_uids | python | sajjadium/ctf-archives | ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py | MIT |
def device_response(callback, **kwargs):
"""
Stream the response since the communication with the device is not instant.
It prevents concurrent HTTP requests from being blocked.
"""
def generate_device_response(callback, **kwargs):
# force headers to be sent
yield b""
# generate reponse
yield json.dumps(callback(**kwargs)).encode()
return Response(stream_with_context(generate_device_response(callback, **kwargs)), content_type="application/json") | Stream the response since the communication with the device is not instant.
It prevents concurrent HTTP requests from being blocked. | device_response | python | sajjadium/ctf-archives | ctfs/LedgerDonjon/2021/crypto/magic-otp/challenge/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LedgerDonjon/2021/crypto/magic-otp/challenge/app.py | MIT |
def fortune(self, msg):
""" Generate fortune ticket flavour text. """
nums = [int.from_bytes(msg[i:i+2],'big') for i in range(0,len(msg),2)]
luck = ['']
spce = b'\x30\x00'.decode('utf-16-be')
for num in nums:
if num >= 0x4e00 and num <= 0x9fd6:
luck[-1] += num.to_bytes(2,'big').decode('utf-16-be')
else:
luck += ['']
luck += ['']
maxlen = max([len(i) for i in luck])
for i in range(len(luck)):
luck[i] += spce * (maxlen - len(luck[i]))
card = [spce.join([luck[::-1][i][j] for i in range(len(luck))]) for j in range(maxlen)]
return card | Generate fortune ticket flavour text. | fortune | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | MIT |
def print_card(self, cip, card):
""" Print fortune ticket to terminal. """
upper_hex = long_to_bytes(cip).hex().upper()
fwascii = list(''.join([(ord(i)+65248).to_bytes(2,'big').decode('utf-16-be') for i in list(upper_hex)]))
enclst = [''.join(fwascii[i:i+len(card[0])]) for i in range(0, len(fwascii), len(card[0]))]
# Frame elements
sp = b'\x30\x00'.decode('utf-16-be')
dt = b'\x30\xfb'.decode('utf-16-be')
hl = b'\x4e\x00'.decode('utf-16-be')
vl = b'\xff\x5c'.decode('utf-16-be')
# Print fortune ticket
enclst[-1] += sp*(len(card[0])-len(enclst[-1]))
print()
print(2*sp + dt + hl*(len(card[0])+2) + dt)
print(2*sp + vl + dt + hl*len(card[0]) + dt + vl)
for row in card:
print(2*sp + 2*vl + row + 2*vl)
print(2*sp + vl + dt + hl*len(card[0]) + dt + vl)
for row in enclst:
print(2*sp + vl + sp + row + sp + vl)
print(2*sp + dt + hl*(len(card[0])+2) + dt)
print() | Print fortune ticket to terminal. | print_card | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Shrine_of_the_Sweating_Buddha/pravrallier.py | MIT |
def parse(polynomial):
'''
TODO: Parse polynomial
For example, parse("x^3 + 2x^2 - x + 1") should return [1,2,-1,1]
''' | TODO: Parse polynomial
For example, parse("x^3 + 2x^2 - x + 1") should return [1,2,-1,1] | parse | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Vietas_Poly/template.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Vietas_Poly/template.py | MIT |
def __init__(self, maptype, params):
"""Initialise map object"""
if maptype.lower() in ['l','lm','logic']:
self.f = self.__LOGI
elif maptype.lower() in ['e','el','elm','extended logic']:
self.f = self.__EXT_LOGI
else:
raise ValueError('Invalid Map Type.')
try:
self.p = list(params)
except:
self.p = [params] | Initialise map object | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __LOGI(self, x): # <--- p in [3.7, 4]
"""Logistic map"""
return self.p[0] * x * (1 - x) | Logistic map | __LOGI | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __EXT_LOGI(self, x): # <--- p in [2, 4]
"""Extended logistic map"""
if x < 0.5:
return self.__LOGI(x)
else:
return self.p[0] * (x * (x - 1) + 1 / 4) | Extended logistic map | __EXT_LOGI | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def sample(self, x_i, settles, samples):
"""Generates outputs after certain number of settles"""
x = x_i
for _ in range(settles):
x = self.f(x)
ret = []
for _ in range(samples):
x = self.f(x)
ret += [x]
return ret | Generates outputs after certain number of settles | sample | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __init__(self, key=None, iv=None):
"""Initialise Mowhock class object."""
if (key is None) or (len(key) != 64):
key = os.urandom(32).hex()
self.key = key
if (iv is None) or (len(iv) != 16):
iv = os.urandom(8).hex()
self.iv = iv
self.maps = self.map_schedule()
self.buffer_raw = None
self.buffer_byt = None | Initialise Mowhock class object. | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def key_schedule(self):
"""Convert key into 8 round subkeys."""
KL, KR = self.key[:32], self.key[32:]
VL, VR = self.ctr[:8], self.ctr[8:]
HL, HR = [sha256(bytes.fromhex(i)).digest() for i in [VL+KL,VR+KL]]
hlbits, hrbits = ['{:0256b}'.format(int.from_bytes(H,'big')) for H in [HL,HR]]
bitweave = ''.join([hlbits[i]+hrbits[i] for i in range(256)])
subkeys = [int(bitweave[i:i+64],2) for i in range(0,512,64)]
return [self.read_subkey(i) for i in subkeys] | Convert key into 8 round subkeys. | key_schedule | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def map_schedule(self):
"""Convert IV into 8 maps with iv-dependent parameters"""
iv = bytes.fromhex(self.iv)
maps = [
Map('L', iv[0]*(4.00 - 3.86)/255 + 3.86),
Map('L', iv[1]*(4.00 - 3.86)/255 + 3.86),
Map('L', iv[2]*(4.00 - 3.86)/255 + 3.86),
Map('L', iv[3]*(4.00 - 3.86)/255 + 3.86),
Map('E', iv[4]*(4.00 - 3.55)/255 + 3.55),
Map('E', iv[5]*(4.00 - 3.55)/255 + 3.55),
Map('E', iv[6]*(4.00 - 3.55)/255 + 3.55),
Map('E', iv[7]*(4.00 - 3.55)/255 + 3.55),
]
order = self.hop_order(int(self.key[:2],16),8)
return [maps[i] for i in order] | Convert IV into 8 maps with iv-dependent parameters | map_schedule | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def read_subkey(self, subkey):
"""Convert subkey int from key schedule to orbit parameters."""
# Integer to bits
byts = subkey.to_bytes(8, 'big')
bits = ''.join(['{:08b}'.format(i) for i in byts])
# Read key elements
hpsn = int(bits[0:8],2)
seed = float('0.00'+str(int(bits[8:32],2)))
offset = float('0.0000'+str(int(bits[32:48],2)))
settles = int(bits[48:56],2) + 512
orbits = int(bits[56:60],2) + 4
samples = int(bits[60:64],2) + 4
# Processing key elements
hopord = self.hop_order(hpsn,orbits)
x_i = [seed + offset*i for i in hopord]
# Return subkey dictionary
return {
'order' : hopord,
'hpsn' : hpsn,
'seed' : seed,
'offset' : offset,
'x_i' : x_i,
'settles' : settles,
'orbits' : orbits,
'samples' : samples
} | Convert subkey int from key schedule to orbit parameters. | read_subkey | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def hop_order(self, hpsn, orbits):
"""Determine orbit hop order"""
i = 1
ret = []
while len(ret) < orbits:
o = (pow(hpsn,i,256)+i) % orbits
if o not in ret:
ret += [o]
i += 1
return ret | Determine orbit hop order | hop_order | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def ctr_increment(self):
"""Increments IV and reschedules key."""
self.ctr = (int(self.ctr,16) + 1).to_bytes(8, 'big').hex()
self.subkeys = self.key_schedule()
self.fill_buffers() | Increments IV and reschedules key. | ctr_increment | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def fill_buffers(self, save_raw=False):
"""Fills internal buffer with pseudorandom bytes"""
self.buffer_raw = []
self.buffer_byt = []
raw = []
for i in range(8):
settles = self.subkeys[i]['settles']
samples = self.subkeys[i]['samples']
for x_i in self.subkeys[i]['x_i']:
raw += self.maps[i].sample(x_i, settles, samples)
if save_raw:
self.buffer_raw += raw
bitstr = ['{:032b}'.format(int(i*2**53)) for i in raw]
byt = []
for b32 in bitstr:
byt += [int(b32[:8],2) ^ int(b32[16:24],2), int(b32[8:16],2) ^ int(b32[24:32],2)]
self.buffer_byt += bytes(byt) | Fills internal buffer with pseudorandom bytes | fill_buffers | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def encrypt(self, msg):
"""Encrypts a message through the power of chaos"""
# Fill initial buffers
self.ctr = self.iv
self.subkeys = self.key_schedule()
self.fill_buffers()
# Encrypt (increment and refill buffers if necessary)
cip = b''
if type(msg) == str:
msg = bytes.fromhex(msg)
for byt in msg:
try:
cip += bytes( [byt ^ self.buffer_byt.pop(0)] )
except:
self.ctr_increment()
cip += bytes( [byt ^ self.buffer_byt.pop(0)] )
# Return IV and ciphertext
return self.iv + cip.hex() | Encrypts a message through the power of chaos | encrypt | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Mowhock/mowhock.py | MIT |
def __init__(self, key):
""" Initialise the bee colony. """
self.fields = self.plant_flowers(key)
self.nectar = None
self.collect() | Initialise the bee colony. | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def plant_flowers(self, key):
""" Plant flowers around the beehive. """
try:
if type(key) != bytes:
key = bytes.fromhex(key)
return [FlowerField(key[i:i+6]) for i in range(0,36,6)]
except:
raise ValueError('Invalid Key!') | Plant flowers around the beehive. | plant_flowers | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def collect(self):
""" Collect nectar from the closest flowers. """
A,B,C,D,E,F = [i.flowers for i in self.fields]
self.nectar = [A[2]^^B[4],B[3]^^C[5],C[4]^^D[0],D[5]^^E[1],E[0]^^F[2],F[1]^^A[3]] | Collect nectar from the closest flowers. | collect | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def swap_petals(F1, F2, i1, i2):
""" Swap the petals of two flowers. """
F1.flowers[i1], F2.flowers[i2] = F2.flowers[i2], F1.flowers[i1] | Swap the petals of two flowers. | cross_breed.swap_petals | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def cross_breed(self):
""" Cross-breed the outermost bordering flowers. """
def swap_petals(F1, F2, i1, i2):
""" Swap the petals of two flowers. """
F1.flowers[i1], F2.flowers[i2] = F2.flowers[i2], F1.flowers[i1]
A,B,C,D,E,F = self.fields
swap_petals(A,B,1,5)
swap_petals(B,C,2,0)
swap_petals(C,D,3,1)
swap_petals(D,E,4,2)
swap_petals(E,F,5,3)
swap_petals(F,A,0,4) | Cross-breed the outermost bordering flowers. | cross_breed | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.